Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
f6d2dbd
feat: Build each endpoint's request model when its class is defined
slatecipher Dec 1, 2026
2cf3413
refactor: Check nested helpers before building the request model
slatecipher Dec 1, 2026
8d4edf1
refactor: Check path and helper rules on the request model
slatecipher Dec 1, 2026
b24e59b
refactor: Check body and key rules on the request model
slatecipher Dec 1, 2026
72818c3
feat: Require SkipValidation on file and stream parameters
slatecipher Dec 1, 2026
e969213
feat: Validate every call's arguments with the request model
slatecipher Dec 1, 2026
7f5fe61
feat: Remove validate_arguments, now that every call is validated
slatecipher Dec 1, 2026
c0a924d
refactor: Work out each argument's route from the request model
slatecipher Dec 1, 2026
5acd2e6
feat: Build each request from the validated request model
slatecipher Dec 1, 2026
783fbed
refactor: Move the path and type helpers out of the planner
slatecipher Dec 1, 2026
96a5ee6
refactor: Judge parameter types by what they dump to
slatecipher Dec 1, 2026
aa13f51
feat: Remove the planner, now that the request model does its work
slatecipher Dec 1, 2026
de4e60d
feat: Validate endpoint tools with the request model
slatecipher Dec 2, 2026
0fdaa8d
refactor: Remove the validation module
slatecipher Dec 2, 2026
7d83a5e
docs: Point to a helper's strict=True for strict validation
slatecipher Dec 2, 2026
086efdb
docs: Describe the request model in CLAUDE.md
slatecipher Dec 2, 2026
674bb8f
docs: Add the request model's changes to the changelog
slatecipher Dec 2, 2026
ff34147
docs: Document validating every call in the requests guide
slatecipher Dec 2, 2026
4850b32
docs: Update the reference, errors, tools and llms.txt for validating…
slatecipher Dec 2, 2026
11b85df
docs: Say how a type with only a serializer becomes a tool argument
slatecipher Dec 2, 2026
689fe5a
docs: Say how a dict passed for a model is read
slatecipher Dec 2, 2026
0b52d0d
refactor: Build an arguments model that tool methods can share
slatecipher Dec 2, 2026
f97857c
feat: Validate tool methods with a model of their parameters
slatecipher Dec 2, 2026
5c1f78a
feat: Reject pydantic secret parameters
slatecipher Dec 2, 2026
6ad7d6c
docs: Split the parameter checks in the errors guide into sub-bullets
slatecipher Dec 2, 2026
1f20270
docs: List the reasons for ArgumentError in the errors guide
slatecipher Dec 2, 2026
5cfe335
docs: Break up the plain values, helper arguments and defaults text
slatecipher Dec 2, 2026
3efe48e
docs: Break up the dense paragraphs in the requests guide
slatecipher Dec 2, 2026
af2fda7
docs: Break up dense paragraphs across the guide and reference
slatecipher Dec 2, 2026
d86d6b4
feat: Let file tuples of text and bytes skip SkipValidation
slatecipher Dec 2, 2026
5e1fc9d
refactor: Move the schema and key helpers out of the rules module
slatecipher Dec 2, 2026
7e297ba
docs: Say that file tuples of text and bytes need no SkipValidation
slatecipher Dec 2, 2026
9a5a868
refactor: Send a file tuple with a headers dict without SkipValidation
slatecipher Dec 2, 2026
7d88447
docs: Show a default and a default factory in the helper reference
slatecipher Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,30 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),

## [Unreleased]

### Added

- A pydantic serializer in a parameter's type runs, as in `Annotated[Point, PlainSerializer(str, return_type=str), Query()]`. ClientX checks what a type dumps to, from pydantic's serialization schema, so a type of your own that dumps to text or a number can go in the query string, a header or a form. It used to raise `DefinitionError`. A type whose dumped form pydantic can't tell, such as a class of your own without a serializer, still raises.
- A helper's `default_factory` works, with `= None` after it so type checkers see the argument as optional: `tags: Annotated[list[str] | None, Json(default_factory=list)] = None` sends `[]` when the caller leaves it out. A `default` inside a helper still raises: put it after `=`.
- Pydantic's `exclude_if` on a helper leaves a value out of the request, as in `Json(exclude_if=lambda value: value is None)`.

### Changed

- Every call's arguments are validated against their annotations, in pydantic's lax mode, before the request is built, and the request is built from the validated values. A helper's constraints, such as `Query(ge=1)`, apply to every call, and an argument that doesn't fit raises `ArgumentError`, with pydantic's `ValidationError` as its cause, before anything is sent. A helper's `strict=True`, as in `Query(strict=True)`, makes one parameter strict. Defaults aren't validated. **Breaking:**
- A call that used to send an argument that doesn't fit its annotation now raises `ArgumentError`. For example, a `str` for a `Sequence[str]` parameter fails, as pydantic doesn't take a string as a sequence: annotate it `str | Sequence[str]` to take both.
- Converted values are sent: `3` for a `float` parameter is sent as `3.0`.
- A model is sent as its annotated type, so a subclass's extra fields are left out. Annotate the parameter `SerializeAsAny[Model]` to send them.
- A `dict` passed for a model is validated into the model, as the model reads one: by alias, and keys the model doesn't have are dropped. It used to be sent as it was. Set `validate_by_name=True` or `extra="allow"` in the model's `model_config` to take field names or keep other keys.
- A `File()` or `Body()` parameter whose type holds a binary file, a stream or `Any`, such as `BinaryIO`, `tuple[str, BinaryIO]` or `Iterator[bytes]`, needs pydantic's `SkipValidation` in its annotation, as in `Annotated[BinaryIO, File(), SkipValidation]`: pydantic can't validate a file or stream, so its value is passed on as it is, and the annotation says so. `str`, `bytes`, and file tuples and lists of them, such as `tuple[str, bytes, str]`, are validated and need none. **Breaking:** one without it raises `DefinitionError` when the class is defined. Add `SkipValidation`.
- A parameter can't be named `model_config`, a name starting with `_`, or the name of a pydantic `BaseModel` attribute, such as `json`, as each call's arguments are validated with a pydantic model of them. **Breaking:** one of those names raises `DefinitionError` when the class is defined. Rename the parameter, and give its helper `alias=` to send the old name.
- A parameter typed as a Pydantic secret, `SecretStr`, `SecretBytes` or `Secret[...]`, raises `DefinitionError` when the class is defined. Pydantic dumps one as `**********`, so the API got the stars: a `Json()` secret used to be sent that way without a word. **Breaking:** pass credentials with the client's `auth=`, or annotate the parameter `str` to send the value.
- A `Send` option on a helper it doesn't apply to, such as `embed` on a `Query()`, is ignored, as pydantic ignores metadata it doesn't use. It used to raise `DefinitionError`.
- A tool validates a model's arguments with a pydantic model of the parameters: an endpoint's tool with the same model as a call, and a `@tool` method's with one of its own. An argument the method doesn't have is reported as `Extra inputs are not permitted`, rather than `Unexpected keyword argument`. **Breaking:** a `@tool` method's parameter can't be named `model_config`, start with `_`, or have the name of a `BaseModel` attribute, such as `json`, as for an endpoint: one raises `DefinitionError` when the method is decorated. Rename it.

### Removed

- `validate_arguments=True` on `ClientX` and `AsyncClientX`: every call is validated now. **Breaking:** passing it raises a `TypeError`. Leave it out.
- `Send`'s `exclude_unset`, `exclude_none` and `exclude_defaults`. `Send` keeps `embed` and `json_part`. **Breaking:** an endpoint that sets one raises a `TypeError` when its module is imported. A model's own fields are dumped as the model defines them, and pydantic's `exclude_if` on the helper leaves out a value, as in `Json(exclude_if=lambda value: value is None)`. A parameter with a default of `None` is still left out when the caller doesn't pass it.

## [0.6.1] - 2026-11-29

### Fixed
Expand Down
15 changes: 9 additions & 6 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,19 @@ uv run pytest test/test_paths.py::test_name --no-cov # one test, without cover
An endpoint goes through three stages. Every check that can run before a call runs in the first two, so a mistake raises `DefinitionError` when its module is imported. Don't add call-time work that could be done there.

- **Decoration** (`_method.py`): each verb in `clientx.method` is a `Method`. Its decorator calls `inspect_signature` (`_signature.py`) and builds an `Endpoint` (`_endpoint.py`), whose `__post_init__` checks the parameters, return annotation, `stream=` and `decoder=`, and picks the decoder (`_decoding.py`). It returns a sync or an async wrapper, by the method's kind, and registers wrapper → endpoint in `_registry.py`.
- **Class creation** (`_client.py`, `_class_setup.py`): `__init_subclass__` on `ClientX`, `AsyncClientX`, `Resource` and `AsyncResource` checks the class body, stores a client's class arguments (`base_url`, checked to be absolute, and `user_agent`), claims its endpoints (an endpoint has one owner class), joins a resource's prefix and tags onto them, then calls `Endpoint.set_up_request_plan()`, which plans the endpoint's request (`plan_request` in `_planner.py`) now that its path is final.
- **Call** (the wrappers in `_method.py`): deprecation warning → `client_of` (walks resource parents up to the client) → `Endpoint.bind` (the arguments, and which ones the caller passed) → `Endpoint.check_arguments` if the client was created with `validate_arguments=True` → `build_request` in `_builder.py` (the URL path and `build_request` arguments, by the plan) → `build_request` and `send` on the client itself → `httpx2.HTTPStatusError` for a 4xx or 5xx unless `raise_for_status` is off → the open response for `stream=True`, or else `decode` / `adecode`.
- **Class creation** (`_client.py`, `_class_setup.py`): `__init_subclass__` on `ClientX`, `AsyncClientX`, `Resource` and `AsyncResource` checks the class body, stores a client's class arguments (`base_url`, checked to be absolute, and `user_agent`), claims its endpoints (an endpoint has one owner class), joins a resource's prefix and tags onto them, then calls `Endpoint.set_up_request_plan()` now that the path is final: it builds the endpoint's request model (`build_request_model` in `_request_model.py`), checks it (`check_request_model` in `_request_rules.py`), and works out each argument's route (`plan_routes` in `_request_routes.py`).
- **Call** (the wrappers in `_method.py`): deprecation warning → `client_of` (walks resource parents up to the client) → `Endpoint.bind` (the arguments, and which ones the caller passed) → `Endpoint.request_arguments`: `validate_call` validates the passed arguments with the request model, raising `ArgumentError`, then `build_request` in `_builder.py` builds the URL path and `build_request` arguments from the validated model by the routes → `build_request` and `send` on the client itself → `httpx2.HTTPStatusError` for a 4xx or 5xx unless `raise_for_status` is off → the open response for `stream=True`, or else `decode` / `adecode`.

Where the rules are written down:

- `_planner.py`'s module docstring: where each parameter goes (a path placeholder, or its helper's `build_request` argument), the plain-value allow-list, what each argument takes, spreading, one kind of body, key clashes, `Send`'s options, and the path template syntax. Each argument's rules live in one `HttpxArgumentSpec` subclass there; the planner asks the spec rather than testing for particular arguments.
- `_builder.py`'s module docstring: how one call's arguments become the request by the plan: path encoding, text, `None` left out (or `null` in JSON for a `None` passed explicitly), files, and the body. The builder never reads annotations, `Send` or the specs.
- `_tools.py`'s module docstring: how endpoints become tools for a model (`clientx.tools`): names, which endpoints are left out, descriptions, compact schemas, calls and `ToolError`'s messages. Tools are built from each `Endpoint` the registry knows; nothing there depends on an AI library.
- `_validation.py`'s module docstring: how one validator per endpoint checks a call's arguments for `validate_arguments=True` (strict, only the passed ones, never changing what's sent, types Pydantic can't validate skipped), built on the first checked call. `clientx.tools` validates a model's arguments with the same validator, leniently.
- `_request_model.py`'s module docstring: the request model, one pydantic model per endpoint built with `create_model`, with a field per parameter (its full annotation and default), the settings ClientX gives it (lax, by name, extra arguments forbidden), the checks that run on the parameters before it's built (nested helpers, defaults and factories, names a model can't hold), and how `validate_call` validates each call. `describe_errors` writes pydantic's errors for messages here and in tools.
- `_request_rules.py`'s module docstring: the rules checked on the model's fields when the class is defined: placeholders, which parameters need helpers, what each argument takes (judged by the serialization schema, so by what a value dumps to), files and raw bodies (`SkipValidation` on those holding a binary file, a stream or `Any`), one kind of body, key clashes. Each rule is one `if` in `check_request_model`.
- `_request_schema.py`'s module docstring: what the rules and the routes both read: each field's serialization schema (`request_schema`, with a type pydantic can't describe marked rather than failing), whether it dumps to a plain value, and which parameters are spread and the keys each value is sent under.
- `_request_routes.py`'s module docstring: where each field goes (`FieldRoute`): the path, its helper's `build_request` argument and key, spreading, and when the lone `Json()` parameter is the whole body. `Send` keeps only `embed` (`Json()`) and `json_part` (`Form()`); pydantic's `exclude_if` leaves a value out.
- `_builder.py`'s module docstring: how one call's validated model becomes the request by the routes: path encoding, text, `None` left out (or `null` in JSON for a `None` passed explicitly), files, the body, and NaN. The builder never reads annotations or `Send`.
- `_tools.py`'s module docstring: how endpoints become tools for a model (`clientx.tools`): names, which endpoints are left out, descriptions, compact schemas, calls and `ToolError`'s messages. Tools are built from each `Endpoint` the registry knows; an endpoint tool validates with the request model, a `@tool` method with its own model from the same `arguments_model`. Nothing there depends on an AI library.
- `_decoding.py`'s module docstring: how the return annotation decides decoding (`-> None`, `Response`, `str`, `bytes`, `Iterator[str]` or `Iterator[bytes]`, anything else through a `TypeAdapter`).
- `_paths.py` parses a path template; `_annotations.py` tells what a type is (plain value, file, model, helper metadata) for the rules and routes.
- `_signature.py`: one `ParameterInfo` per parameter, with `Annotated` kept and PEP 695 `type` aliases expanded. A parameter's helper is the last `clientx.arguments` mark in its outermost `Annotated`. The helpers wrap `pydantic.Field` and append their `HttpxArgument` to its metadata (`_arguments.py`).
- `_types.py`: shared types: `HttpxArgument`, `Send`, the type aliases, and TypedDicts that mirror httpx2's signatures (`HttpxClientOptions`, `AsyncHttpxClientOptions`, `BuildRequestKwargs`); a test in `test_clients.py` fails when httpx2's parameters change. It's the only module that imports httpx2's private modules.

Expand Down
37 changes: 5 additions & 32 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ api = ExampleAPI("https://api.example.com", user_agent="my-app/1.0", timeout=5.0
- `base_url`: the API's base URL, which every endpoint's path is relative to. It's required unless the class sets one (see [Class defaults](#class-defaults)), and it wins over the class's.
- `user_agent`: your app's product, such as `my-app/1.0`, sent first in the `User-Agent`, before the class's and ClientX's (see [User-Agent](#user-agent)). A `User-Agent` in `headers=` goes first the same way.
- `raise_for_status`: whether a 4xx or 5xx response raises `httpx2.HTTPStatusError`. It's on by default; see [Errors for 4xx and 5xx responses](responses.md#errors-for-4xx-and-5xx-responses).
- `validate_arguments`: whether each call's arguments are checked against their annotations before anything is sent. It's off by default; see [Validating arguments](#validating-arguments).
- Any other `httpx2.Client` option, such as `timeout`, `headers`, `params`, `auth` (see [Authentication](#authentication)), `transport`, `proxy` or `follow_redirects`.

A `ClientX` is an `httpx2.Client`, so those options, and everything else httpx2 documents for a client, work as they do there. That includes changing `headers`, `params`, `auth` or `timeout` on a client after it's created: the change applies to every endpoint. Each client has its own connections, settings and credentials, so clients for production and staging, or one per account, can be used side by side.
Expand Down Expand Up @@ -72,43 +71,17 @@ print(api.headers["User-Agent"]) # my-app/1.0 (me@example.com) example-client/0
api.headers["User-Agent"] = "my-app/1.0" # sent as it is
```

## Validating arguments

ClientX sends arguments as they're passed: type checkers catch a wrong type in code they check, and a helper's constraints, such as `Query(ge=1)`, aren't checked. To check each call's arguments against their annotations before anything is sent, create the client with `validate_arguments=True`:

<!-- docs_src/configuration/validating_arguments.py -->
```python
from typing import Annotated

from clientx import ArgumentError, ClientX, Query, method


class ExampleAPI(ClientX, base_url="https://api.example.com"):
@method.get("/users")
def list_users(self, page: Annotated[int, Query(ge=1)] = 1) -> None: ...


with ExampleAPI(validate_arguments=True) as api:
try:
api.list_users(page=0)
except ArgumentError as error:
print(error.parameter) # page: no request was sent
```

- Arguments are checked strictly, as a type checker would: `"7"` doesn't fit an `int`. A helper's constraints are checked too.
- Only the arguments a call passes are checked, not the defaults.
- The request is built from the arguments as they were passed: checking never changes what's sent. A model instance isn't validated again.
- A parameter whose type Pydantic can't validate isn't checked: a binary file (`IO[bytes]`, `BinaryIO`, or a file tuple holding one), `Iterator[bytes]` or an async stream, or your own class that Pydantic doesn't know. A stream's items are never checked. Pydantic's [Standard Library Types](https://pydantic.dev/docs/validation/latest/api/pydantic/standard_library_types/) lists what it validates, and how strictly.
- An argument that doesn't fit raises [`ArgumentError`](errors.md#argumenterror). Its `parameter` names the first one that doesn't fit, its message lists every problem, and Pydantic's `ValidationError` is its `__cause__`.
- It's for the whole client, and off unless you turn it on: in tests, for example, or for callers whose code isn't type-checked.

## Authentication

Give a client its credentials with `auth=` when you create it. `auth=` is httpx2's authentication option: the client applies it to every request. For what it accepts and how to write your own scheme, see httpx2's [Authentication](https://pydantic.dev/docs/httpx2/advanced/authentication/) documentation.

Keep credentials out of endpoint parameters: every caller would have to pass them.

Don't add credentials in a request [event hook](#logging-and-event-hooks). httpx2 documents hooks for logging, monitoring and tracing. A request hook also runs again for every redirect, so it would put back an `Authorization` header that httpx2 dropped for another host. And it can't send a token request through the client's flow or send a request again after a 401.
Don't add credentials in a request [event hook](#logging-and-event-hooks). httpx2 documents hooks for logging, monitoring and tracing, and a hook can't do what `auth=` does:

- A request hook runs again for every redirect, so it would put back an `Authorization` header that httpx2 dropped for another host.
- It can't send a token request through the client's flow.
- It can't send a request again after a 401.

For other schemes, httpx2's [Third Party Packages](https://pydantic.dev/docs/httpx2/community/third_party_packages/) page lists libraries that support it. Use a library's `Auth` class as `auth=`, not its client class.

Expand Down
6 changes: 5 additions & 1 deletion docs/endpoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ with UsersAPI("https://api.example.com") as api:

`get_user(42)` sends `GET /users/42`, because `user_id` matches `{user_id}`, and returns the JSON response as a `User`. The two halves are independent: `User`'s fields come from the response, not from the arguments.

Import the decorators' module, `from clientx import method`, and decorate each endpoint with the verb it sends: `@method.get(...)`, `@method.post(...)`, `@method.put(...)`, `@method.patch(...)`, `@method.delete(...)`, `@method.head(...)` or `@method.options(...)`, always with parentheses: `@method.get()` for an endpoint with no path, since `@method.get` alone raises `DefinitionError`. They decorate `def` methods of a `ClientX` or a `Resource`, and `async def` methods of an `AsyncClientX` or an `AsyncResource` (see [Async clients](async.md)).
Import the decorators' module, `from clientx import method`, and decorate each endpoint with the verb it sends:

- The verbs are `@method.get(...)`, `@method.post(...)`, `@method.put(...)`, `@method.patch(...)`, `@method.delete(...)`, `@method.head(...)` and `@method.options(...)`.
- Always write the parentheses: `@method.get()` for an endpoint with no path. `@method.get` alone raises `DefinitionError`.
- They decorate `def` methods of a `ClientX` or a `Resource`, and `async def` methods of an `AsyncClientX` or an `AsyncResource` (see [Async clients](async.md)).

## Options

Expand Down
Loading