Metadata-Version: 2.4
Name: wireshape
Version: 0.1.0
Summary: Strongly typed HTTP calls on top of requests, with pydantic models and TOML field overrides
Keywords: requests,pydantic,http,api-client,typing,serialization,toml
Author: croese
Author-email: croese <croese@gmail.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Dist: pydantic>=2.9
Requires-Dist: requests>=2.32
Requires-Dist: typing-extensions>=4.10 ; python_full_version < '3.13'
Requires-Python: >=3.12
Project-URL: Homepage, https://github.com/croese/wireshape
Project-URL: Repository, https://github.com/croese/wireshape
Project-URL: Issues, https://github.com/croese/wireshape/issues
Project-URL: Examples, https://github.com/croese/wireshape/tree/main/examples/employee_directory
Description-Content-Type: text/markdown

# wireshape

Strongly typed HTTP calls on top of [`requests`](https://requests.readthedocs.io/).
You declare the type you send and the type you expect back as
[pydantic](https://docs.pydantic.dev/) 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`](https://github.com/croese/wireshape/tree/main/examples/employee_directory). It talks to two
incompatible versions of an HR API over real HTTP using one set of models.

## Quick start

```python
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 raw `requests.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 with `Content-Type: application/json`.
- Any other keyword argument (`params`, `headers`, `auth`, `timeout`, ...) goes
  straight to `requests.Session.request`.
- The verbs are `get`, `post`, `put`, `patch` and `delete`, plus
  `request(method, url, ...)` for anything else.

### Client options

```python
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

1. `Client(config="path/to/wireshape.toml")`: a standalone file. If the file is
   named `pyproject.toml`, its `[tool.wireshape]` table is used.
2. `Client(config=Config(...))`: an already loaded config, for example from
   `wireshape.load_config(path)`.
3. With no `config`, the `[tool.wireshape]` table of the nearest
   `pyproject.toml`, searching upward from the current directory, is used if
   there is one.

Pass `config=Config()` to turn overrides off completely.

### Format

```toml
# 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:

```toml
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:

```python
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:

```jsonc
// 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"}]}}
```

```toml
[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"]
```

```python
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`, `unwrap` and `wrap` keys as the top
  level.
- Field overrides merge **key by key**. In the example, the `employee_id` field
  gets `path` from the profile and would keep an `alias` from the base. When a
  profile sets the same key, its value wins.
- `required` and `default` count as one setting: a profile that sets either one
  replaces both from the base.
- Lists such as `aliases` and `path` are replaced, not appended to.
- A profile can change keys but can't remove them, because TOML has no null.
  The exception is `unwrap = []` or `wrap = []`, which turn off the base value.
- Model names are matched in each layer separately before merging, so `User` in
  the base and `"app.models.User"` in a profile both apply to the same class.
- An unknown profile name raises `ConfigError` when 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

- **`path` and `aliases` are receive-only.** A field read from a nested
  location or from an extra name is sent back flat, under its `alias` or name.
  Writing into nested paths isn't supported yet.
- **`unwrap` applies 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-level `unwrap` gets 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, because
  `response` is typed as `type[T]` and a union isn't a class. Until Python
  gains `TypeForm`, cast the result yourself:

  ```python
  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

```sh
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
```
