wireshape
Strongly typed HTTP calls on top of requests.
You declare the type you send and the type you expect back as
pydantic models, and wireshape handles the JSON
serialization and validation. Field-level details such as wire names, defaults,
exclusions, constraints and date formats can be adjusted from a TOML file
without touching the models.
Requires Python 3.12+.
For a complete, runnable walkthrough, see
examples/employee_directory. It talks to two
incompatible versions of an HR API over real HTTP using one set of models.
Quick start
from pydantic import BaseModel
from wireshape import Client
class NewUser(BaseModel):
name: str
email: str
class User(BaseModel):
id: int
name: str
email: str
with Client("https://api.example.com") as client:
user = client.get("/users/1", response=User) # -> User
users = client.get("/users", response=list[User]) # -> list[User]
created = client.post(
"/users", body=NewUser(name="Ada", email="ada@example.com"), response=User
)
raw = client.get("/health") # -> requests.Response
response=takes any type pydantic can validate: a model,list[Model],dict[str, Model]and so on. Without it you get the rawrequests.Response. Type checkers infer the return type from it.body=takes a model, or anything pydantic can serialize such as dicts and lists. It's sent as JSON withContent-Type: application/json.- Any other keyword argument (
params,headers,auth,timeout, ...) goes straight torequests.Session.request. - The verbs are
get,post,put,patchanddelete, plusrequest(method, url, ...)for anything else.
Client options
Client(
base_url=None, # prefix for relative URLs; absolute URLs bypass it
config=None, # Config, or a path to a TOML file (see below)
profile=None, # name of a [profiles.<name>] table to apply, e.g. "v2"
session=None, # bring your own requests.Session (not closed by the client)
raise_for_status=True, # raise HTTPStatusError on 4xx/5xx
timeout=None, # default timeout for every request
)
client.dump(obj) -> bytes and client.load(data, Type) expose the same
serialization as a request, with overrides, wrap and unwrap applied,
without making the request.
Errors
All errors derive from wireshape.WireshapeError:
| Exception | When |
|---|---|
HTTPStatusError |
4xx/5xx response (.response, .status_code) |
ResponseValidationError |
body isn't valid JSON or doesn't match response= (.response, .errors()) |
ResponseShapeError |
body has nothing at the unwrap path (.response, .path) |
ConfigError |
invalid TOML, unknown keys, or overrides that don't fit the model |
TOML field overrides
Where config comes from
Client(config="path/to/wireshape.toml"): a standalone file. If the file is namedpyproject.toml, its[tool.wireshape]table is used.Client(config=Config(...)): an already loaded config, for example fromwireshape.load_config(path).- With no
config, the[tool.wireshape]table of the nearestpyproject.toml, searching upward from the current directory, is used if there is one.
Pass config=Config() to turn overrides off completely.
Format
# standalone file; in pyproject.toml prefix every table with "tool.wireshape."
[models.User.fields.user_id]
alias = "userId" # JSON key used for both sending and receiving
[models.User.fields.team_id]
path = ["team", "id"] # read from a nested location (receive only)
[models.User.fields.email]
aliases = ["mail", ["contact", "email"]] # also accept these (receive only)
[models.User.fields.nickname]
required = false # optional; defaults to None unless `default` is given
default = "anon" # new default (validated against the field type)
[models.User.fields.password]
exclude = "send" # "send" | "receive" | "both"
[models.User.fields.age]
ge = 0 # gt, ge, lt, le, multiple_of,
le = 150 # min_length, max_length, pattern
[models.User.fields.created]
format = "%d/%m/%Y" # strptime/strftime format for date, datetime or time fields
| Key | Effect |
|---|---|
alias |
Wire name, used for both validation and serialization. |
path |
Where to read the value from in the incoming object, as a list of keys (strings) and array indexes (integers); it must start with a key. Receive only: when sending, the field uses alias or its own name. Can't be combined with exclude = "receive". |
aliases |
Extra names to accept when receiving, each a key or a path. The field's normal key (its path, else alias, else the name or alias declared in code) is tried first, then each entry in order; the first one present wins. Receive only. Can't be combined with exclude = "receive". |
required |
false makes the field optional (T | None, default None); true removes a code-declared default. Can't be combined with default. |
default |
Replaces the default value. |
exclude |
send: left out of request bodies. receive: ignored in responses, so the field must have a default. both: both. |
| constraints | Added to the constraints already declared in code. |
format |
Parses and renders date, datetime and time fields with the given format. |
Model keys can be the fully qualified class name ("myapp.models.User",
which needs quoting), the qualified name ("Outer.User"), or the bare class
name (User). Within one layer of config, the most specific match wins and
entries are not merged.
Unknown keys are rejected when the config is loaded. Field names are checked against the model the first time that model is used.
Envelopes: unwrap and wrap
Many APIs put the payload inside an envelope. Two top-level keys handle that for every request the client makes:
unwrap = ["data", "items"] # responses: validate body["data"]["items"]
wrap = ["data"] # request bodies: send {"data": <body>}
Both take a path, a list of keys and (for unwrap) array indexes. wrap
goes from the outermost key inwards: ["a", "b"] sends {"a": {"b": <body>}}.
If a response has nothing at the unwrap path, ResponseShapeError is raised.
Calls without response= return the raw requests.Response, which is never
unwrapped.
To override either one for a single call, pass unwrap= or wrap= to that
call; None turns it off for the call:
client.get("/stats", response=Stats, unwrap=None)
client.get("/latest", response=Item, unwrap=["data", "items", 0])
client.post("/batch", body=items, wrap=["batch"])
Profiles: one model, several API versions
A profile is a named set of settings layered on top of the base config. Pick
one per client with Client(profile=...). This lets one model class serve
several versions of an API whose JSON differs.
For example, here is an employee list where v1 and v2 put the payload under different envelopes, and the employee ID at a different path under a different name:
// GET /v1/employees
{"results": [{"emp": {"ids": {"empId": 7}}, "name": "Ada", "hired": "04/03/2021"}]}
// GET /v2/employees
{"data": {"employees": [{"identity": {"employeeNumber": 7}, "name": "Ada", "hired": "04/03/2021"}]}}
[models.Employee.fields.hired] # base layer: applies to every profile
format = "%d/%m/%Y"
[profiles.v1]
unwrap = ["results"]
[profiles.v1.models.Employee.fields.employee_id]
path = ["emp", "ids", "empId"]
[profiles.v2]
unwrap = ["data", "employees"]
[profiles.v2.models.Employee.fields.employee_id]
path = ["identity", "employeeNumber"]
class Employee(BaseModel):
employee_id: int
name: str
hired: date
v1 = Client("https://hr.example.com/api/v1", profile="v1")
v2 = Client("https://hr.example.com/api/v2", profile="v2")
v1.get("/employees", response=list[Employee]) # same class and values from both
v2.get("/employees", response=list[Employee])
How layers combine:
- A profile accepts the same
models,unwrapandwrapkeys as the top level. - Field overrides merge key by key. In the example, the
employee_idfield getspathfrom the profile and would keep analiasfrom the base. When a profile sets the same key, its value wins. requiredanddefaultcount as one setting: a profile that sets either one replaces both from the base.- Lists such as
aliasesandpathare replaced, not appended to. - A profile can change keys but can't remove them, because TOML has no null.
The exception is
unwrap = []orwrap = [], which turn off the base value. - Model names are matched in each layer separately before merging, so
Userin the base and"app.models.User"in a profile both apply to the same class. - An unknown profile name raises
ConfigErrorwhen the client is created.
How it works
For each model that has overrides, either directly or through a nested model
field, wireshape builds a subclass with those fields redefined. Validated
responses are instances of that subclass, so isinstance(user, User) holds,
the static type is still User, and a parsed object compares equal (==) to
a User you build yourself with the same values. Before a request body is serialized, its
instances are converted to the subclass so that send-side overrides apply too.
Limitations
-
pathandaliasesare receive-only. A field read from a nested location or from an extra name is sent back flat, under itsaliasor name. Writing into nested paths isn't supported yet. -
unwrapapplies to the whole body, not to each item. If every element of a list is wrapped, as in JSON:API's{"data": [{"attributes": {...}}, ...]}, a body-levelunwrapgets you the list but can't reach into each item. -
Self-referencing models. In a model such as
class Node: children: list[Node], overrides apply only at the top level, not to the recursive references. -
Union response types are untyped.
response=User | None(or any other union) works at runtime, but type checkers reject the argument, becauseresponseis typed astype[T]and a union isn't a class. Until Python gainsTypeForm, cast the result yourself:from typing import cast user = cast( "User | None", client.get("/users/1", response=User | None), # pyright: ignore[reportArgumentType] )
The same applies to
Literal[...],Annotated[...]and other type expressions that aren't classes.list[User],dict[str, User]and similar generics are fine.
Development
uv sync
uv run pytest
uv run ruff check . && uv run ruff format --check .
uv run pyright # strict on src/ and tests/typing_check.py
Metadata
Release files for wireshape 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| wireshape-0.1.0.tar.gz | 17.6 kB | With provenance | Details for wireshape-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| wireshape-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for wireshape-0.1.0-py3-none-any.whl |
Total release size: 37.0 kB
Release files / wireshape-0.1.0.tar.gz
| Download URL | wireshape-0.1.0.tar.gz |
|---|---|
| Size | 17.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c05f632cb69f74e70ffe6b156f3a38c8868bc612b31d6cdb16f98f2adf2b1728
|
|
BLAKE2b-256 checksum How to use checksums |
79f56352d5e4ec8961eac906d1516507cc6fd861264d3d152c8e28589856d50c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logRelease files / wireshape-0.1.0-py3-none-any.whl
| Download URL | wireshape-0.1.0-py3-none-any.whl |
|---|---|
| Size | 19.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5038115bdbb6b2452c23c7071f1e732e97b69903b135b0ffb9f6a0d6303f871c
|
|
BLAKE2b-256 checksum How to use checksums |
4dadef04f0ad41961e8ace707889a8401a49805dc09da7d6ecabe38e487466b5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logSecurity for wireshape 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for wireshape-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.