diff --git a/CHANGELOG.md b/CHANGELOG.md index d0293fa..cccf183 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/CLAUDE.md b/CLAUDE.md index 3db2e09..bf22138 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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. diff --git a/docs/configuration.md b/docs/configuration.md index 8ddebf0..b5d147f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -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. @@ -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`: - - -```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. diff --git a/docs/endpoints.md b/docs/endpoints.md index 8f3fa9e..188dd3d 100644 --- a/docs/endpoints.md +++ b/docs/endpoints.md @@ -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 diff --git a/docs/errors.md b/docs/errors.md index 313c28f..cec5e35 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -5,7 +5,7 @@ ClientX raises errors of its own, all derived from `ClientXError`, so `except Cl | Error | Base | Raised for | |---|---|---| | `DefinitionError` | `TypeError` | a client, resource or endpoint written in a way ClientX can't use | -| `ArgumentError` | `ValueError` | an argument value that can't be sent, or that doesn't fit its annotation on a client with `validate_arguments=True` | +| `ArgumentError` | `ValueError` | an argument that doesn't fit its annotation, or whose value can't be sent | | `ToolError` | | a tool call that failed, from [`clientx.tools`](tools.md) | ## `DefinitionError` @@ -27,11 +27,30 @@ When the client or resource class is defined: - An endpoint is the wrong kind for its class: `async def` on a `ClientX` or `Resource`, or `def` on an `AsyncClientX` or `AsyncResource`. - An endpoint or mounted resource has a name the client already uses (see [Endpoint names](endpoints.md#endpoint-names)), or the endpoint is already in another class's body. - A resource is mounted on the other kind of client or resource, or on a class that isn't one, or a resource class is assigned where an instance should be (`users = Users` rather than `users = Users()`). -- The path has a brace that isn't part of a placeholder (`{{` and `}}` included), a placeholder other than `{name}` or `{name:path}`, or a placeholder, a resource prefix's included, that names no parameter. A placeholder's parameter isn't a plain value, can be `None`, has a helper other than `Url()` or an alias, or a `Url()` parameter has no placeholder. -- A helper is nested inside a parameter's type, has a default inside it, or is on a model's field. A parameter's type has a Pydantic serializer, such as `PlainSerializer`, which wouldn't run. The same goes for a `Send`, and for a `Send` option where it can't apply, such as `Send(embed=True)` on a parameter that isn't sent as JSON, any option on a path parameter, or `Send(exclude_unset=True)` on a parameter with no default, or a `None` default, whose type has no Pydantic model, or `Send(exclude_none=True)` on a `Form()` that isn't a JSON part. -- A parameter's value can't go to its part: a type that isn't a plain value, such as a class of your own, for a path, query, header or form value; a list for a header; a field of a spread model that isn't a plain value; a `File()` that isn't `bytes`, a binary file or a file tuple (`str` included); or a `Body()` that isn't `str`, `bytes` or a stream of `bytes`, or a stream of the wrong kind for the client. The parameters make more than one kind of body, or more than one is marked `Body()`. Two values would be sent under one key, or a header name isn't ASCII. - -See [Building requests](requests.md) for the rules behind the last three. +- The path is written wrong: + - It has a brace that isn't part of a placeholder, `{{` and `}}` included. + - It has a placeholder other than `{name}` or `{name:path}`. + - A placeholder, a resource prefix's included, names no parameter. +- A path parameter can't fill its placeholder: it isn't a plain value, can be `None`, or has a helper other than `Url()` or an alias. Or a `Url()` parameter has no placeholder. +- A helper, `Send` or default is in the wrong place: + - A helper or `Send` is nested inside a parameter's type, or is on a model's field. + - A helper has a `default` inside it, or a `default_factory` without `= None` after it. + - A path parameter has a `Send`. +- A parameter's type is, or holds, a Pydantic secret (`SecretStr`, `SecretBytes` or `Secret[...]`), which Pydantic would send as `**********`. Pass credentials with the client's `auth=`. +- A parameter has a name a Pydantic model can't hold: `model_config`, one starting with `_`, or the name of a `BaseModel` attribute, such as `json`. Rename it, and give its helper `alias=` to send the old name. +- A parameter's value can't go to its part: + - A path, query, header or form value whose type doesn't dump to a plain value, or whose dumped form Pydantic can't tell, such as a class of your own without a serializer. + - A list for a header. + - A field of a spread model that isn't a plain value. + - A `File()` that isn't `bytes`, a binary file or a file tuple (`str` included). + - A `Body()` that isn't `str`, `bytes` or a stream of `bytes`, or a stream of the wrong kind for the client. + - A `File()` or `Body()` whose type holds a binary file, a stream or `Any`, without `SkipValidation`. +- The parameters don't fit together: + - They make more than one kind of body, or more than one is marked `Body()`. + - Two values would be sent under one key. + - A header name isn't ASCII. + +See [Building requests](requests.md) for the rules behind the parameter checks above. At call time: @@ -40,7 +59,13 @@ At call time: ## `ArgumentError` -An `ArgumentError` is raised before the request is sent, when an argument's value can't be sent as it is. Its `parameter` attribute names the parameter. A path value raises it when it would call a different path: `None`, an empty value, or a `{name:path}` value with a leading, trailing or doubled slash (see [Path parameters](requests.md#path-parameters)). A JSON value raises it when Pydantic can't serialize it, such as an object of an unknown class passed through `Any`, or when it holds NaN or infinity, which JSON can't. A text value raises it when it can't become text, such as `bytes` that aren't UTF-8, and a header's name or value when it isn't ASCII. On a client created with `validate_arguments=True`, an argument that doesn't fit its annotation raises it too, with Pydantic's `ValidationError` as its `__cause__` (see [Validating arguments](configuration.md#validating-arguments)). +An `ArgumentError` is raised before the request is sent. Its `parameter` attribute names the parameter. It's raised when: + +- **An argument doesn't fit its annotation**, with Pydantic's `ValidationError` as its `__cause__` (see [Validating arguments](requests.md#validating-arguments)). +- **A path value would call a different path:** `None`, an empty value, or a `{name:path}` value with a leading, trailing or doubled slash (see [Path parameters](requests.md#path-parameters)). +- **A JSON value can't be serialized**, such as an object of an unknown class passed through `Any`, or it holds NaN or infinity, which JSON can't. +- **A text value can't become text**, such as `bytes` that aren't UTF-8. +- **A header's name or value isn't ASCII.** ```python @@ -61,7 +86,13 @@ with UsersAPI("https://api.example.com") as api: ## `ToolError` -A `ToolError` is raised by a tool's `call()` or `acall()`, from [`clientx.tools`](tools.md), when the arguments a model gave don't fit, the request can't be sent or fails, or the response doesn't fit the endpoint's return annotation. Its message is written for the model, and never holds the host or the query string. Its `tool` attribute names the tool, and the original error is its `__cause__` (see [Errors](tools.md#errors) on the AI tools page). +A `ToolError` is raised by a tool's `call()` or `acall()`, from [`clientx.tools`](tools.md), when: + +- The arguments a model gave don't fit. +- The request can't be sent, or fails. +- The response doesn't fit the endpoint's return annotation. + +Its message is written for the model, and never holds the host or the query string. Its `tool` attribute names the tool, and the original error is its `__cause__` (see [Errors](tools.md#errors) on the AI tools page). ## Other errors diff --git a/docs/reference.md b/docs/reference.md index b95f66f..463d5aa 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1,6 +1,12 @@ # API Reference -Everything public in ClientX is on this page. Import it from `clientx`, use the verb decorators through `clientx.method` (`from clientx import method`, then `@method.get(...)`), and import the AI tools from `clientx.tools`. The submodule `clientx.arguments` holds names that `clientx` already exports, so either import works, and so does `clientx.exceptions`, along with `ToolError`, which is also in `clientx.tools`. +Everything public in ClientX is on this page: + +- Import it from `clientx`. +- Use the verb decorators through `clientx.method`: `from clientx import method`, then `@method.get(...)`. +- Import the AI tools from `clientx.tools`. + +The submodule `clientx.arguments` holds names that `clientx` already exports, so either import works, and so does `clientx.exceptions`, along with `ToolError`, which is also in `clientx.tools`. Anything else is internal and can change in any release: modules whose names start with an underscore, such as `clientx._planner`, and any name not listed here. ClientX is pre-1.0, so the public API can change between minor versions too. The [changelog](../CHANGELOG.md) lists each change. @@ -29,7 +35,6 @@ ExampleAPI( *, user_agent: str | None = None, raise_for_status: bool | None = None, - validate_arguments: bool = False, **options, # any httpx2.Client option ) ``` @@ -52,7 +57,6 @@ Arguments when creating a client: | `base_url` | `str` or `httpx2.URL` | the class's | The URL every endpoint's path is relative to. With none here or on the class, creating the client raises `TypeError`, and one that isn't absolute raises `ValueError`. | | `user_agent` | `str` | a `User-Agent` in `headers=` | The app's product, such as `my-app/1.0`, sent first in the `User-Agent`, before the class's and `ClientX/`. For one exact value, set `client.headers["User-Agent"]` after creating the client. | | `raise_for_status` | `bool` | `True` | Whether a 4xx or 5xx response raises `httpx2.HTTPStatusError`. An endpoint's own `raise_for_status=` wins. | -| `validate_arguments` | `bool` | `False` | Whether each call's arguments are checked against their annotations, strictly and with a helper's constraints, before anything is sent; one that doesn't fit raises `ArgumentError`. See [Validating arguments](configuration.md#validating-arguments). | | `**options` | | | Any [`httpx2.Client` option](https://pydantic.dev/docs/httpx2/api/#httpx2.Client), such as `auth`, `headers`, `params`, `cookies`, `timeout`, `verify`, `proxy`, `transport`, `mounts`, `event_hooks` or `follow_redirects`. | An endpoint or mounted resource on a client can't use a name the client already has, which includes every name of `httpx2.Client`, such as `get` or `send` (see [Endpoint names](endpoints.md#endpoint-names)). The client's own httpx2 methods still send one-off requests. See [Client configuration](configuration.md). @@ -69,12 +73,17 @@ ExampleAPI( *, user_agent: str | None = None, raise_for_status: bool | None = None, - validate_arguments: bool = False, **options, # any httpx2.AsyncClient option ) ``` -The base class for an async client, with `async def` endpoints. It takes the same class arguments and arguments as [`ClientX`](#clientx), but it's an [`httpx2.AsyncClient`](https://pydantic.dev/docs/httpx2/api/#httpx2.AsyncClient): close it with `async with` or `await client.aclose()`, give it async transports, and make its event hooks `async` functions. See [Async clients](async.md). +The base class for an async client, with `async def` endpoints. It takes the same class arguments and arguments as [`ClientX`](#clientx), but it's an [`httpx2.AsyncClient`](https://pydantic.dev/docs/httpx2/api/#httpx2.AsyncClient): + +- Close it with `async with` or `await client.aclose()`. +- Give it async transports. +- Make its event hooks `async` functions. + +See [Async clients](async.md). ## `Resource` @@ -134,7 +143,15 @@ The module of verb decorators: `get`, `post`, `put`, `patch`, `delete`, `head` a | `timeout` | the client's | The request timeout, in seconds or as an `httpx2.Timeout`. `None` turns it off. | | `raise_for_status` | the client's | Whether a 4xx or 5xx response raises `httpx2.HTTPStatusError`. | -The method's parameters build the request (see [Request helpers](#request-helpers)), and its return annotation decides what the endpoint returns: `-> None` nothing, `-> Response` the response, `-> str` or `-> bytes` the body, `-> Iterator[str]` or `-> Iterator[bytes]` the body streamed (`AsyncIterator` for `async def`), and any other type the JSON body, validated by Pydantic. See [Defining endpoints](endpoints.md) and [Responses](responses.md). +The method's parameters build the request (see [Request helpers](#request-helpers)), and its return annotation decides what the endpoint returns: + +- `-> None`: nothing. +- `-> Response`: the response. +- `-> str` or `-> bytes`: the body. +- `-> Iterator[str]` or `-> Iterator[bytes]`: the body streamed (`AsyncIterator` for `async def`). +- Any other type: the JSON body, validated by Pydantic. + +See [Defining endpoints](endpoints.md) and [Responses](responses.md). ## Request helpers @@ -148,7 +165,13 @@ Form(**field_arguments) File(**field_arguments) ``` -Each helper takes exactly the arguments of [`pydantic.Field`](https://docs.pydantic.dev/latest/api/fields/#pydantic.fields.Field), and marks where a parameter's value goes. Put it in the parameter's outermost `Annotated`: `user_id: Annotated[int, Query(alias="userId")]`. ClientX reads `alias=`, the name the value is sent under. A default goes after `=`, not inside the helper. Every parameter needs a helper, except one named like a path placeholder, which fills it. +Each helper takes exactly the arguments of [`pydantic.Field`](https://docs.pydantic.dev/latest/api/fields/#pydantic.fields.Field), and marks where a parameter's value goes. Every parameter needs a helper, except one named like a path placeholder, which fills it. + +- Put it in the parameter's outermost `Annotated`: `user_id: Annotated[int, Query(alias="userId")]`. +- ClientX reads `alias=`, the name the value is sent under. +- A default goes after `=`, not inside the helper: `page: Annotated[int, Query()] = 1`, not `Query(default=1)`. +- A `default_factory` goes inside the helper, with `= None` after: `tags: Annotated[list[str] | None, Json(default_factory=list)] = None` sends `[]` when the call leaves `tags` out. +- Each call's arguments are validated against their annotations, a helper's constraints included, before anything is sent (see [Validating arguments](requests.md#validating-arguments)). | Helper | Sends the value as | It takes | |---|---|---| @@ -160,7 +183,9 @@ Each helper takes exactly the arguments of [`pydantic.Field`](https://docs.pydan | `Form()` | a form field | a plain value, a list of them, or a model, dataclass or mapping to spread | | `File()` | a file in a multipart form | `bytes`, a binary file, a `(filename, content[, content_type[, headers]])` tuple, or a list of them | -A plain value is a `str`, `int`, `float`, `bool`, `Enum`, `date`, `datetime`, `time`, `UUID`, `Decimal` or `bytes`, a `Literal` of those, or a `NewType` of one. See [Building requests](requests.md). +A [plain value](requests.md#plain-values) is one Pydantic dumps to a single string, number or boolean: a `str`, `int`, `float`, `bool`, `Enum`, `date`, `datetime`, `time`, `UUID`, `Decimal` or `bytes`, a `Literal` of those, a `NewType` of one, or a type whose serializer dumps it to one. + +A `File()` or `Body()` whose type holds a binary file, a stream or `Any` needs Pydantic's `SkipValidation` in its annotation; `str`, `bytes`, and file tuples and lists of them need none. See [Building requests](requests.md). ## `Send` @@ -168,9 +193,6 @@ A plain value is a `str`, `int`, `float`, `bool`, `Enum`, `date`, `datetime`, `t Send( *, embed: bool | None = None, - exclude_unset: bool | None = None, - exclude_none: bool | None = None, - exclude_defaults: bool | None = None, json_part: bool | None = None, ) ``` @@ -180,12 +202,9 @@ Options that change how a parameter is sent. Put it next to the helper, in the p | Option | Effect | |---|---| | `embed` | Sends a lone JSON parameter under its name, as a field of a JSON object, instead of as the whole body. | -| `exclude_unset` | Leaves out the parameter when the caller doesn't pass it, and a model's fields that weren't set. | -| `exclude_none` | Leaves out a model's fields that are `None`. | -| `exclude_defaults` | Leaves out a model's fields that equal their defaults. | | `json_part` | Sends a `Form()` parameter's value as a JSON part of a multipart form. | -Each option works with some helpers only, and one where it can't apply raises `DefinitionError` when the class is defined. See [Send](requests.md#send) for where each one works. +`embed` works with `Json()`, and `json_part` with `Form()`; on another helper, an option does nothing. A `Send` on a path parameter raises `DefinitionError` when the class is defined. To leave a value out, use Pydantic's `exclude_if` on the helper. See [Send](requests.md#send). ## Errors @@ -193,7 +212,7 @@ Each option works with some helpers only, and one where it can't apply raises `D |---|---|---| | `ClientXError` | `Exception` | The base of the others, so `except ClientXError` catches any of them. | | `DefinitionError` | `ClientXError`, `TypeError` | A client, resource or endpoint written in a way ClientX can't use. Almost always raised when the class is defined, so the mistake fails when its module is imported. | -| `ArgumentError` | `ClientXError`, `ValueError` | An argument value that can't be sent, or that doesn't fit its annotation on a client with `validate_arguments=True`, raised before anything is sent. Its `parameter` attribute names the endpoint parameter. | +| `ArgumentError` | `ClientXError`, `ValueError` | An argument that doesn't fit its annotation, or whose value can't be sent, raised before anything is sent. Its `parameter` attribute names the endpoint parameter. | | `ToolError` | `ClientXError` | A tool call that failed, from [`clientx.tools`](#clientxtools). Its message is written for a model, and its `tool` attribute names the tool. | ```py @@ -216,7 +235,12 @@ tool.call(arguments: Mapping[str, Any] | None = None) -> Any # on a ClientX await tool.acall(arguments: Mapping[str, Any] | None = None) -> Any # on an AsyncClientX ``` -`list_tools` returns a `Tool` for each endpoint on the client and its mounted resources that a model can use, and for each `@tool` method there: endpoints that stream, return the raw `Response` or `bytes`, take an argument with no JSON form, or have `include_in_tools=False` are left out, and so are private names, which start with `_`, with everything on a resource mounted under one. Nothing in it depends on an AI library. +`list_tools` returns a `Tool` for each endpoint on the client and its mounted resources that a model can use, and for each `@tool` method there. Nothing in it depends on an AI library. These are left out: + +- Endpoints that stream, or return the raw `Response` or `bytes`. +- Endpoints that take an argument with no JSON form. +- Endpoints with `include_in_tools=False`. +- Private names, which start with `_`, and everything on a resource mounted under one. | `Tool` attribute | Type | What it is | |---|---|---| @@ -231,9 +255,22 @@ await tool.acall(arguments: Mapping[str, Any] | None = None) -> Any # on an Asy `call()` validates a model's arguments leniently, passes only those it gave, and returns JSON-ready data. A failed call raises `ToolError`, with a message for the model that never holds the host or query string, and the original error as its `__cause__`. See [AI tools](tools.md). -`ToolOptions` sets an endpoint's hints, through its verb's `tool_options=`. Each hint is worked out on its own: one you set is used as it is, and one left as `None` comes from the HTTP method (`GET`, `HEAD` and `OPTIONS` are read-only and idempotent; `PUT` and `DELETE` destructive and idempotent; `PATCH` destructive; `POST` none of them). Setting one hint never changes another. An endpoint whose hints end up read-only and destructive, set or from its method, raises `DefinitionError`. See [Where each hint comes from](tools.md#where-each-hint-comes-from). +`ToolOptions` sets an endpoint's hints, through its verb's `tool_options=`. Each hint is worked out on its own, and setting one never changes another: + +- A hint you set is used as it is. +- A hint left as `None` comes from the HTTP method: `GET`, `HEAD` and `OPTIONS` are read-only and idempotent; `PUT` and `DELETE` destructive and idempotent; `PATCH` destructive; `POST` none of them. +- An endpoint whose hints end up read-only and destructive, set or from its method, raises `DefinitionError`. + +See [Where each hint comes from](tools.md#where-each-hint-comes-from). + +`@tool` makes a method of a client or resource a tool, listed and called as an endpoint is. -`@tool` makes a method of a client or resource a tool, listed and called as an endpoint is. It needs a docstring, its description, and a return annotation. Its hints are `False` unless set, as there's no HTTP method to take them from, and a resource's tags go in front of its own. `@tool` on an endpoint, on a private name, or on a method that returns `bytes`, raises `DefinitionError`. See [Tools that aren't endpoints](tools.md#tools-that-arent-endpoints). +- It needs a docstring, its description, and a return annotation. +- Its hints are `False` unless set, as there's no HTTP method to take them from. +- A resource's tags go in front of its own. +- `@tool` on an endpoint, on a private name, or on a method that returns `bytes`, raises `DefinitionError`, and so does a parameter named like `json`, `model_config` or `_private`. + +See [Tools that aren't endpoints](tools.md#tools-that-arent-endpoints). ## `clientx.fastmcp` @@ -243,7 +280,15 @@ from clientx.fastmcp import fastmcp_tool fastmcp_tool(tool: Tool) -> fastmcp.tools.Tool ``` -Returns a FastMCP tool that calls a ClientX tool, for a `FastMCP` server's `tools=`, or `add_tool()`. Its parameters are the tool's `input_schema`, as it is, and the tool validates the model's arguments. A result that isn't an object is wrapped as `{"result": ...}`, as FastMCP wraps its own. The hints become MCP's annotations, and the tags FastMCP's. A `ToolError`'s message reaches the model, and any other exception's only its type. A sync client's tool runs in a worker thread. It needs FastMCP: `pip install "clientx[fastmcp]"`. See [Serving tools with FastMCP](tools.md#serving-tools-with-fastmcp). +Returns a FastMCP tool that calls a ClientX tool, for a `FastMCP` server's `tools=`, or `add_tool()`. It needs FastMCP: `pip install "clientx[fastmcp]"`. + +- Its parameters are the tool's `input_schema`, as it is, and the tool validates the model's arguments. +- A result that isn't an object is wrapped as `{"result": ...}`, as FastMCP wraps its own. +- The hints become MCP's annotations, and the tags FastMCP's. +- A `ToolError`'s message reaches the model, and any other exception's only its type. +- A sync client's tool runs in a worker thread. + +See [Serving tools with FastMCP](tools.md#serving-tools-with-fastmcp). ## From httpx2 diff --git a/docs/requests.md b/docs/requests.md index 045bfdd..fd36533 100644 --- a/docs/requests.md +++ b/docs/requests.md @@ -44,7 +44,7 @@ A parameter's name has no meaning of its own: one named `json` or `headers` foll | Helper | Sends the value as | It takes | |---|---|---| -| `Url()` | a path placeholder's value | a plain value | +| `Url()` | a path placeholder's value | a [plain value](#plain-values) | | `Query()` | a query parameter | a plain value or a list of them, or a model, dataclass or mapping to [spread](#spreading-a-model-dataclass-or-mapping) | | `Header()` | a header | a plain value, or a model, dataclass or mapping to spread | | `Json()` | the JSON body, or one of its fields | anything Pydantic can turn into JSON | @@ -52,15 +52,41 @@ A parameter's name has no meaning of its own: one named `json` or `headers` foll | `Form()` | a form field | a plain value or a list of them, or a model, dataclass or mapping to spread; with [`Send(json_part=True)`](#send), any value, as a JSON part | | `File()` | a file in a multipart form | `bytes`, a binary file, or a `(filename, content[, content_type[, headers]])` tuple, or a list of them; not `str` | -A plain value is a `str`, `int`, `float`, `bool`, `Enum`, `date`, `datetime`, `time`, `UUID`, `Decimal` or `bytes`, a `Literal` of those, or a `NewType` of one: each has one text form. Any other type, such as a class of your own, raises `DefinitionError` when the class is defined; annotate the parameter as `str` and convert the value at the call. `Any`, or no annotation, is the escape hatch: its value is sent in Pydantic's JSON form, so a list or dict becomes one compact JSON text value, and as `str(value)` only if Pydantic doesn't know its type. To repeat a key, annotate the parameter as a list. +### Plain values -The helpers are built on `pydantic.Field` and take its arguments. ClientX reads `alias=`, the name the value is sent under: `Annotated[int, Query(alias="userId")]`. A `description=` or a constraint such as `ge=1` documents the parameter, for example in a model's JSON Schema. ClientX checks arguments against them before sending only on a client created with `validate_arguments=True` (see [Validating arguments](configuration.md#validating-arguments)). +A path, query, header or form value must be a plain value: one Pydantic dumps to a single string, number or boolean. -A parameter's default goes after `=`, as for any parameter: `page: Annotated[int, Query()] = 1`. A default inside the helper, such as `Query(default=1)` or `Query(1)`, raises `DefinitionError`, since ClientX doesn't read it there. +- **Built in:** `str`, `int`, `float`, `bool`, `Enum`, `date`, `datetime`, `time`, `UUID`, `Decimal` and `bytes`, a `Literal` of those, or a `NewType` of one. +- **A type of your own, with a serializer:** `Annotated[Point, PlainSerializer(str, return_type=str), Query()]` sends `str(point)`. ClientX reads what a type dumps to from Pydantic's serialization schema. +- **`Any`, or no annotation:** the escape hatch. The value is sent in Pydantic's JSON form, so a list or dict becomes one compact JSON text value, and an object Pydantic doesn't know is sent as `str(value)`. +- **To repeat a key**, annotate the parameter as a list: `tags: Annotated[list[str], Query()]`. + +Any other type raises `DefinitionError` when the class is defined, and so does one whose dumped form Pydantic can't tell, such as a class of your own without a serializer. + +A Pydantic secret, `SecretStr`, `SecretBytes` or `Secret[...]`, raises `DefinitionError` in any part, JSON included: Pydantic dumps it as `**********`, so the API would get the stars. Pass credentials with the client's `auth=` (see [Authentication](configuration.md#authentication)). + +### Helper arguments + +The helpers are built on `pydantic.Field` and take its arguments. These matter most: + +- **`alias=`** is the name the value is sent under: `Annotated[int, Query(alias="userId")]`. +- **A constraint**, such as `ge=1`, is checked on every call (see [Validating arguments](#validating-arguments)). +- **`description=`** describes the parameter, for example in a tool's schema. + +### Defaults + +- **A default goes after `=`**, as for any parameter: `page: Annotated[int, Query()] = 1`. +- **Not inside the helper:** `Query(default=1)` or `Query(1)` raises `DefinitionError`, since type checkers don't see it there. +- **A `default_factory` goes inside the helper**, 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. ## Path parameters -Each `{placeholder}` in the path, including one in a [resource's prefix](resources.md#prefixes), is filled from the parameter with the same name. A placeholder that names no parameter raises `DefinitionError`, and so does a placeholder's parameter that isn't a plain value, can be `None` (`str | None`), or has a helper other than `Url()`. `Url()` is optional: it only marks the parameter, for example to describe it, and raises `DefinitionError` if the path has no placeholder for it. A path parameter is matched to its placeholder by name, so `Url(alias=...)` raises `DefinitionError` too. +Each `{placeholder}` in the path, including one in a [resource's prefix](resources.md#prefixes), is filled from the parameter with the same name, which must be a [plain value](#plain-values). `DefinitionError` is raised when the class is defined if: + +- A placeholder names no parameter. +- Its parameter can be `None` (`str | None`), or has a helper other than `Url()`. +- A `Url()` parameter has no placeholder. `Url()` is optional: it only marks the parameter, for example to describe it. +- A `Url()` has an `alias=`: a path parameter is matched to its placeholder by name. A value becomes text, as a query value does (see [Values as text](#values-as-text)), and is then percent-encoded, so a value such as `"a/b"` or `"../admin"` stays one path segment and can't add a query string. Don't encode values yourself: a `%` would be encoded again. For a value that spans segments, such as a file path, use `{name:path}`, which keeps the slashes and still encodes each segment: @@ -78,7 +104,11 @@ class ReposAPI(ClientX): There are no literal braces: a brace that isn't part of a placeholder, `{{` and `}}` included, raises `DefinitionError` when the class is defined, and so does a placeholder such as `{user-id}` or one with a converter other than `path` (`{user_id:int}`). -A value that would call a different path raises `ArgumentError` before anything is sent: `None`, which would be sent as `null` (it can only come through `Any`, or a parameter without an annotation); an empty value, since `/users/{user_id}` with `""` would call `/users/`; and in a `{name:path}` value, a leading, trailing or doubled slash. The error's `parameter` attribute names the parameter. +A value that would call a different path raises `ArgumentError` before anything is sent, with the parameter's name in its `parameter` attribute: + +- `None`, which would be sent as `null`. It can only come through `Any`, or a parameter without an annotation. +- An empty value: `/users/{user_id}` with `""` would call `/users/`. +- In a `{name:path}` value, a leading, trailing or doubled slash. ## Query parameters and headers @@ -112,7 +142,7 @@ class ItemsAPI(ClientX): - **Names.** A value is sent under its helper's `alias`, or else under the parameter's name. - **`None`.** A value of `None` is left out, and so is an empty list and a `None` in one, so an optional parameter defaults to `None`. -- **Defaults.** A default that isn't `None` is sent, like any other value, unless [`Send(exclude_unset=True)`](#send) leaves the parameter out when the caller doesn't pass it, so the server applies its own default. +- **Defaults.** A default that isn't `None` is sent, like any other value. To let the server apply its own default, make yours `None`. - **One key, one value.** Two values sent under one key, such as two parameters with the same alias, or a parameter and a field of a spread model, raise `DefinitionError` when the class is defined, since one would be lost. A spread mapping's keys are known only at the call, so avoiding a clash with them is up to you. - **The client's own.** Values set with the client's `params=` and `headers=` are sent too. An endpoint's value under the same name replaces the client's. @@ -131,7 +161,7 @@ Each value is sent as text: | A list or dict, through `Any` | Compact JSON text, as in a JSON body | | Any other object, through `Any` | `str(value)` | -A `Literal` or `NewType` of these types is sent as the value it holds. Any other type can only come through `Any`. A value that can't become text, such as `bytes` that aren't UTF-8, raises `ArgumentError` before anything is sent. +A `Literal` or `NewType` of these types is sent as the value it holds, and a type with a serializer as what it dumps to. Any other type can only come through `Any`. A value that can't become text, such as `bytes` that aren't UTF-8, raises `ArgumentError` before anything is sent. ### Query parameters @@ -154,14 +184,28 @@ A request has one kind of body: JSON, raw content, or a form. Parameters that wo A parameter marked `Json()` goes to the JSON body: -- **One parameter that isn't a plain value, or is typed `Any`, is the whole body.** A `post: Annotated[NewPost, Json()]` parameter sends the model's JSON, and an `items: Annotated[list[Item], Json()]` parameter sends the list. To send it under its name instead, add [`Send(embed=True)`](#send): `ids: Annotated[list[str], Json(), Send(embed=True)]` sends `{"ids": [...]}`. Adding a second `Json()` parameter moves the first under its name, as in FastAPI, so `Send(embed=True)` also keeps the body's shape fixed if you might add one later. +- **One parameter that isn't a plain value, or is typed `Any`, is the whole body.** `post: Annotated[NewPost, Json()]` sends the model's JSON, and `items: Annotated[list[Item], Json()]` sends the list. + - To send it under its name instead, add [`Send(embed=True)`](#send): `ids: Annotated[list[str], Json(), Send(embed=True)]` sends `{"ids": [...]}`. + - A second `Json()` parameter moves the first under its name, as in FastAPI, so `Send(embed=True)` also keeps the body's shape fixed if you might add one later. - **Otherwise, each JSON parameter is a field of a JSON object**, under its alias or name: `title: Annotated[str, Json()]` and `tags: Annotated[list[str], Json()]` send `{"title":"Hello","tags":["a","b"]}`. -- **Values are sent as Pydantic sends them in JSON mode.** A model uses its own serializers and is sent by alias, so `user_id: int = Field(alias="userId")` is sent as `"userId"`. Dates, UUIDs and enums become JSON values. A model's field that's `None` is sent as `null`, unless [`Send`](#send) says otherwise. A value Pydantic can't serialize raises `ArgumentError` before anything is sent, and so does a value holding NaN or infinity, which JSON can't hold. -- **`None` and defaults.** A JSON field left at its `None` default is left out, and one passed explicitly as `None` is sent as `null`, as a PATCH that clears a field needs. With a `nickname: Annotated[str | None, Json()] = None` parameter, `update(1)` sends no body, and `update(1, nickname=None)` sends `{"nickname":null}`. A default other than `None` is sent, as in the query string, unless [`Send(exclude_unset=True)`](#send) leaves the field out when the caller doesn't pass it. A body parameter that's `None` sends no body. +- **Values are sent as Pydantic sends them in JSON mode.** + - A model uses its own serializers and is sent by alias: `user_id: int = Field(alias="userId")` is sent as `"userId"`. + - Dates, UUIDs and enums become JSON values. + - A model's field that's `None` is sent as `null`. To leave it out, give the field `Field(exclude_if=lambda v: v is None)`. + - A value Pydantic can't serialize, or one holding NaN or infinity, which JSON can't hold, raises `ArgumentError` before anything is sent. +- **`None` and defaults.** + - A JSON field left at its `None` default is left out, and one passed explicitly as `None` is sent as `null`, as a PATCH that clears a field needs. With `nickname: Annotated[str | None, Json()] = None`, `update(1)` sends no body, and `update(1, nickname=None)` sends `{"nickname":null}`. + - A default other than `None` is sent, as in the query string. + - A body parameter that's `None` sends no body. ### Raw content -`Body()` sends a `str`, `bytes`, or a stream of `bytes` as the body, as it is: an iterable of `bytes` on a sync client, and an async iterable on an async one. Anything else, or a stream of the other kind, raises `DefinitionError` when the class is defined. An endpoint takes at most one `Body()` parameter. Set the content type with a header: +`Body()` sends the body as it is. It takes: + +- A `str` or `bytes`. +- A stream of `bytes`: an iterable on a sync client, and an async iterable on an async one. A stream needs Pydantic's `SkipValidation`, as in `Annotated[Iterator[bytes], Body(), SkipValidation]`: Pydantic can't validate one, so it's passed on as it is (see [Validating arguments](#validating-arguments)). + +Anything else, or a stream of the other kind, raises `DefinitionError` when the class is defined. An endpoint takes at most one `Body()` parameter. Set the content type with a header: ```python @@ -202,7 +246,17 @@ class ProfilesAPI(ClientX): `upload_avatar(("me.png", data, "image/png"))` sends a multipart form with the file `image` and the field `caption`. -A file is `bytes`, a binary file (`open(path, "rb")`, `io.BytesIO`, `IO[bytes]`), or a `(filename, content[, content_type[, headers]])` tuple, where `headers` is a mapping of the file part's own headers. A list of files sends each under the same field, and leaves out a `None` in it; a tuple is one file, so a list of files is a `list`, not a tuple. Several `File()` parameters can share a field with an alias, too. A `str` isn't a file: httpx2 would send the text itself as the file's content, so open the file yourself, or pass text as `bytes`. Any other type raises `DefinitionError` when the class is defined. +A file is one of: + +- `bytes`. +- A binary file: `open(path, "rb")`, `io.BytesIO`, `IO[bytes]`. +- A `(filename, content[, content_type[, headers]])` tuple, where `headers` is a mapping of the file part's own headers. + +A few rules: + +- **A list of files** sends each under the same field, and leaves out a `None` in it. A tuple is one file, so a list of files is a `list`, not a tuple. Several `File()` parameters can share a field with an alias, too. +- **A `str` isn't a file:** httpx2 would send the text itself as the file's content. Open the file yourself, or pass text as `bytes`. Any other type raises `DefinitionError` when the class is defined. +- **A binary file needs Pydantic's `SkipValidation`**, as in `Annotated[BinaryIO, File(), SkipValidation]`, and so does a tuple holding one: Pydantic can't validate a binary file, so it's passed on as it is. `bytes`, and tuples and lists of `str` and `bytes`, as above, are validated and need none. Without a file or a JSON part, the form is sent URL-encoded, so with an optional `File()` parameter, or an optional JSON part, the encoding depends on whether one is sent. @@ -258,7 +312,7 @@ class IssuesAPI(ClientX): `search(Filters(labels=["bug", "ui"]))` sends `GET /issues?state=open&labels=bug&labels=ui`. - Each field follows the part's rules, as a parameter would: it must be a plain value or, except in a header, a list of them. A field that doesn't fit raises `DefinitionError` when the class is defined. A field that's `None` is left out. -- Every other field is sent, defaults included. To send only the fields that were set, or those that differ from their defaults, add [`Send(exclude_unset=True)` or `Send(exclude_defaults=True)`](#send). +- Every other field is sent, defaults included. To leave a field out, give it `Field(exclude_if=...)` in the model. - A model's own serializers apply, and its fields are sent by alias. A computed field is sent like a field. A model with a `model_serializer` is spread by what it dumps, each key as it is, like a mapping: its keys are known only at the call, so a clash with them isn't caught when the class is defined. - A list in a header, from a field or mapping typed `Any`, is sent as one value, JSON text. - A helper on a model's field, such as `assignee: Annotated[str, Header()]`, raises `DefinitionError`: the parameter's helper decides where all of the model's fields go. @@ -270,11 +324,10 @@ The helper says where a parameter goes; `Send` says how it's sent there. Put it | Option | Works with | Effect | |---|---|---| | `embed=True` | `Json()` | Sends a lone JSON parameter under its alias or name, as a field of a JSON object, instead of as the whole body. FastAPI's `Body(embed=True)` does the same for the request it receives. | -| `exclude_unset=True` | `Json()`, `Query()`, `Header()`, `Form()` | Leaves out what the caller didn't set, so the server's defaults apply: the parameter, when the caller doesn't pass it, so `page: Annotated[int, Query(), Send(exclude_unset=True)] = 1` sends no `page` unless it's passed; and a model's fields that weren't set when it was made, for a PATCH with only the fields to change. | -| `exclude_none=True` | `Json()`, `Form()` | Leaves out the fields of a model or Pydantic dataclass that are `None`, instead of sending `null`. With `Form()`, only on a JSON part: a plain form leaves out `None` already, as do the query string and headers. On a JSON field, a `None` passed explicitly is then left out too. | -| `exclude_defaults=True` | `Json()`, `Query()`, `Header()`, `Form()` | Leaves out the fields of a model or Pydantic dataclass that equal their defaults. With `Query()` and `Header()`, on a spread model; with `Form()`, on a spread model or a JSON part. | | `json_part=True` | `Form()` | Sends the parameter's value as its own part of a multipart form, as JSON with the `application/json` content type, as some APIs take next to files (see [Forms and files](#forms-and-files)). | +To leave out a value, use pydantic's `exclude_if` on the helper, which takes `pydantic.Field`'s arguments: `note: Annotated[str | None, Json(exclude_if=lambda v: v is None)] = None` leaves `note` out when it's `None`. On a model's fields, use `Field(exclude_if=...)`. + Many APIs take a body such as `{"ids": [...]}`. Without `embed`, a lone `ids: Annotated[list[str], Json()]` would be the whole body, `[...]`: @@ -297,17 +350,17 @@ class HostsAPI(ClientX): To send it under another name, give it an alias with its helper: `ids: Annotated[list[str], Json(alias="deviceIds"), Send(embed=True)]` sends `{"deviceIds": [...]}`. ClientX reads the name only from its own helpers, so a plain `pydantic.Field(alias=...)` doesn't change it. -`exclude_unset`, `exclude_none` and `exclude_defaults` are Pydantic's dump options. They apply to a model anywhere in the value, such as each item of a `list[User]`. Each must have something to act on, or it raises `DefinitionError`, since Pydantic would ignore it silently: `exclude_none` and `exclude_defaults` need a model or a Pydantic dataclass (`pydantic.dataclasses.dataclass`), not a standard library one, and `exclude_unset` a default other than `None` to leave out (`None` is left out anyway), or a Pydantic model, the only kind that records which fields were set. - With several `Send` in one `Annotated`, such as one from a `type` alias and one on the parameter, the last one wins whole, as the last helper does. -`Send` where it can't apply raises `DefinitionError` when the class is defined: an option on a part that doesn't take it (set to `False` too), such as `embed` outside `Json()`; any `Send` on a path parameter; a dump option on a type it can't affect; or a `Send` nested inside the parameter's type or on a model's field. +An option on a part that doesn't take it, such as `embed` outside `Json()`, does nothing. A `Send` on a path parameter, nested inside the parameter's type, or on a model's field raises `DefinitionError` when the class is defined. ## Where a helper goes -Put the helper in the parameter's outermost `Annotated`, around the full type with `None` included: `Annotated[int | None, Query()]`. A helper nested inside another type, such as `Annotated[int, Query()] | None` or `list[Annotated[str, Query()]]`, raises `DefinitionError`. Use one helper per parameter; if there are several, the last one wins. +- **Put the helper in the parameter's outermost `Annotated`**, around the full type with `None` included: `Annotated[int | None, Query()]`. +- **A helper nested inside another type** raises `DefinitionError`, such as `Annotated[int, Query()] | None` or `list[Annotated[str, Query()]]`. +- **Use one helper per parameter.** If there are several, the last one wins. -Pydantic's own metadata, such as `Field(ge=1)`, isn't a helper and can go anywhere in the type. A serializer such as `PlainSerializer` raises `DefinitionError`, though: ClientX sends a value by its own type, so it wouldn't run. Convert the value at the call, or make it a field of a model, where its serializers apply. +Pydantic's own metadata, such as `Field(ge=1)` or `PlainSerializer`, isn't a helper and can go anywhere in the type, where it applies as it does in a model. To reuse an annotation, name it with a `type` alias, plain or generic: @@ -326,6 +379,37 @@ class PostsAPI(ClientX): def list_posts(self, user_id: UserId, trace_id: HeaderValue[str | None] = None) -> Response: ... ``` +## Validating arguments + +Each call's arguments are validated against their annotations before anything is sent, and the request is built from the validated values: + + +```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() as api: + try: + api.list_users(page=0) + except ArgumentError as error: + print(error.parameter) # page: no request was sent +``` + +- Validation is Pydantic's lax mode, which converts what it can: `"7"` fits an `int`, and a `dict` fits a model. The converted value is sent, so `3` for a `float` is sent as `3.0`. To make one parameter strict, give its helper `strict=True`: `Annotated[int, Query(strict=True)]`. +- A helper's constraints apply, such as `Query(ge=1)`, and so does Pydantic's metadata anywhere in the type. +- Only the arguments a call passes are validated, not the defaults. +- A model is sent as its annotated type, so a subclass's extra fields are left out. Annotate the parameter `SerializeAsAny[User]` to send them. +- A `dict` passed for a model is read as the model reads one, by alias, so `{"userId": 2}` fits `user_id: int = Field(alias="userId")`. Keys the model doesn't have are dropped. The model's own `model_config` can change both: `validate_by_name=True` takes `user_id` too, and `extra="allow"` keeps other keys. A tool, though, takes a model's fields by name, as its schema lists them. +- Pydantic can't validate a binary file or a stream, so a `File()` or `Body()` parameter whose type holds one, or `Any`, needs `SkipValidation` in its annotation, which passes the value on as it is. `str`, `bytes`, and file tuples and lists of them are validated and need none (see [Forms and files](#forms-and-files)). +- 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__`. + ## In a FastAPI app The helpers are named like FastAPI's, but they do the opposite job: FastAPI's read the incoming request, and ClientX's build the outgoing one. In a FastAPI app that calls other APIs, import one of them under another name (`from clientx import Query as ClientQuery`), or use the module (`import clientx`, then `clientx.Query()`). diff --git a/docs/tools.md b/docs/tools.md index d031729..6e6900b 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -65,6 +65,7 @@ Every endpoint on the client, and on the resources mounted on it, is a tool, exc | Returns `bytes`, such as a file download | A model can't read binary data, and it often isn't text, so it wouldn't become JSON. | Annotate text as `str`. Keep a file download for your code. | | Has `include_in_tools=False` | You keep it from models, such as an export that holds credentials (see [Keeping an endpoint from a model](#keeping-an-endpoint-from-a-model)). | Remove `include_in_tools=False`. | | Takes an argument with no JSON form, such as a binary file (`BinaryIO`) | A model sends its arguments as JSON. | Keep it for your code: a model can't send a file. | +| Takes an argument of your own type with a serializer but no validator, such as `Annotated[Point, PlainSerializer(str, return_type=str)]` | Pydantic can say what it sends, but not what a model should send in. | Add a validator that says what it takes: `PlainValidator(parse_point, json_schema_input_type=str)`. | | Has a private name, which starts with `_`, such as `_delete`, or is on a resource mounted under one | It's private in Python, so it's private from a model too: a method of yours can check something before calling it, and a model can't go around the check (see [Guarding an endpoint](#guarding-an-endpoint)). | Name it without the leading `_`. | An endpoint's second name in its class is the same endpoint, so it's listed once. A second name that isn't private is listed even when the first one is. @@ -178,8 +179,8 @@ def list_orders( - Arguments are named as in the method, not by a helper's `alias=`, which is the name sent to the API. - A model's fields are named as in Python too, in the arguments and in the result, and both schemas list them that way. ClientX still sends and reads the API's names: with `pet_id: int = Field(alias="petId")`, the model sees `pet_id` and the API `petId`. -- They're validated as Pydantic validates a call, leniently: `"7"` fits an `int`. -- Only the arguments the model gave are passed, so the rest keep their defaults, as in a Python call: a `Send(exclude_unset=True)` parameter the model left out isn't sent, and a JSON field left at `None` isn't sent as `null`. +- They're validated leniently, as every call is: `"7"` fits an `int` (see [Validating arguments](requests.md#validating-arguments)). An endpoint's tool validates them with the endpoint's own request model, so a helper's `strict=True` applies, and an argument the endpoint doesn't have is rejected. +- Only the arguments the model gave are passed, so the rest keep their defaults, as in a Python call: a JSON field left at `None` isn't sent as `null`. On an `AsyncClientX`, call tools with `await tool.acall(arguments)`. `call()` on an async tool, or `acall()` on a sync one, raises `TypeError`. @@ -456,7 +457,9 @@ print([each.name for each in list_tools(api)]) # ['order', 'product', 'order_pr `list_tools` lists `order_products` with the endpoints, and a model calls it the same way. As for an endpoint, it's named by its attribute path, described by its docstring, and its schemas come from its signature. With one call, the model gets each product in the order, instead of calling `order`, then `product` once per product. -- **It needs a docstring:** that's the tool's description, and there's no method and path to fall back on. It needs a return annotation too, which can't be `bytes`, and each argument and the result need a JSON form: a tool method without one raises `DefinitionError` when you list the tools, rather than being left out, since you made it a tool on purpose. +- **It needs a docstring:** that's the tool's description, and there's no method and path to fall back on. It needs a return annotation too, which can't be `bytes`. +- **Its parameters follow an endpoint's naming rule,** as its arguments are validated with a pydantic model of them: none can be named `model_config`, start with `_`, or have the name of a `BaseModel` attribute, such as `json`, or `@tool` raises `DefinitionError`. +- **Each argument and the result need a JSON form:** a tool method without one raises `DefinitionError` when you list the tools, rather than being left out, since you made it a tool on purpose. - **Its hints are `False` unless you set them,** as there's no HTTP method to take them from: `@tool(read_only=True)` is read-only, but neither destructive nor idempotent. They mean what they do for an endpoint (see [Hints](#hints)). Tag it with `@tool(tags=[...])`: a resource's tags go in front, as for an endpoint. - **It's the kind of its class,** as an endpoint is: `def` on a `ClientX` or `Resource`, and `async def` on an `AsyncClientX` or `AsyncResource`. - **A request it sends that fails raises `ToolError`,** as for an endpoint (see [Errors](#errors)). The message names only the HTTP method, as in `to a GET request`, since the tool's requests aren't one endpoint's. Other exceptions pass through. diff --git a/docs_src/configuration/validating_arguments.py b/docs_src/requests/validating_arguments.py similarity index 88% rename from docs_src/configuration/validating_arguments.py rename to docs_src/requests/validating_arguments.py index 9bed0fc..92b30fb 100644 --- a/docs_src/configuration/validating_arguments.py +++ b/docs_src/requests/validating_arguments.py @@ -8,7 +8,7 @@ class ExampleAPI(ClientX, base_url="https://api.example.com"): def list_users(self, page: Annotated[int, Query(ge=1)] = 1) -> None: ... -with ExampleAPI(validate_arguments=True) as api: +with ExampleAPI() as api: try: api.list_users(page=0) except ArgumentError as error: diff --git a/llms.txt b/llms.txt index 28389a8..93ad0f4 100644 --- a/llms.txt +++ b/llms.txt @@ -97,30 +97,30 @@ Rules for writing endpoints: - The return annotation decides what the endpoint returns: `-> None` nothing, `-> Response` the response with its body read (`clientx.Response` is `httpx2.Response`; `clientx` also re-exports `Auth`, `Request` and `Timeout`), `-> str` the text, `-> bytes` the content, `-> Iterator[str]` the body streamed as lines, `-> Iterator[bytes]` streamed as chunks (`AsyncIterator[...]` for `async def` endpoints), and any other type the JSON body validated against the full annotation by a Pydantic `TypeAdapter` (models, `list[User]`, dicts, dataclasses, `TypedDict`s, `Annotated` constraints). A body that doesn't match raises `pydantic.ValidationError`, a `ValueError`. A type Pydantic can't validate raises `DefinitionError` when the class is defined. There are no decoder classes. - `decoder=` takes any function `(response: httpx2.Response) -> T` in place of the annotation's decoding. Type checkers check that `T` matches the endpoint's annotation, at the decorator. The decoder does the validating, and its result is returned as is: build the model (`User.model_validate(response.json())`) or use a `TypeAdapter` in it; returning `response.json()` unchanged returns an unvalidated `dict`. The body is read before it runs, so it's a plain function (not `async def`), even for an `async def` endpoint. A generator decoder streams: a generator on a `def` endpoint annotated `-> Iterator[...]`, an async generator on an `async def` endpoint annotated `-> AsyncIterator[...]`. A decoder on an endpoint annotated `-> None` raises `DefinitionError`. - `stream=True`, only with `-> Response` and no `decoder=`, returns the open, unread response: the caller reads it (`iter_bytes()`, `iter_lines()`) and must close it. A streamed iterator closes its response when iteration ends, breaks or fails, or when the iterator is closed. -- Where each parameter goes is never guessed: (1) a parameter named like a `{placeholder}` fills it; (2) every other parameter needs a helper in its outermost `Annotated`, and goes where the helper says: `Url()` (a placeholder's value), `Query()`, `Header()`, `Json()` (the JSON body or one of its fields), `Body()` (the raw body: `str`, `bytes`, or a stream of `bytes`, an iterable on a sync client and an async iterable on an async one; the other kind raises `DefinitionError`), `Form()` (a form field), `File()` (a file in a multipart form: `bytes`, a binary file, or a `(filename, content[, content_type[, headers]])` tuple, or a list of them, which repeats the field, as several `File()` parameters with one alias can; never `str`, which httpx2 would send as the file's content). A parameter without a helper raises `DefinitionError`, models and plain values included: write `user: Annotated[NewUser, Json()]` and `page: Annotated[int, Query()] = 1`, not `user: NewUser` or `page: int = 1`. A parameter's name, such as `json` or `headers`, has no meaning of its own. -- The helpers wrap `pydantic.Field` and take its arguments. The name a value is sent under is `alias=`: `Annotated[int, Query(alias="userId")]`. A default goes after `=` (`page: Annotated[int, Query()] = 1`); a default inside the helper, such as `Query(1)` or `Query("userId")`, raises `DefinitionError`. A `description=` or constraint such as `ge=1` isn't checked before sending, unless the client is created with `validate_arguments=True`. +- Where each parameter goes is never guessed: (1) a parameter named like a `{placeholder}` fills it; (2) every other parameter needs a helper in its outermost `Annotated`, and goes where the helper says: `Url()` (a placeholder's value), `Query()`, `Header()`, `Json()` (the JSON body or one of its fields), `Body()` (the raw body: `str`, `bytes`, or a stream of `bytes`, an iterable on a sync client and an async iterable on an async one; the other kind raises `DefinitionError`), `Form()` (a form field), `File()` (a file in a multipart form: `bytes`, a binary file, or a `(filename, content[, content_type[, headers]])` tuple, or a list of them, which repeats the field, as several `File()` parameters with one alias can; never `str`, which httpx2 would send as the file's content). A `File()` or `Body()` whose type holds a binary file, a stream or `Any` needs Pydantic's `SkipValidation` (`Annotated[BinaryIO, File(), SkipValidation]`), or it raises `DefinitionError`: Pydantic can't validate a file or stream, so it's passed on as is. `str`, `bytes`, and file tuples and lists of them (`tuple[str, bytes, str]`) are validated and need none. A parameter without a helper raises `DefinitionError`, models and plain values included: write `user: Annotated[NewUser, Json()]` and `page: Annotated[int, Query()] = 1`, not `user: NewUser` or `page: int = 1`. A parameter's name, such as `json` or `headers`, has no meaning of its own. +- The helpers wrap `pydantic.Field` and take its arguments. The name a value is sent under is `alias=`: `Annotated[int, Query(alias="userId")]`. A default goes after `=` (`page: Annotated[int, Query()] = 1`); a default inside the helper, such as `Query(1)` or `Query("userId")`, raises `DefinitionError`. A `default_factory` goes in the helper with `= None` after it (`tags: Annotated[list[str] | None, Json(default_factory=list)] = None`); without `= None` it raises `DefinitionError`. A constraint such as `ge=1` is checked on every call (see Argument validation). A parameter can't be named `model_config`, start with `_`, or have the name of a Pydantic `BaseModel` attribute such as `json` (`DefinitionError`): rename it and send the old name with `alias=`. - Path values become text (an `Enum` its value, a `datetime` ISO 8601, a number or `bool` JSON text) and are percent-encoded as one segment, so `/`, `?`, `#` and `..` in a value can't change the path. Don't pre-encode values: `%` would be encoded again. `{name:path}` keeps slashes for a value such as a file path. There are no literal braces: any brace that isn't part of a placeholder, `{{` and `}}` included, or a converter other than `path`, raises `DefinitionError`. Placeholders in a resource prefix count too, and every placeholder needs a parameter, which must be a plain value that can't be `None` (not `str | None`), with no helper other than `Url()` and no alias (it's matched by name). A `None` (through `Any`) or empty value, or a `{name:path}` value with a leading, trailing or doubled slash, raises `ArgumentError` (with `.parameter`) before sending. -- Query parameters, headers and form fields are sent under the alias, or else the parameter's name; a header's name has underscores turned into hyphens (`request_id` becomes `request-id`). A list repeats a query parameter or form field (`?tag=a&tag=b`), and so does a tuple or set (whose order can vary between runs); `str | list[str]` takes either, decided at the call, and a `str` for a `Sequence[str]` is one value; a header takes one plain value, so join several yourself, and its name and value must be ASCII (`DefinitionError` for a name known when the class is defined, `ArgumentError` at the call otherwise). Values become text as path values do. `None` is left out, and so are an empty list and a `None` in one; any other default is sent, unless `Send(exclude_unset=True)` leaves the parameter out when the caller doesn't pass it. Two values under one key (two aliases, or a parameter and a spread field; header names ignoring case) raise `DefinitionError`. The client's own `params=` and `headers=` are sent too; an endpoint's value under the same name replaces the client's. -- A plain value is one of `str`, `int`, `float`, `bool`, `Enum`, `date`, `datetime`, `time`, `UUID`, `Decimal`, `bytes`, a `Literal` of those, or a `NewType` of one. Any other type for a path, query, header or form value, such as your own class, raises `DefinitionError`: annotate it `str` and convert at the call. `Any`, or no annotation, is the escape hatch: sent in Pydantic's JSON form (a list or dict as one compact JSON text value), and as `str(value)` only for a type Pydantic doesn't know. A value that can't become text raises `ArgumentError`. A Pydantic serializer (`PlainSerializer`, `WrapSerializer`) in a parameter's type raises `DefinitionError`, since values are sent by their own type. -- A request has one kind of body: JSON, raw `Body()` content (at most one), or a form (`Form()` fields, and `File()` files for a multipart form; without a file it's URL-encoded, so an optional `File()` changes the encoding with the value; a `Form()` parameter with `Send(json_part=True)` takes any value and is sent as its own JSON part, `application/json`, which makes the form multipart); two kinds raise `DefinitionError`. A lone JSON parameter that isn't a plain value, `Any` included, is the whole body; otherwise each JSON parameter is a field of a JSON object, under its alias or name. Adding a second `Json()` parameter moves the first under its name, as in FastAPI. Values are dumped as Pydantic dumps them in JSON mode, models by alias; a model's `None` field is sent as `null`. A JSON parameter left at its `None` default is left out, and one passed explicitly as `None` is sent as `null` (with `nickname: Annotated[str | None, Json()] = None`, `update(1)` sends no body and `update(1, nickname=None)` sends `{"nickname":null}`); any other default is sent, unless `Send(exclude_unset=True)`; a lone body parameter that's `None` sends no body. A value Pydantic can't serialize, or one holding NaN or infinity, raises `ArgumentError` before sending. -- `Send(embed=True)`, next to the helper in the outermost `Annotated`, sends a lone JSON parameter under its alias or name instead of as the whole body, as FastAPI's `Body(embed=True)` does: `ids: Annotated[list[str], Json(), Send(embed=True)]` sends `{"ids": [...]}`. With several `Send`, the last one wins whole. `Send(exclude_unset=True)`, `Send(exclude_none=True)` and `Send(exclude_defaults=True)` are Pydantic's dump options, for a model anywhere in a `Json()` value or a `Form()` JSON part (all three), or a model spread into `Query()`, `Header()` or `Form()` (`exclude_unset` and `exclude_defaults`): `user: Annotated[User, Json(), Send(exclude_unset=True)]` sends only the fields that were set, for a PATCH. `Send(exclude_unset=True)` also leaves out the parameter itself when the caller doesn't pass it, so the server's default applies. `exclude_none` and `exclude_defaults` need a model or Pydantic dataclass, and `exclude_unset` a default other than `None` (which is left out anyway) or a Pydantic model; with nothing to act on they raise `DefinitionError`, as Pydantic would ignore them. An option on a part that doesn't take it (`embed` outside `Json()`, `embed=False` too), any `Send` on a path parameter, or a `Send` nested inside the type or on a model's field, raises `DefinitionError`. -- A model, dataclass or mapping marked `Query()`, `Header()` or `Form()` is spread into that part: each field is a separate value, under its alias or name (hyphens for headers), and must be a plain value or, except in a header, a list of them; `None` fields are left out, and every other field is sent, defaults included, unless `Send(exclude_unset=True)` or `Send(exclude_defaults=True)` says otherwise. Computed fields are sent like fields; a model with a `model_serializer` is spread by what it dumps, like a mapping, its keys known only at the call. A helper on a model's field raises `DefinitionError`: the parameter's helper decides where all of its fields go. -- One helper per parameter, in the outermost `Annotated`, around the full type with `None` inside (`Annotated[int | None, Query()]`). A helper nested inside another type (`Annotated[int, Query()] | None`, `list[Annotated[str, Query()]]`) raises `DefinitionError`; with several helpers, the last one wins. Pydantic metadata such as `Field(ge=1)` isn't a helper and can go anywhere. Reuse annotations with `type` aliases: `type UserId = Annotated[int, Query(alias="userId")]`, or `type HeaderValue[T] = Annotated[T, Header()]`. +- Query parameters, headers and form fields are sent under the alias, or else the parameter's name; a header's name has underscores turned into hyphens (`request_id` becomes `request-id`). A list repeats a query parameter or form field (`?tag=a&tag=b`), and so does a tuple or set (whose order can vary between runs); `str | list[str]` takes either, decided at the call, and a `str` for a `Sequence[str]` raises `ArgumentError`, as Pydantic doesn't take a string as a sequence; a header takes one plain value, so join several yourself, and its name and value must be ASCII (`DefinitionError` for a name known when the class is defined, `ArgumentError` at the call otherwise). Values become text as path values do. `None` is left out, and so are an empty list and a `None` in one; any other default is sent (make it `None` to let the server's default apply), and so is a value `exclude_if` doesn't leave out (`Query(exclude_if=lambda v: v == 0)`). Two values under one key (two aliases, or a parameter and a spread field; header names ignoring case) raise `DefinitionError`. The client's own `params=` and `headers=` are sent too; an endpoint's value under the same name replaces the client's. +- A plain value is one Pydantic dumps to a single string, number or boolean, read from its serialization schema: `str`, `int`, `float`, `bool`, `Enum`, `date`, `datetime`, `time`, `UUID`, `Decimal`, `bytes`, a `Literal` of those, a `NewType` of one, or a type whose serializer dumps it to one (`Annotated[Point, PlainSerializer(str, return_type=str), Query()]`). Any other type for a path, query, header or form value, or one whose dumped form Pydantic can't tell, such as your own class without a serializer, raises `DefinitionError`, and so does a Pydantic secret (`SecretStr`, `SecretBytes`, `Secret[...]`) in any part, which would be sent as `**********`: use `auth=` for credentials. `Any`, or no annotation, is the escape hatch: sent in Pydantic's JSON form (a list or dict as one compact JSON text value), and as `str(value)` only for a type Pydantic doesn't know. A value that can't become text raises `ArgumentError`. A Pydantic serializer (`PlainSerializer`, `WrapSerializer`) in a parameter's type runs, as in a model. +- A request has one kind of body: JSON, raw `Body()` content (at most one), or a form (`Form()` fields, and `File()` files for a multipart form; without a file it's URL-encoded, so an optional `File()` changes the encoding with the value; a `Form()` parameter with `Send(json_part=True)` takes any value and is sent as its own JSON part, `application/json`, which makes the form multipart); two kinds raise `DefinitionError`. A lone JSON parameter that isn't a plain value, `Any` included, is the whole body; otherwise each JSON parameter is a field of a JSON object, under its alias or name. Adding a second `Json()` parameter moves the first under its name, as in FastAPI. Values are the validated ones, dumped as Pydantic dumps them in JSON mode, models by alias and as their annotated type (`SerializeAsAny[User]` keeps a subclass's extra fields); a model's `None` field is sent as `null` unless `Field(exclude_if=lambda v: v is None)` leaves it out. A JSON parameter left at its `None` default is left out, and one passed explicitly as `None` is sent as `null` (with `nickname: Annotated[str | None, Json()] = None`, `update(1)` sends no body and `update(1, nickname=None)` sends `{"nickname":null}`); any other default is sent; a lone body parameter that's `None` sends no body. A value Pydantic can't serialize, or one holding NaN or infinity, raises `ArgumentError` before sending. +- `Send(embed=True)`, next to the helper in the outermost `Annotated`, sends a lone JSON parameter under its alias or name instead of as the whole body, as FastAPI's `Body(embed=True)` does: `ids: Annotated[list[str], Json(), Send(embed=True)]` sends `{"ids": [...]}`. With several `Send`, the last one wins whole. `Send` has only `embed` (for `Json()`) and `json_part` (for `Form()`); on another helper an option does nothing. To leave a value out, use Pydantic's `exclude_if` on the helper (`Json(exclude_if=lambda v: v is None)`) or on a model's `Field`. A `Send` on a path parameter, nested inside the type, or on a model's field raises `DefinitionError`. +- A model, dataclass or mapping marked `Query()`, `Header()` or `Form()` is spread into that part: each field is a separate value, under its alias or name (hyphens for headers), and must be a plain value or, except in a header, a list of them; `None` fields are left out, and every other field is sent, defaults included, unless the field's `Field(exclude_if=...)` leaves it out. Computed fields are sent like fields; a model with a `model_serializer` is spread by what it dumps, like a mapping, its keys known only at the call. A helper on a model's field raises `DefinitionError`: the parameter's helper decides where all of its fields go. +- One helper per parameter, in the outermost `Annotated`, around the full type with `None` inside (`Annotated[int | None, Query()]`). A helper nested inside another type (`Annotated[int, Query()] | None`, `list[Annotated[str, Query()]]`) raises `DefinitionError`; with several helpers, the last one wins. Pydantic metadata such as `Field(ge=1)` or `PlainSerializer` isn't a helper and can go anywhere. Reuse annotations with `type` aliases: `type UserId = Annotated[int, Query(alias="userId")]`, or `type HeaderValue[T] = Annotated[T, Header()]`. - The helpers are named like FastAPI's but build the outgoing request. In a FastAPI app, import ClientX's under another name (`from clientx import Query as ClientQuery`) or use `clientx.Query()`. - Resources group endpoints: `class Users(Resource, prefix="/users")`, mounted as an instance (`users = Users()`, not `users = Users`, which raises `DefinitionError`) on a client or on another resource. Prefixes are absolute (they're not combined when nesting); put an API-wide prefix such as `/v1` in the base URL. A resource subclass inherits its parent's prefix unless it sets its own, and the prefix applies only to endpoints in its own body. A resource's `tags=` go before each endpoint's own, and a subclass's tags are added to its parent's, each tag once. Calling an endpoint on a resource that isn't mounted raises `DefinitionError`. An endpoint belongs to the class whose body it's in: a second name there (`QueryDevices = query_devices`) is fine, but putting it in another class raises `DefinitionError` (declare it again there). -- Clients and resources can have plain, undecorated methods, which call endpoints through `self`. Use them to normalize arguments (endpoint bodies never run, and ClientX sends values as given) and for pagination: a `next` URL can't be passed back as a path value, which is percent-encoded, so read its query parameters with `httpx2.URL(next).params` and call the list endpoint. +- Clients and resources can have plain, undecorated methods, which call endpoints through `self`. Use them to normalize arguments (endpoint bodies never run) and for pagination: a `next` URL can't be passed back as a path value, which is percent-encoded, so read its query parameters with `httpx2.URL(next).params` and call the list endpoint. - A `ClientX` is an `httpx2.Client`, so an endpoint or mounted resource on a client can't use any name the client has: `get`, `post`, `send`, `headers`, `close`, and the rest of httpx2's raise `DefinitionError`. They're free on a resource. An endpoint's name also hides that name for the rest of the class body: with bare imports (`from clientx.method import get`), a method called `get` replaces the decorator; a method called `list` makes a later `list[Post]` fail with `TypeError: 'function' object is not subscriptable` (define it last, or write `builtins.list[Post]`). Using clients: -- `ClientX(base_url=None, *, user_agent=None, raise_for_status=None, validate_arguments=False, **options)`: `base_url` is required unless the class sets one, and every other keyword is an `httpx2.Client` option (`auth`, `headers`, `params`, `cookies`, `timeout`, `verify`, `proxy`, `transport`, `mounts`, `event_hooks`, `follow_redirects`...). A client is an `httpx2.Client`, so its settings can be changed after it's created, and `api.get(url)` sends a one-off httpx2 request (not decoded, and it doesn't raise for a 4xx or 5xx). `base_url=` and `user_agent=` are the only class arguments (`class ExampleAPI(ClientX, base_url="https://api.example.com", user_agent="example-api/1.0")`, then `ExampleAPI()`); a subclass keeps its parent's, a `base_url` given when creating a client wins, a base URL without a scheme and host raises `DefinitionError` in the class statement or `ValueError` when creating a client, no base URL in either place raises `TypeError` when the client is created, and any other keyword in the class statement raises `TypeError: ...__init_subclass__() takes no keyword arguments`. The `User-Agent` lists products, most significant first: the app's (`user_agent=`, else one in `headers=`), then the class's `user_agent=`, then `ClientX/`, leaving out any that isn't set, as in `my-app/1.0 example-client/0.1 ClientX/`; set `client.headers["User-Agent"]` after creating the client to send one exact value. A client's `repr` hides a password in the base URL. Close a client with `with` or `close()`; a long-lived client (web app, worker) is created once, reused, and closed at shutdown; a closed client can't be reused (`RuntimeError`). +- `ClientX(base_url=None, *, user_agent=None, raise_for_status=None, **options)`: `base_url` is required unless the class sets one, and every other keyword is an `httpx2.Client` option (`auth`, `headers`, `params`, `cookies`, `timeout`, `verify`, `proxy`, `transport`, `mounts`, `event_hooks`, `follow_redirects`...). A client is an `httpx2.Client`, so its settings can be changed after it's created, and `api.get(url)` sends a one-off httpx2 request (not decoded, and it doesn't raise for a 4xx or 5xx). `base_url=` and `user_agent=` are the only class arguments (`class ExampleAPI(ClientX, base_url="https://api.example.com", user_agent="example-api/1.0")`, then `ExampleAPI()`); a subclass keeps its parent's, a `base_url` given when creating a client wins, a base URL without a scheme and host raises `DefinitionError` in the class statement or `ValueError` when creating a client, no base URL in either place raises `TypeError` when the client is created, and any other keyword in the class statement raises `TypeError: ...__init_subclass__() takes no keyword arguments`. The `User-Agent` lists products, most significant first: the app's (`user_agent=`, else one in `headers=`), then the class's `user_agent=`, then `ClientX/`, leaving out any that isn't set, as in `my-app/1.0 example-client/0.1 ClientX/`; set `client.headers["User-Agent"]` after creating the client to send one exact value. A client's `repr` hides a password in the base URL. Close a client with `with` or `close()`; a long-lived client (web app, worker) is created once, reused, and closed at shutdown; a closed client can't be reused (`RuntimeError`). - Async: subclass `AsyncClientX` (an `httpx2.AsyncClient`, with the same arguments) and write endpoints as `async def` methods with the same decorators. `await api.users.retrieve(42)` returns the decoded value, and `asyncio.gather(...)` sends requests concurrently. Group async endpoints with `AsyncResource`, which mounts only on an `AsyncClientX` or another `AsyncResource`. An endpoint of the wrong kind for its class, a resource mounted on the other kind, or a class that subclasses both kinds raises `DefinitionError` when the class is defined. Stream with `-> AsyncIterator[str]` and `async for line in await api.events()`. Close with `async with` or `await client.aclose()`. Transports and event hooks must be async. Test with anyio's pytest plugin, which comes with httpx2: `@pytest.mark.anyio async def test_...`. - Authentication: pass credentials with `auth=` when creating the client, never as endpoint parameters. `auth=` is httpx2's authentication option; for what it accepts and how to write an `Auth` subclass, see https://pydantic.dev/docs/httpx2/advanced/authentication/. Don't add credentials in a request event hook: a request hook runs again for each redirect, putting back the `Authorization` header httpx2 drops for another host. Use a third-party library's `Auth` class, not its client class. - Status codes: a 4xx or 5xx response raises `httpx2.HTTPStatusError` from every endpoint, with the body already read (`error.response.json()` works) and before anything is decoded. A redirect isn't an error, and httpx2 follows redirects only with `follow_redirects=True`; without it, the redirect response is what's decoded. A streamed error response is read and closed before raising. Turn it off for a client with `ClientX(..., raise_for_status=False)`, or per endpoint with `@method.get(..., raise_for_status=False)` (the endpoint's setting wins); an error response is then decoded like any other, so annotate the endpoint `-> Response`. -- Argument validation: off by default. `ClientX(..., validate_arguments=True)` checks each call's arguments against their annotations before sending: strictly (`"7"` doesn't fit an `int`), with a helper's constraints (`Query(ge=1)`), only the arguments the call passes (not defaults), and without changing what's sent; a model instance isn't validated again, and a 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 a class Pydantic doesn't know; a stream's items are never checked (Pydantic's supported types: https://pydantic.dev/docs/validation/latest/api/pydantic/standard_library_types/). One that doesn't fit raises `ArgumentError` (`.parameter` is the first; the message lists every problem; `__cause__` is the `pydantic.ValidationError`). It's set for the whole client, not per endpoint. +- Argument validation: every call's arguments are validated against their annotations before sending, with a Pydantic model of the endpoint's parameters, and the request is built from the validated values. It's Pydantic's lax mode (`"7"` fits an `int`, and `3` for a `float` is sent as `3.0`); a helper's `strict=True` makes one parameter strict (`Query(strict=True)`). A helper's constraints (`Query(ge=1)`) and Pydantic metadata apply; only the arguments the call passes are validated, not defaults. A `dict` for a model is read as the model reads one: by alias, dropping keys it doesn't have, unless its `model_config` sets `validate_by_name=True` or `extra="allow"` (a tool reads a model's fields by name). One that doesn't fit raises `ArgumentError` (`.parameter` is the first; the message lists every problem; `__cause__` is the `pydantic.ValidationError`). There's no setting to turn it off; `SkipValidation` in an annotation passes that value on unchecked, and binary files and streams need it. - Test clients without the network: `ExampleAPI("https://api.example.com", transport=httpx2.MockTransport(handler))`, where `handler(request: httpx2.Request) -> httpx2.Response` records each request (assert on `request.method`, `request.url.path`, `request.url.params`, `request.headers`, `request.content`) and returns the response to decode, or a 4xx to test `HTTPStatusError`. For a streaming endpoint, give the response an iterator of bytes (`content=iter([b"a\n"])`). -- Errors: ClientX raises `DefinitionError` (a `TypeError`) and `ArgumentError` (a `ValueError`), both `clientx.ClientXError`. `DefinitionError` is raised when the class is defined for a mistake in an endpoint, a path, a helper or a class, and at call time for an endpoint on an unmounted resource. `ArgumentError` is raised before sending for a path value that would change the path, a JSON value Pydantic can't serialize or that holds NaN or infinity, a value that can't become text, or a header name or value that isn't ASCII, and, on a client with `validate_arguments=True`, for an argument that doesn't fit its annotation. A response that doesn't match the annotation raises `pydantic.ValidationError`. HTTP errors come from httpx2: `HTTPStatusError`, and `RequestError` for connection errors and timeouts. Annotations are evaluated when the method is decorated, so `from __future__ import annotations` works; the types they name must be defined before the class, and, in string annotations, at module level. -- AI tools: `from clientx.tools import list_tools, tool, ToolError, ToolOptions`. `list_tools(api)` takes a client instance (calls go through its base URL and `auth=`; creating one doesn't connect) and returns one `Tool` per endpoint a model can use, named by attribute path (`users_create`). Left out: streams (`-> Iterator[...]`, `stream=True`), `-> Response` (annotate what the API returns instead, such as a model or `dict[str, Any]`), `-> bytes` (binary a model can't read; annotate text as `str`), arguments with no JSON form (a binary file), endpoints with `include_in_tools=False` (the client's author keeps them from every app that serves the tools; use it for a public endpoint, and a private name for one a `@tool` method guards), and private names (`_delete`), with everything on a resource mounted under one (a second name that isn't private is listed). So a `@tool` method can guard a private endpoint, which a model can't go around: it checks first, raises `ArgumentError` to refuse (the model sees its message in the `ToolError`), then calls the endpoint. Each `Tool` has `description` (the docstring up to its first section, such as `Args:` or `Raises:`, else the method and path), a compact `input_schema` (plain JSON Schema; parameters named as in the method, not by alias, and a model's fields by name, not alias, in both schemas, the arguments and the result, while the API still gets and sends its aliases; each described by its helper's `description=`, else its docstring `Args:` entry; no titles; models written in place, keeping a model's docstring and its fields' `Field(description=...)`, as `output_schema` does too; a docstring under a field only with `use_attribute_docstrings=True`), `output_schema` (`None` for `-> None`), the hints `read_only` (changes nothing), `destructive` (can delete or overwrite; `False` means it only adds) and `idempotent` (repeating has no further effect), each worked out separately: the endpoint's `tool_options=ToolOptions(...)` value if set, else the HTTP method's, so with no `tool_options=` all three come from the method (`GET`, `HEAD`, `OPTIONS`: read-only and idempotent; `PUT`, `DELETE`: destructive and idempotent; `PATCH`: destructive; `POST`: none), which don't imply each other (`read_only=False` on a `GET` stays idempotent unless `idempotent=False` is set; read-only with destructive raises `DefinitionError`), `tags` (a tuple, the resource's first), `deprecated` (the endpoint's `deprecated=` message or `None`: a deprecated endpoint is still listed, and its description starts with `Deprecated: ` and a blank line; leave it out with `if not t.deprecated`), `is_async`, and `call(arguments)` (`await acall(arguments)` on an `AsyncClientX`; the wrong one raises `TypeError`). A call validates leniently (`"7"` fits an `int`), passes only the arguments given (so defaults and `Send(exclude_unset=True)` behave as in Python), and returns JSON-ready data. A failure raises `ToolError` (a `ClientXError`, with `.tool`) whose message is for the model: each bad argument, the API's own error body (up to 2,000 characters) with the method and path template, or what failed; never the host or query string; the original error is `__cause__`. Other exceptions, such as a decoder's own, pass through. No AI library is needed. `@tool(read_only=False, destructive=False, idempotent=False, tags=None)` makes a method of a client or resource a tool too, listed and called like an endpoint and named by attribute path, for work that takes several requests, such as fetching an order and then each of its products: it needs a docstring (its description) and a return annotation; its hints are `False` unless set (there's no HTTP method to fall back on); a resource's tags go before its own; it's `def` on `ClientX`/`Resource` and `async def` on the async ones; one whose arguments or result have no JSON form raises `DefinitionError` from `list_tools`; its HTTP errors name only the method (`to a GET request`). `@tool` on an endpoint raises `DefinitionError` (use `tool_options=`), and so does `@tool` on a private name or on a method that returns `bytes`. +- Errors: ClientX raises `DefinitionError` (a `TypeError`) and `ArgumentError` (a `ValueError`), both `clientx.ClientXError`. `DefinitionError` is raised when the class is defined for a mistake in an endpoint, a path, a helper or a class, and at call time for an endpoint on an unmounted resource. `ArgumentError` is raised before sending for a path value that would change the path, a JSON value Pydantic can't serialize or that holds NaN or infinity, a value that can't become text, a header name or value that isn't ASCII, and an argument that doesn't fit its annotation. A response that doesn't match the annotation raises `pydantic.ValidationError`. HTTP errors come from httpx2: `HTTPStatusError`, and `RequestError` for connection errors and timeouts. Annotations are evaluated when the method is decorated, so `from __future__ import annotations` works; the types they name must be defined before the class, and, in string annotations, at module level. +- AI tools: `from clientx.tools import list_tools, tool, ToolError, ToolOptions`. `list_tools(api)` takes a client instance (calls go through its base URL and `auth=`; creating one doesn't connect) and returns one `Tool` per endpoint a model can use, named by attribute path (`users_create`). Left out: streams (`-> Iterator[...]`, `stream=True`), `-> Response` (annotate what the API returns instead, such as a model or `dict[str, Any]`), `-> bytes` (binary a model can't read; annotate text as `str`), arguments with no JSON form (a binary file, or a type of your own with a serializer but no validator: add `PlainValidator(parse, json_schema_input_type=str)`), endpoints with `include_in_tools=False` (the client's author keeps them from every app that serves the tools; use it for a public endpoint, and a private name for one a `@tool` method guards), and private names (`_delete`), with everything on a resource mounted under one (a second name that isn't private is listed). So a `@tool` method can guard a private endpoint, which a model can't go around: it checks first, raises `ArgumentError` to refuse (the model sees its message in the `ToolError`), then calls the endpoint. Each `Tool` has `description` (the docstring up to its first section, such as `Args:` or `Raises:`, else the method and path), a compact `input_schema` (plain JSON Schema; parameters named as in the method, not by alias, and a model's fields by name, not alias, in both schemas, the arguments and the result, while the API still gets and sends its aliases; each described by its helper's `description=`, else its docstring `Args:` entry; no titles; models written in place, keeping a model's docstring and its fields' `Field(description=...)`, as `output_schema` does too; a docstring under a field only with `use_attribute_docstrings=True`), `output_schema` (`None` for `-> None`), the hints `read_only` (changes nothing), `destructive` (can delete or overwrite; `False` means it only adds) and `idempotent` (repeating has no further effect), each worked out separately: the endpoint's `tool_options=ToolOptions(...)` value if set, else the HTTP method's, so with no `tool_options=` all three come from the method (`GET`, `HEAD`, `OPTIONS`: read-only and idempotent; `PUT`, `DELETE`: destructive and idempotent; `PATCH`: destructive; `POST`: none), which don't imply each other (`read_only=False` on a `GET` stays idempotent unless `idempotent=False` is set; read-only with destructive raises `DefinitionError`), `tags` (a tuple, the resource's first), `deprecated` (the endpoint's `deprecated=` message or `None`: a deprecated endpoint is still listed, and its description starts with `Deprecated: ` and a blank line; leave it out with `if not t.deprecated`), `is_async`, and `call(arguments)` (`await acall(arguments)` on an `AsyncClientX`; the wrong one raises `TypeError`). A call validates leniently (`"7"` fits an `int`), an endpoint's with its request model, so an argument it doesn't have is rejected, passes only the arguments given (so defaults behave as in Python), and returns JSON-ready data. A failure raises `ToolError` (a `ClientXError`, with `.tool`) whose message is for the model: each bad argument, the API's own error body (up to 2,000 characters) with the method and path template, or what failed; never the host or query string; the original error is `__cause__`. Other exceptions, such as a decoder's own, pass through. No AI library is needed. `@tool(read_only=False, destructive=False, idempotent=False, tags=None)` makes a method of a client or resource a tool too, listed and called like an endpoint and named by attribute path, for work that takes several requests, such as fetching an order and then each of its products: it needs a docstring (its description) and a return annotation; its parameters can't be named `model_config`, start with `_`, or name a `BaseModel` attribute such as `json` (`DefinitionError` at `@tool`), as its arguments are validated with a pydantic model, as an endpoint's are; its hints are `False` unless set (there's no HTTP method to fall back on); a resource's tags go before its own; it's `def` on `ClientX`/`Resource` and `async def` on the async ones; one whose arguments or result have no JSON form raises `DefinitionError` from `list_tools`; its HTTP errors name only the method (`to a GET request`). `@tool` on an endpoint raises `DefinitionError` (use `tool_options=`), and so does `@tool` on a private name or on a method that returns `bytes`. - Writing endpoint docstrings for a model: the summary says what the endpoint does; the paragraph after it says when to use it and what to expect (side effects, limits, paging, errors such as a 404), since later sections never reach the model; `Args:` gives each argument's format, unit and allowed values; prefer types that say it (`Literal[...]` becomes an `enum`, `Query(le=100)` a maximum); use Markdown, not reStructuredText (`` ``x`` `` and `::` reach the model raw). - Registering tools: `input_schema` is accepted as is; only the wrapper differs. Anthropic: `{"name", "description", "input_schema"}`; OpenAI Responses: `{"type": "function", "name", "description", "parameters"}`; OpenAI Chat Completions: the same nested under `"function"`; MCP: `inputSchema`, with the hints as `annotations.readOnlyHint`, `destructiveHint` and `idempotentHint`, and an `outputSchema` that must describe an object (wrap a list as `{"result": ...}`). Turn a `ToolError` into the framework's error result with its message. Serving over MCP: `from clientx.fastmcp import fastmcp_tool` (needs `pip install "clientx[fastmcp]"`) turns a `Tool` into a FastMCP tool: `server = FastMCP("shop", tools=[fastmcp_tool(t) for t in list_tools(api) if t.read_only])` (`server.add_tool(fastmcp_tool(t))` adds one later), next to the server's own `@server.tool` functions, which still work after `tools=`; the server's name, transport and auth are FastMCP's. Its parameters are `input_schema` as is (the ClientX tool validates leniently, only the given arguments); a non-object result is wrapped as `{"result": ...}` with `x-fastmcp-wrap-result`; hints become `readOnlyHint`/`destructiveHint`/`idempotentHint` and tags FastMCP's; a `ToolError`'s message reaches the model, any other exception only as ` failed unexpectedly ().`; a `ClientX` tool's `call()` runs in a worker thread (prefer `AsyncClientX` for a server). Strict modes need schema changes ClientX doesn't make (OpenAI: every property in `required`, optional ones nullable; Anthropic: `additionalProperties: false` and `required`). Register only the tools a model should use: tag those endpoints, or their resource, and keep `[t for t in list_tools(api) if "ai" in t.tags]`; the hints are another start (`[t for t in list_tools(api) if t.read_only]`): set them with `tool_options=` where the HTTP method is wrong, such as `POST /search`, which only reads. - Serving many users (such as a public MCP server calling an API for each user): serve the tools with FastMCP (`FastMCP("shop", auth=JWTVerifier(...), tools=[fastmcp_tool(t) for t in list_tools(api)])`) and use one shared `AsyncClientX` whose `auth=` is an `httpx2.Auth` whose `auth_flow` calls FastMCP's `get_access_token()` (from `fastmcp.server.dependencies`) and sends the upstream token stored for its `subject`. FastMCP keeps each request's validated token in that request's context, so concurrent users don't mix; a sync client works too, as `fastmcp_tool` runs its calls in worker threads that keep the context, but prefer `AsyncClientX`. Never pass the token the user's app sent your server through to the upstream API (the MCP specification forbids token passthrough). Refresh tokens inside `auth_flow` on a 401. Users who need a different base URL need separate clients. diff --git a/src/clientx/_annotations.py b/src/clientx/_annotations.py new file mode 100644 index 0000000..3414d00 --- /dev/null +++ b/src/clientx/_annotations.py @@ -0,0 +1,326 @@ +"""Tell what a parameter's type is: a plain value, a file, a model, and so on. + +The rules (``_request_rules``) and routes (``_request_routes``) ask these about +a parameter's annotation, or a part of it, when the class is defined. Each +takes one type, ``Annotated`` and ``type`` aliases unwrapped where it matters: + +- A union splits into its arms, ``None`` left out (``union_arms``), and + ``allows_none`` asks about ``None``. +- A plain value is on an allow-list (``_PLAIN_TYPES``): ``str``, ``int``, + ``float``, ``bool``, ``Enum``, ``date``, ``datetime``, ``time``, ``UUID``, + ``Decimal``, ``bytes``, a ``Literal`` of those, or a ``NewType`` of one. + ``Any``, or no annotation, is the escape hatch. +- A file is ``bytes``, a binary file, or a ``(filename, content[, + content_type[, headers]])`` tuple; a raw body is ``str``, ``bytes``, or a + stream of bytes. ``holds_only_text_and_bytes`` tells one pydantic can + validate from a binary file or stream, which it can't. +- A model, dataclass or mapping has fields (``has_fields``, ``fields_of``). +- ``contains_metadata`` searches a type, and every type inside it, for + ``Annotated`` metadata, such as a helper (``is_helper``) or ``Send``. +""" + +from __future__ import annotations + +import io +from collections.abc import AsyncIterable, Callable, Iterable, Iterator, Mapping +from dataclasses import fields, is_dataclass +from datetime import date, datetime, time +from decimal import Decimal +from enum import Enum +from types import NoneType, UnionType +from typing import ( + IO, + Any, + Literal, + TextIO, + TypeAliasType, + Union, + cast, + get_args, + get_origin, + get_type_hints, +) +from uuid import UUID + +from pydantic import BaseModel, Secret, SecretBytes, SecretStr +from pydantic.dataclasses import is_pydantic_dataclass + +from clientx._arguments import get_httpx_argument +from clientx._signature import NO_VALUE, unwrap_annotated +from clientx._types import Send + +# Pydantic's secret types. SecretStr and SecretBytes don't subclass Secret. +_SECRET_TYPES = (SecretStr, SecretBytes, Secret) + + +# --- Metadata in a type ------------------------------------------------------- +def contains_metadata(annotation: Any, wanted: Callable[[object], bool]) -> bool: + """Return whether ``annotation``, or a type inside it, has ``wanted``.""" + return any(wanted(meta) for _, metadata in _walk(annotation) for meta in metadata) + + +def is_helper(meta: object) -> bool: + """Return whether ``meta`` is a ``clientx.arguments`` helper's field.""" + return get_httpx_argument(meta) is not None + + +def is_send(meta: object) -> bool: + """Return whether ``meta`` is a ``Send``.""" + return isinstance(meta, Send) + + +def contains_secret(annotation: Any) -> bool: + """Return whether ``annotation``, or a type inside it, is a pydantic secret. + + That's ``SecretStr``, ``SecretBytes`` or ``Secret[...]``, which pydantic + dumps as ``"**********"``. + """ + return any((cls := class_of(base)) is not None and issubclass(cls, _SECRET_TYPES) for base, _ in _walk(annotation)) + + +def _walk(annotation: Any, seen: frozenset[TypeAliasType] = frozenset()) -> Iterator[tuple[Any, tuple[Any, ...]]]: + """Yield the type and each type inside it, outermost first. + + Each comes split by ``unwrap_annotated`` into its type and its metadata. + That expands a ``type`` alias too, so metadata inside one counts. ``seen`` + holds the aliases already expanded on the way here, so one that contains + itself, such as ``type Value = dict[str, Value] | str``, is expanded only + once. + """ + alias = annotation if isinstance(annotation, TypeAliasType) else get_origin(annotation) + if isinstance(alias, TypeAliasType): + if alias in seen: + return + seen |= {alias} + base, metadata = unwrap_annotated(annotation) + yield base, metadata + for arg in get_args(base): + yield from _walk(arg, seen) + + +# --- What a type is ----------------------------------------------------------- +# The plain-value allow-list: each has one defined text form. A subclass counts +# too, so bool (an int), datetime (a date) and any Enum are in. +_PLAIN_TYPES = (str, int, float, bool, Enum, date, datetime, time, UUID, Decimal, bytes) + + +def is_plain(annotation: Any) -> bool: + """Return whether a value of this type is sent as one piece of text. + + It is if it's on the allow-list (a ``NewType`` of one counts), a + ``Literal`` of values on it, or ``Any`` or no annotation, the escape hatch. + It takes one type: ``all_plain`` splits a union first. + """ + if annotation is Any or annotation is NO_VALUE: + return True + if get_origin(annotation) is Literal: + # Literal["asc", "desc"]: each value is plain. None is left out. + return all(value is None or isinstance(value, _PLAIN_TYPES) for value in get_args(annotation)) + cls = class_of(annotation) + return cls is not None and issubclass(cls, _PLAIN_TYPES) + + +# How deep union_arms follows unions inside unions, so a type alias that +# contains itself, such as ``type U = int | U``, can't recurse forever. +_MAX_UNION_DEPTH = 100 + + +def union_arms(annotation: Any, depth: int = 0) -> list[Any]: + """Return the types a value of ``annotation`` can have, without ``None``. + + For a union, they're its members, each without ``Annotated`` or a ``type`` + alias, and a union inside a union is flattened: ``int | (str | None)`` gives + ``[int, str]``. A type that isn't a union is the only one. + """ + base, _ = unwrap_annotated(annotation) + if base is NoneType: + return [] + # Union is Optional[int] and Union[int, str]; UnionType is int | str. + if get_origin(base) not in {Union, UnionType} or depth > _MAX_UNION_DEPTH: + return [base] + return [arm for member in get_args(base) for arm in union_arms(member, depth + 1)] + + +def all_plain(annotation: Any) -> bool: + return all(is_plain(arm) for arm in union_arms(annotation)) + + +def allows_none(annotation: Any, depth: int = 0) -> bool: + """Return whether ``None`` is one of the types a value can have. + + ``union_arms`` drops ``None``, so this is how to ask about it: + ``int | None``, ``Optional[int]`` and ``Literal["a", None]`` allow it. + """ + base, _ = unwrap_annotated(annotation) + if base is NoneType or base is None: + return True + if get_origin(base) is Literal: + return None in get_args(base) + if get_origin(base) not in {Union, UnionType} or depth > _MAX_UNION_DEPTH: + return False + return any(allows_none(member, depth + 1) for member in get_args(base)) + + +def class_of(annotation: Any) -> type[Any] | None: + """Return the class a type stands for, or ``None`` if it isn't one. + + ``list[str]`` stands for ``list``, and ``NewType("UserId", int)`` for + ``int``. ``Literal["a"]`` and a ``TypeVar``, for example, aren't classes. + """ + # A NewType isn't a class; the type it's made from is. + while hasattr(annotation, "__supertype__"): + annotation = annotation.__supertype__ + # get_origin gives list for list[str], and None for a plain class like int. + cls: object = get_origin(annotation) or annotation + return cast("type[Any]", cls) if isinstance(cls, type) else None + + +def has_fields(annotation: Any) -> bool: + """Return whether the type is a model, dataclass or mapping: has fields.""" + cls = class_of(annotation) + return cls is not None and (issubclass(cls, BaseModel | Mapping) or is_dataclass(cls)) + + +def fields_of(cls: type[Any]) -> dict[str, tuple[Any, str | None]]: + """Return each field's type and serialization alias, by attribute name. + + A model's computed fields count too: they're dumped like fields. + """ + if issubclass(cls, BaseModel): + model_fields = {name: (info.annotation, info.serialization_alias) for name, info in cls.model_fields.items()} + computed = {name: (info.return_type, info.alias) for name, info in cls.model_computed_fields.items()} + return model_fields | computed + if is_pydantic_dataclass(cls): + return {name: (info.annotation, info.serialization_alias) for name, info in cls.__pydantic_fields__.items()} + # A standard library dataclass: its fields have no aliases. + hints = get_type_hints(cls) + return {field.name: (hints.get(field.name, Any), None) for field in fields(cls)} + + +def has_model_serializer(cls: type[Any]) -> bool: + """Return whether a model or pydantic dataclass has a model serializer.""" + decorators = getattr(cls, "__pydantic_decorators__", None) + return decorators is not None and bool(decorators.model_serializers) + + +# The classes pydantic validates and dumps back as they were, so a file or raw +# body made only of them needs no SkipValidation. +_TEXT_AND_BYTES_CLASSES = (str, bytes, NoneType, tuple, list, dict) + + +def holds_only_text_and_bytes(annotation: Any) -> bool: + """Return whether the type is made of text and bytes alone. + + It is if it, and every type inside it, is ``str``, ``bytes``, ``None``, a + union, or a ``tuple``, ``list`` or ``dict``: a file tuple such as ``(str, + bytes, str)``, or a list of them. A binary file, a stream or ``Any`` isn't. + """ + for base, _ in _walk(annotation): + if get_origin(base) in {Union, UnionType}: + continue + cls = class_of(base) + if cls is None or not issubclass(cls, _TEXT_AND_BYTES_CLASSES): + return False + return True + + +def is_file(annotation: Any) -> bool: + """Return whether a value of this type is one file httpx2 can send. + + That's file content (``bytes`` or a binary file), a ``(filename, + content[, content_type[, headers]])`` tuple, or ``Any``. Not ``str``: + httpx2 would send the string as the file's content, so ``"report.pdf"`` + would upload that text, named ``upload``. + """ + cls = class_of(annotation) + if cls is not None and issubclass(cls, tuple): + return _is_file_tuple(annotation) + return _is_file_content(annotation) + + +def _is_file_content(annotation: Any) -> bool: + """Return whether the type is ``bytes``, a binary file, or ``Any``.""" + if annotation is Any or annotation is NO_VALUE: + return True + cls = class_of(annotation) + return cls is not None and (issubclass(cls, bytes) or _is_binary_file(cls, annotation)) + + +def _is_binary_file(cls: type[Any], annotation: Any) -> bool: + """Return whether the type, whose class is ``cls``, is a file of bytes. + + ``IO[bytes]`` and ``BinaryIO`` are; so are ``io.BytesIO`` and what + ``open(path, "rb")`` returns. ``IO[str]``, ``TextIO`` and a text file + aren't. A bare ``IO`` has no item type, so it counts as ``Any``. + """ + if issubclass(cls, IO): + type_args = get_args(annotation) + return not issubclass(cls, TextIO) and (not type_args or type_args[0] is bytes or type_args[0] is Any) + return issubclass(cls, io.RawIOBase | io.BufferedIOBase) + + +def _is_file_tuple(annotation: Any) -> bool: + """Return whether the type is ``(filename, content[, type[, headers]])``. + + The filename and content type are ``str`` or ``None``; the content is file + content; the headers, the file part's own, a mapping of ``str`` to + ``str``. A bare ``tuple`` has no item types, so it counts as ``Any``. + """ + type_args = get_args(annotation) + if not type_args: + return True + if len(type_args) not in {2, 3, 4} or Ellipsis in type_args: + return False + filename, content, *rest = type_args + content_arms = union_arms(content) + return ( + _is_text_or_none(filename) + and bool(content_arms) + and all(_is_file_content(arm) for arm in content_arms) + and all(_is_text_or_none(item) for item in rest[:1]) + and all(_is_text_mapping(item) for item in rest[1:]) + ) + + +def _is_text_mapping(annotation: Any) -> bool: + """Return whether the type is a mapping of ``str`` to ``str``, or ``Any``. + + A bare ``Mapping`` or ``dict`` has no item types, so it counts as ``Any``. + """ + arms = union_arms(annotation) + for arm in arms: + if arm is Any: + continue + cls = class_of(arm) + if cls is None or not issubclass(cls, Mapping): + return False + if not all(_is_text_or_none(item) for item in get_args(arm)): + return False + return bool(arms) + + +def _is_text_or_none(annotation: Any) -> bool: + """Return whether the type is ``str``, ``None``, both, or ``Any``.""" + return all(arm is Any or (isinstance(arm, type) and issubclass(arm, str)) for arm in union_arms(annotation)) + + +def is_content(annotation: Any) -> bool: + """Return whether a value of this type is a raw body httpx2 can send. + + That's ``str`` (sent as UTF-8), ``bytes``, or an iterable or async + iterable of bytes, which is streamed; or ``Any``. A model, mapping, + ``bytearray`` or ``memoryview`` is iterable too, but not of bytes. + """ + if annotation is Any or annotation is NO_VALUE: + return True + cls = class_of(annotation) + if cls is None: + return False + if issubclass(cls, str | bytes): + return True + if issubclass(cls, BaseModel | Mapping | bytearray | memoryview) or not issubclass(cls, Iterable | AsyncIterable): + return False + # The item type comes first: Iterator[bytes], Generator[bytes, None, None]. + # A bare Iterator has none, so its items count as Any. + type_args = get_args(annotation) + return not type_args or all(arm is Any or arm is bytes for arm in union_arms(type_args[0])) diff --git a/src/clientx/_builder.py b/src/clientx/_builder.py index 0e8e4be..8e60ec7 100644 --- a/src/clientx/_builder.py +++ b/src/clientx/_builder.py @@ -1,158 +1,205 @@ -"""Build one call's request by the endpoint's ``RequestPlan``. +"""Build one call's request from its validated request model and routes. -``Endpoint.request_arguments`` calls ``build_request`` with the plan -``_planner`` made when the class was defined, the call's arguments, and the -names the caller passed. The builder only follows the plan: it never reads -annotations, ``Send`` or the specs, and the only error it raises is -``ArgumentError``, before anything is sent, for a path value that would call a -different path, a value that can't become text or JSON, or a header name or -value that isn't ASCII. +``Endpoint.request_arguments`` validates the call's arguments with the +endpoint's request model, then calls ``build_request`` with the model, the +path and the routes ``_request_routes`` made when the class was defined. The +builder only follows the routes: it never reads annotations or ``Send``, and +the only error it raises is ``ArgumentError``, before anything is sent, for a +path value that would call a different path, a value that can't become text or +JSON, or a header name or value that isn't ASCII. + +Values are the model's, so serializers and the model's conversions apply, and +a model is sent as its annotated type. Each field is dumped on its own, so an +error names its parameter. A value pydantic's ``exclude_if`` leaves out of the +dump isn't sent at all. - Path: each placeholder is filled with percent-encoded text, one segment, or - several for ``{name:path}``. ``.`` and ``..`` are encoded too. A ``None`` or - empty value, or a ``{name:path}`` value with an empty segment, raises. + several for ``{name:path}``. ``.`` and ``..`` are encoded too. An empty + value, or a ``{name:path}`` value with an empty segment, raises. - Text: a value becomes text by one rule, for the path, query, headers and - form: pydantic's JSON form, so an ``Enum`` is its value, a ``datetime`` ISO - 8601 text, a number or ``bool`` JSON text (``true``), and a list or dict - compact JSON text. ``str`` is used only for an object pydantic doesn't know. + form: its JSON form, so an ``Enum`` is its value, a ``datetime`` ISO 8601 + text, a number or ``bool`` JSON text (``true``), and a list or dict compact + JSON text. An object pydantic doesn't know, passed through ``Any``, is its + ``str``. - Query, headers, form: ``None`` is left out, and so is an empty collection - and a ``None`` item in one. Where the plan says ``many``, a collection - repeats the key, decided by the value: a ``str`` is one value. A spread - model or dataclass is dumped with its ``DumpOptions``, then each field is - sent under its planned key; what a spread mapping, or a model with its own - model serializer, dumps is sent under its own keys. A header's name and - value must be ASCII, as httpx2 sends them, or they raise. -- Not passed: a parameter planned ``only_if_passed`` is left out when the - caller didn't pass it, so the server's default applies. -- Files: each file is passed as it is, and a list of them repeats the field. - A ``None`` in the list is left out. A form field planned ``json_part`` is - sent among them, as its own part: its JSON, with ``application/json``. -- JSON fields: each is dumped with its ``DumpOptions``, by alias, into one JSON - object. ``None`` is left out, unless it was passed explicitly and the plan - says ``sends_null``: then it's ``null``. With no fields left, there's no - JSON body. -- Body: ``Body()`` is passed as it is; a lone JSON body is dumped with its - ``DumpOptions``. ``None`` means no body, never ``null``. + and a ``None`` item in one. A list repeats the key, but in a header, which + takes one value. A spread model or dataclass sends each field under its + routed key; what a spread mapping, or a model with its own model serializer, + dumps is sent under its own keys. A key known only at the call that equals + another replaces it. A header's name and value must be ASCII, as httpx2 + sends them. +- Files: each file is passed as it is, read from the model, never dumped; a + list of them repeats the field. A ``None`` in the list is left out. A form + field with ``Send(json_part=True)`` is sent among them, as its own part: its + JSON, with ``application/json``. +- JSON fields: each is dumped by alias into one JSON object. A ``None`` the + caller passed is ``null``; any other ``None`` is left out. With no fields + left, there's no JSON body. +- Body: ``Body()`` is passed as it is, read from the model; the lone JSON body + is dumped by alias. ``None`` means no body, never ``null``. - NaN and infinity: JSON can't hold them, so one in a JSON field, body or part - raises. Values are dumped keeping them, where pydantic would send ``null``. + raises. In text, they're sent as ``NaN`` and ``Infinity``. """ from __future__ import annotations import json -from collections.abc import Collection, Generator, Iterable, Mapping +from collections.abc import Collection, Generator, Mapping, Sequence from contextlib import contextmanager -from typing import Any, cast +from typing import cast from urllib.parse import quote -from pydantic import ConfigDict, TypeAdapter +from pydantic import BaseModel from pydantic_core import PydanticSerializationError, to_jsonable_python -from clientx._planner import DumpOptions, PathPlaceholder, PlannedParameter, RequestPlan, SpreadParameter +from clientx._paths import PathPlaceholder +from clientx._request_routes import FieldRoute from clientx._types import BuildRequestKwargs, HttpxArgument from clientx.exceptions import ArgumentError +# The arguments whose values are sent as text under a key. +_TEXT_ARGUMENTS = frozenset({HttpxArgument.PARAMS, HttpxArgument.HEADERS, HttpxArgument.DATA}) + # --- Entry point -------------------------------------------------------------- def build_request( - plan: RequestPlan, arguments: Mapping[str, object], passed: Collection[str] + path: tuple[str | PathPlaceholder, ...], routes: Sequence[FieldRoute], validated: BaseModel ) -> tuple[str, BuildRequestKwargs]: """Return the URL path and the ``build_request`` arguments for one call. Args: - plan: The endpoint's plan, from ``plan_request``. - arguments: The call's arguments by parameter name, defaults filled in. - passed: The names of the arguments the caller passed, so an explicit - ``None`` can be told from a default one. + path: The endpoint's parsed path template. + routes: Where each of the request model's fields goes. + validated: The request model, validated from the arguments the caller + passed, so its ``model_fields_set`` is what was passed. Raises: ArgumentError: If a path value would change which path is called, a value can't become text or JSON, or a header name or value isn't ASCII. """ - path = _build_path(plan.path, arguments) + in_path = {route.name: _dump_text(validated, route) for route in routes if route.argument is HttpxArgument.URL} + url = _build_path(path, in_path) # Each argument's keyed values: params, headers, data and json. Files are a # list of pairs instead, so one field can repeat. keyed: dict[HttpxArgument, dict[str, object]] = {} files: list[tuple[str, object]] = [] - for item in plan.parameters: - if item.only_if_passed and item.name not in passed: - continue - value = arguments[item.name] - with _converting(item.name): - if isinstance(item, SpreadParameter): - if value is not None: - # A key known only at the call that equals another replaces - # it, as in dict.update; httpx2 sends both header names - # that differ only in case. The planner caught every clash - # it could see. - keyed.setdefault(item.httpx_argument, {}).update(_spread(item, value)) - elif item.httpx_argument is HttpxArgument.FILES or item.json_part: - files.extend(_multipart_entries(item, value)) - elif (sent := _keyed_value(item, value, passed)) is not _LEFT_OUT: - keyed.setdefault(item.httpx_argument, {})[item.key] = sent + request_arguments: dict[str, object] = {} + for route in routes: + if route.argument in _TEXT_ARGUMENTS and not route.send.json_part: + keyed.setdefault(route.argument, {}).update(_text_values(route, _dump_text(validated, route))) + elif route.argument is HttpxArgument.JSON: + _add_json(validated, route, keyed, request_arguments) + elif route.argument is HttpxArgument.DATA: # A form's JSON part. + if (value := _dump_json(validated, route)) is not None and value is not _LEFT_OUT: + files.append((route.key, (None, _encode_json(route, value), "application/json"))) + elif route.argument is HttpxArgument.FILES: + files.extend((route.key, file) for file in _files(getattr(validated, route.name))) + elif route.argument is HttpxArgument.CONTENT and (content := getattr(validated, route.name)) is not None: + request_arguments["content"] = content # Each argument's name is build_request's: "params", "headers", "data"... - request_arguments: dict[str, object] = {argument.value: values for argument, values in keyed.items() if values} + request_arguments.update({argument.value: values for argument, values in keyed.items() if values}) if files: request_arguments["files"] = files - body = plan.body - if body is not None and not (body.only_if_passed and body.name not in passed): - request_arguments.update(_body(body, arguments[body.name])) - return path, cast("BuildRequestKwargs", request_arguments) + return url, cast("BuildRequestKwargs", request_arguments) -# What _keyed_value returns for a value that isn't sent at all. +def _add_json( + validated: BaseModel, + route: FieldRoute, + keyed: dict[HttpxArgument, dict[str, object]], + request_arguments: dict[str, object], +) -> None: + """Add a ``Json()`` route's value: the whole body, or a field of it. + + A ``None`` the caller passed is ``null`` in the JSON object; a default + ``None``, or a whole body of ``None``, sends nothing. It changes ``keyed`` + or ``request_arguments`` in place. + """ + value = _dump_json(validated, route) + if value is _LEFT_OUT or (value is None and (route.whole_body or route.name not in validated.model_fields_set)): + return + if route.whole_body: + request_arguments["json"] = value + else: + keyed.setdefault(HttpxArgument.JSON, {})[route.key] = value + + +# --- Dumping values ----------------------------------------------------------- +def _dump_text(validated: BaseModel, route: FieldRoute) -> object: + """Return a text field's value in JSON form, by attribute name. + + Nested models are dumped by attribute name, which the routes map to keys. + An object pydantic doesn't know is its ``str``: the ``Any`` escape hatch. + + Raises: + ArgumentError: If the value can't become text, such as ``bytes`` that + aren't UTF-8. + """ + with _converting(route.name): + # A value exclude_if leaves out of the dump is None here: left out. + return validated.model_dump(mode="json", include={route.name}, fallback=str).get(route.name) + + +# What _dump_json returns for a value exclude_if leaves out of the dump. _LEFT_OUT = object() -def _keyed_value(item: PlannedParameter, value: object, passed: Collection[str]) -> object: - """Return what's sent under a parameter's key, or ``_LEFT_OUT``. +def _dump_json(validated: BaseModel, route: FieldRoute) -> object: + """Return a JSON field's, body's or part's value as JSON-ready data. + + It's ``_LEFT_OUT`` if ``exclude_if`` leaves it out. Its models are dumped by + alias. httpx2 encodes it when it builds the request; it's encoded once here + first, so a value JSON can't hold raises here, naming the parameter. + There's no ``str`` fallback: JSON has no one text form for an object + pydantic doesn't know. - A JSON field is dumped, or is ``null`` for a ``None`` passed explicitly - where the plan says ``sends_null``. Any other value becomes text. ``None`` - and an empty collection are left out. + Raises: + ArgumentError: If pydantic can't serialize the value, or it holds NaN + or infinity. """ - if item.httpx_argument is HttpxArgument.JSON: - if value is not None: - return _dump_json(item, value) - return None if item.sends_null and item.name in passed else _LEFT_OUT - text = _text_value(value, many=item.many) - if text is None: + try: + dumped = validated.model_dump(mode="json", include={route.name}, by_alias=True) + except PydanticSerializationError as error: + raise ArgumentError( + f"Can't send {route.name!r} as JSON: {error}. Pass a value pydantic can serialize, such as a model, " + "dataclass, dict or list, or convert it at the call. No request was sent.", + parameter=route.name, + ) from error + if not dumped: return _LEFT_OUT - if item.httpx_argument is HttpxArgument.HEADERS: - # Headers take one plain value, never a list. - _check_header(item, item.key, cast("str", text)) - return text + # The one field dumped, under its alias. + value = next(iter(dumped.values())) + _encode_json(route, value) + return value -def _check_header(item: PlannedParameter | SpreadParameter, key: str, text: str) -> None: - """Raise ``ArgumentError`` if a header's name or value isn't ASCII. +def _encode_json(route: FieldRoute, data: object) -> str: + """Return JSON-ready data as JSON text, as httpx2 encodes a JSON body. - httpx2 sends both as ASCII, and would raise ``UnicodeEncodeError`` without - naming the parameter. The planner checked every name it could see; a - spread mapping's keys exist only at the call. + Raises: + ArgumentError: If the data holds NaN or infinity, which JSON can't. """ - if not key.isascii(): - raise ArgumentError( - f"Can't send {item.name!r}: the header name {key!r} isn't ASCII, and header names must be. No request " - "was sent.", - parameter=item.name, - ) - if not text.isascii(): + try: + return _compact_json(data, allow_nan=False) + except ValueError as error: raise ArgumentError( - f"Can't send {item.name!r} as header {key!r}: {text!r} isn't ASCII, and header values must be. Encode " - "it as the API expects, such as with urllib.parse.quote(). No request was sent.", - parameter=item.name, - ) + f"Can't send {route.name!r} as JSON: {error}. No request was sent.", parameter=route.name + ) from error + + +def _compact_json(data: object, *, allow_nan: bool) -> str: + """Return JSON text as httpx2 encodes it: compact, with text as it is.""" + return json.dumps(data, separators=(",", ":"), ensure_ascii=False, allow_nan=allow_nan) @contextmanager def _converting(name: str) -> Generator[None]: """Raise ``ArgumentError`` if a parameter's value can't become text. - Such as ``bytes`` that aren't UTF-8, or an object pydantic can't - serialize, so the error names the parameter, and nothing is sent. + Such as ``bytes`` that aren't UTF-8, so the error names the parameter, and + nothing is sent. """ try: yield @@ -165,19 +212,15 @@ def _converting(name: str) -> Generator[None]: _DOT_SEGMENTS = {".": "%2E", "..": "%2E%2E"} -def _build_path(path: tuple[str | PathPlaceholder, ...], arguments: Mapping[str, object]) -> str: +def _build_path(path: tuple[str | PathPlaceholder, ...], values: Mapping[str, object]) -> str: """Return the path with each placeholder filled with its encoded value. - The planner checked that every placeholder names a parameter, so - ``arguments`` has a value for each. + The rules checked that every placeholder names a parameter, so ``values`` + has one for each. """ parts: list[str] = [] for part in path: - if isinstance(part, str): - parts.append(part) - continue - with _converting(part.name): - parts.append(_encode_path_value(part, arguments[part.name])) + parts.append(part if isinstance(part, str) else _encode_path_value(part, values[part.name])) return "".join(parts) @@ -214,216 +257,104 @@ def _path_value_error(placeholder: PathPlaceholder, value: object, problem: str) ) -# --- Parameters sent under a key ---------------------------------------------- -def _text_value(value: object, *, many: bool) -> str | list[str] | None: - """Return a query, header or form value as text, or ``None`` to omit it. +# --- Parameters sent as text under a key -------------------------------------- +def _text_values(route: FieldRoute, value: object) -> dict[str, str | list[str]]: + """Return a query, header or form route's values as text, by key. - ``None`` is left out, and so is an empty collection: "no values" behaves - like "no value". A ``None`` item in a collection is left out too. Where - ``many`` allows a collection, the value decides: a ``str`` passed for a - ``Sequence[str]`` is one value, not one per character. - """ - if value is None: - return None - if not (many and _is_several(value)): - return _to_text(value) - texts = [_to_text(item) for item in cast("Iterable[object]", value) if item is not None] - return texts or None - - -def _is_several(value: object, *, tuples_too: bool = True) -> bool: - """Return whether the value is a collection of values, rather than one. - - ``str`` and ``bytes`` are collections, but each is one value. A file's - tuple is one file, so files pass ``tuples_too=False``. - """ - if not isinstance(value, Collection) or isinstance(value, str | bytes | bytearray | Mapping): - return False - return tuples_too or not isinstance(value, tuple) - - -def _spread(item: SpreadParameter, value: object) -> dict[str, object]: - """Return a spread parameter's fields as text, by the key each goes under. - - A model or dataclass is dumped with the plan's ``DumpOptions`` first, so a - field ``exclude_unset`` leaves out isn't sent; then each field the plan - lists is sent under its planned key. What a mapping, or a model with its - own model serializer, dumps is sent under its own keys. A field that's - ``None`` or an empty collection is left out. + A plain route sends its value under its key; a spread one, each field of + its dumped value under the key routed for it, or, for a mapping or a model + with its own model serializer, the dumped keys as they are. Raises: ArgumentError: If a model's own serializer dumps it to something other than a mapping, which can't be spread, or a header's name or value isn't ASCII. """ - if item.keys is None: - source = dict(cast("Mapping[object, object]", value)) if isinstance(value, Mapping) else value - dumped = _dump(source, item.dump, by_alias=True) - if not isinstance(dumped, dict): - raise ArgumentError( - f"Can't spread {item.name!r}: it dumps to {type(dumped).__name__}, not a mapping of keys to " - "values. No request was sent.", - parameter=item.name, - ) - pairs = [(str(key), field) for key, field in cast("dict[object, object]", dumped).items()] + if route.spread_keys is None: + pairs = [(route.key, value)] + elif value is None: + pairs = [] + elif not isinstance(value, dict): + raise ArgumentError( + f"Can't spread {route.name!r}: it dumps to {type(value).__name__}, not a mapping of keys to values. " + "No request was sent.", + parameter=route.name, + ) + elif route.spread_keys: + fields = cast("dict[str, object]", value) + pairs = [(key, fields[attribute]) for attribute, key in route.spread_keys if attribute in fields] else: - dumped = cast("dict[str, object]", _dump(value, item.dump, by_alias=False)) - pairs = [(key, dumped[attribute]) for attribute, key in item.keys if attribute in dumped] - fields: dict[str, object] = {} + pairs = [(str(key), field) for key, field in cast("dict[object, object]", value).items()] + is_header = route.argument is HttpxArgument.HEADERS + texts: dict[str, str | list[str]] = {} for key, field in pairs: # Dumped to JSON-ready data, so any collection is a list by now. It - # repeats the key where the argument takes lists; in a header, it's one - # value, JSON text. - text = _text_value(field, many=item.many and isinstance(field, list)) - if text is not None: - fields[key] = text - if item.httpx_argument is HttpxArgument.HEADERS: - for key, text in fields.items(): - _check_header(item, key, cast("str", text)) - return fields - - -def _multipart_entries(item: PlannedParameter, value: object) -> list[tuple[str, object]]: - """Return what a parameter adds to httpx2's ``files=``, as key-value pairs. - - A file parameter's files, or a form field's JSON part: a part with no - filename, holding its JSON, with ``application/json``. - """ - if not item.json_part: - return [(item.key, file) for file in _files(item, value)] - if value is None: - return [] - return [(item.key, (None, _json_text(item, value), "application/json"))] + # repeats the key, but in a header, where it's one value, JSON text. + text = _text_value(field, many=not is_header and isinstance(field, list)) + if text is None: + continue + if is_header: + _check_header(route, key, cast("str", text)) + texts[key] = text + return texts -def _files(item: PlannedParameter, value: object) -> list[object]: - """Return the files to send under the parameter's key, as they are. +def _text_value(value: object, *, many: bool) -> str | list[str] | None: + """Return a query, header or form value as text, or ``None`` to omit it. - One file, or each file of a collection, which repeats the field. ``None``, - an empty collection and a ``None`` in one send none. A tuple is one file, - ``(filename, content...)``, and ``bytes`` are one file's content. + ``None`` is left out, and so is an empty collection: "no values" behaves + like "no value". A ``None`` item in a collection is left out too. """ if value is None: - return [] - several = item.many and _is_several(value, tuples_too=False) - files = list(cast("Iterable[object]", value)) if several else [value] - return [file for file in files if file is not None] + return None + if not many: + return _to_text(value) + texts = [_to_text(item) for item in cast("list[object]", value) if item is not None] + return texts or None -# --- The body ----------------------------------------------------------------- -def _body(body: PlannedParameter, value: object) -> dict[str, object]: - """Return the ``build_request`` argument for the whole body, if any. +def _check_header(route: FieldRoute, key: str, text: str) -> None: + """Raise ``ArgumentError`` if a header's name or value isn't ASCII. - ``Body()`` is passed as it is, as ``content``; a lone JSON body is dumped as - ``json``. ``None`` means no body, never ``null``. + httpx2 sends both as ASCII, and would raise ``UnicodeEncodeError`` without + naming the parameter. The rules checked every name they could see; a + spread mapping's keys exist only at the call. """ - if value is None: - return {} - if body.httpx_argument is HttpxArgument.CONTENT: - return {"content": value} - return {"json": _dump_json(body, value)} + if not key.isascii(): + raise ArgumentError( + f"Can't send {route.name!r}: the header name {key!r} isn't ASCII, and header names must be. No request " + "was sent.", + parameter=route.name, + ) + if not text.isascii(): + raise ArgumentError( + f"Can't send {route.name!r} as header {key!r}: {text!r} isn't ASCII, and header values must be. Encode " + "it as the API expects, such as with urllib.parse.quote(). No request was sent.", + parameter=route.name, + ) -# --- Text --------------------------------------------------------------------- def _to_text(value: object) -> str: - """Return ``value`` as the text that's sent for it. + """Return a JSON-ready value as the text that's sent for it. - It's pydantic's JSON form: an ``Enum`` becomes its value, a ``datetime`` - ISO 8601 text, a ``UUID`` or ``Decimal`` its string, a number or ``bool`` - JSON text (``2``, ``true``), and a list or dict compact JSON text, with - text as it is, as in a JSON body. Only an object pydantic doesn't know uses - ``str``: the ``Any`` escape hatch. + Text is sent as it is; a number or ``bool`` as JSON text (``2``, ``true``), + NaN and infinity as ``NaN`` and ``Infinity``, and a list or dict as compact + JSON text, as in a JSON body. """ jsonable = to_jsonable_python(value, fallback=str) return jsonable if isinstance(jsonable, str) else _compact_json(jsonable, allow_nan=True) -# --- Dumping values ----------------------------------------------------------- -# Dumps a value by its own type, at the call: models nested anywhere in it get -# the dump options too, as in list[User]. NaN and infinity are kept, where -# pydantic would make them None everywhere but in a model's float field, so a -# JSON value holding one raises, and a text value is sent as NaN or Infinity, -# as a float is. -_BY_VALUE = TypeAdapter[Any](Any, config=ConfigDict(ser_json_inf_nan="constants")) - - -def _dump(value: object, dump: DumpOptions, *, by_alias: bool) -> object: - """Return a spread value's fields as JSON-ready data, with dump options. - - A model is dumped by attribute name, which the plan maps to keys; a - mapping, or a model with its own model serializer, by alias. A field - pydantic doesn't know uses ``str``: the ``Any`` escape hatch, as for any - text value. - """ - return _BY_VALUE.dump_python( - value, - mode="json", - by_alias=by_alias, - exclude_unset=dump.exclude_unset, - exclude_none=dump.exclude_none, - exclude_defaults=dump.exclude_defaults, - fallback=str, - ) - - -def _json_text(item: PlannedParameter, value: object) -> str: - """Return a value as JSON text, for a JSON part of a form.""" - return _encode_json(item, _jsonable(item, value)) - - -def _dump_json(item: PlannedParameter, value: object) -> object: - """Return a JSON field's or body's value as JSON-ready data. - - httpx2 encodes it when it builds the request. It's encoded once here first, - so a value JSON can't hold raises here, naming the parameter. - """ - dumped = _jsonable(item, value) - _encode_json(item, dumped) - return dumped +# --- Files -------------------------------------------------------------------- +def _files(value: object) -> list[object]: + """Return the files a ``File()`` value sends, as they are. - -def _jsonable(item: PlannedParameter, value: object) -> object: - """Return a JSON value dumped as JSON-ready data, by alias. - - There's no ``str`` fallback here: JSON has no one text form for an object - pydantic doesn't know. - - Raises: - ArgumentError: If pydantic can't serialize the value, as for a class it - doesn't know passed through ``Any``. No request is sent. - """ - try: - return _BY_VALUE.dump_python( - value, - mode="json", - by_alias=True, - exclude_unset=item.dump.exclude_unset, - exclude_none=item.dump.exclude_none, - exclude_defaults=item.dump.exclude_defaults, - ) - except PydanticSerializationError as error: - raise ArgumentError( - f"Can't send {item.name!r} as JSON: {error}. Pass a value pydantic can serialize, such as a model, " - "dataclass, dict or list, or convert it at the call. No request was sent.", - parameter=item.name, - ) from error - - -def _encode_json(item: PlannedParameter, data: object) -> str: - """Return JSON-ready data as JSON text, as httpx2 encodes a JSON body. - - Raises: - ArgumentError: If the data holds NaN or infinity, which JSON can't. No - request is sent. + One file, or each file of a collection, which repeats the field. ``None``, + an empty collection and a ``None`` in one send none. A tuple is one file, + ``(filename, content...)``, and ``bytes`` are one file's content. """ - try: - return _compact_json(data, allow_nan=False) - except ValueError as error: - raise ArgumentError( - f"Can't send {item.name!r} as JSON: {error}. No request was sent.", parameter=item.name - ) from error - - -def _compact_json(data: object, *, allow_nan: bool) -> str: - """Return JSON text as httpx2 encodes it: compact, with text as it is.""" - return json.dumps(data, separators=(",", ":"), ensure_ascii=False, allow_nan=allow_nan) + if value is None: + return [] + several = isinstance(value, Collection) and not isinstance(value, str | bytes | bytearray | Mapping | tuple) + files: list[object] = list(cast("Collection[object]", value)) if several else [value] + return [file for file in files if file is not None] diff --git a/src/clientx/_client.py b/src/clientx/_client.py index e670f37..9521c1c 100644 --- a/src/clientx/_client.py +++ b/src/clientx/_client.py @@ -20,7 +20,6 @@ class _BaseClientX: __clientx_base_url__: ClassVar[URL | None] = None __clientx_user_agent__: ClassVar[str | None] = None __clientx_raise_for_status__: bool = True - __clientx_validate_arguments__: bool = False def __repr__(self) -> str: client = cast("ClientX | AsyncClientX", self) @@ -66,7 +65,6 @@ def __init__( *, user_agent: str | None = None, raise_for_status: bool | None = None, - validate_arguments: bool = False, **kwargs: Unpack[HttpxClientOptions], ) -> None: """Initialize with a base URL and ``httpx2.Client`` options. @@ -83,10 +81,6 @@ class argument and ``ClientX/``. When ``None``, a raise_for_status: Raise ``httpx2.HTTPStatusError`` when an endpoint gets a 4xx or 5xx response, before any decoder runs. On when ``None``. An endpoint's own ``raise_for_status=`` overrides it. - validate_arguments: Check the arguments of each call against their - annotations, strictly, before anything is sent, and raise - ``ArgumentError`` if one doesn't fit. A helper's constraints, - such as ``Query(ge=1)``, are checked too. **kwargs: Additional keyword arguments passed directly to ``httpx2.Client``. @@ -101,7 +95,6 @@ class argument and ``ClientX/``. When ``None``, a user_agent=user_agent, headers=kwargs.get("headers"), raise_for_status=raise_for_status, - validate_arguments=validate_arguments, ) def __init_subclass__( @@ -144,7 +137,6 @@ def __init__( *, user_agent: str | None = None, raise_for_status: bool | None = None, - validate_arguments: bool = False, **kwargs: Unpack[AsyncHttpxClientOptions], ) -> None: """Initialize with a base URL and ``httpx2.AsyncClient`` options. @@ -159,7 +151,6 @@ def __init__( user_agent=user_agent, headers=kwargs.get("headers"), raise_for_status=raise_for_status, - validate_arguments=validate_arguments, ) def __init_subclass__( @@ -194,7 +185,6 @@ def _configure( user_agent: str | None, headers: HeaderTypes | None, raise_for_status: bool | None, - validate_arguments: bool, ) -> None: # Products go most significant first (RFC 9110, section 10.1.5): the # caller's, the class's, then ClientX's. httpx2 always sets its own @@ -207,7 +197,6 @@ def _configure( client.headers["User-Agent"] = " ".join(product for product in products if product) if raise_for_status is not None: client.__clientx_raise_for_status__ = raise_for_status - client.__clientx_validate_arguments__ = validate_arguments # --- Resources ---------------------------------------------------------------- diff --git a/src/clientx/_endpoint.py b/src/clientx/_endpoint.py index 4993c90..c436369 100644 --- a/src/clientx/_endpoint.py +++ b/src/clientx/_endpoint.py @@ -17,15 +17,18 @@ from typing import Any, get_origin from httpx2 import USE_CLIENT_DEFAULT, Response, Timeout -from pydantic import TypeAdapter +from pydantic import BaseModel from clientx._builder import build_request from clientx._decoding import default_decoder, is_stream -from clientx._planner import RequestPlan, plan_request +from clientx._paths import PathPlaceholder, parse_path from clientx._registry import tool_method_for +from clientx._request_model import build_request_model, validate_call +from clientx._request_routes import FieldRoute, plan_routes +from clientx._request_rules import check_request_model +from clientx._request_schema import request_schema from clientx._signature import NO_VALUE, BoundCall, ParameterInfo, ParameterKind, SignatureInfo from clientx._types import BuildRequestKwargs, Decoder, MethodType, ToolOptions, UseClientDefault -from clientx._validation import build_arguments_validator, check_arguments from clientx.exceptions import DefinitionError # What each HTTP method implies for the tool hints ``tool_options=`` leaves out. @@ -79,15 +82,17 @@ class Endpoint: owner: The client or resource class whose body declares the endpoint, or ``None`` until that class is defined. An endpoint has one owner, so a resource joins its prefix once. - request_plan: How a call's arguments become the request, or ``None`` - until the owner class is defined and calls ``set_up_request_plan``. + request_model: The pydantic model of the parameters, which validates a + call's arguments, or ``None`` until ``set_up_request_plan`` builds + it. + request_routes: Where each of the request model's fields goes, or + ``None`` until ``set_up_request_plan`` works it out. + request_path: ``raw_path`` parsed into text and placeholders, set by + ``set_up_request_plan``. stream: Whether requests are sent in streaming mode: with ``stream_response``, or because the return annotation is an ``Iterator`` (``AsyncIterator`` for ``async def``). ``__post_init__`` sets it. - arguments_validator: Validates a call's arguments for a client - created with ``validate_arguments=True``; ``None`` until the first - checked call builds it. """ method: MethodType @@ -105,9 +110,10 @@ class Endpoint: read_only: bool = field(init=False) destructive: bool = field(init=False) idempotent: bool = field(init=False) - request_plan: RequestPlan | None = field(default=None, init=False) + request_model: type[BaseModel] | None = field(default=None, init=False, repr=False) + request_routes: tuple[FieldRoute, ...] | None = field(default=None, init=False, repr=False) + request_path: tuple[str | PathPlaceholder, ...] = field(default=(), init=False, repr=False) stream: bool = field(init=False) - arguments_validator: TypeAdapter[dict[str, Any]] | None = field(default=None, init=False, repr=False) def __post_init__(self, tool_options: ToolOptions | None) -> None: """Check the signature and work out how to decode the response, once. @@ -300,34 +306,30 @@ def parameters(self) -> tuple[ParameterInfo, ...]: def set_up_request_plan(self) -> None: """Work out how a call's arguments become the request, once. - It also checks the path against the parameters. ``_class_setup`` calls - it when the owner class is defined, after joining a resource's prefix - onto ``raw_path``: the prefix can add placeholders. + It builds the endpoint's request model, checks it against the path, + then works out each argument's route. ``_class_setup`` calls it when + the owner class is defined, after joining a resource's prefix onto + ``raw_path``: the prefix can add placeholders. Raises: - DefinitionError: If the path template and the parameters don't fit - together; see ``plan_request``. + DefinitionError: If a parameter can't go in the request model, see + ``build_request_model``, or the model and the path don't fit + together, see ``check_request_model``. """ try: - self.request_plan = plan_request(self.raw_path, self.parameters(), is_async=self.signature.is_async) + self.request_model = build_request_model(self.signature.qualname, self.parameters()) + schema = request_schema(self.request_model) + check_request_model(self.raw_path, self.request_model, schema, is_async=self.signature.is_async) + self.request_routes = plan_routes(self.request_model, self.raw_path, schema) + self.request_path = parse_path(self.raw_path) except DefinitionError as error: raise DefinitionError(f"Endpoint '{self.signature.qualname}': {error}") from error - def check_arguments(self, bound: BoundCall) -> None: - """Raise ``ArgumentError`` if an argument the caller passed doesn't fit. - - Only for a client created with ``validate_arguments=True``; the rules - are in ``_validation.py``. - """ - if self.arguments_validator is None: - self.arguments_validator = build_arguments_validator(self.parameters()) - passed = {name: value for name, value in bound.arguments.items() if name in bound.passed} - check_arguments(self.arguments_validator, passed, self.signature.qualname) - def request_arguments(self, bound: BoundCall) -> tuple[str, BuildRequestKwargs]: """Return a call's URL path and its other ``build_request`` arguments. - The plan supplies the parts that carry the call's arguments; the + The arguments the caller passed are validated with the request model, + and the request is built from the validated model by the routes; the endpoint adds its ``timeout``. Args: @@ -335,15 +337,18 @@ def request_arguments(self, bound: BoundCall) -> tuple[str, BuildRequestKwargs]: Raises: DefinitionError: If the endpoint isn't declared in the body of a - client or resource class, so it has no ``request_plan``. - ArgumentError: If an argument's value can't be sent. + client or resource class, so it has no request model. + ArgumentError: If an argument doesn't fit its annotation, or its + value can't be sent. """ - if self.request_plan is None: + if self.request_model is None or self.request_routes is None: raise DefinitionError( f"Endpoint '{self.signature.qualname}' can't be called: it isn't declared in the body of a " "ClientX, AsyncClientX, Resource or AsyncResource subclass." ) - url, request_arguments = build_request(self.request_plan, bound.arguments, bound.passed) + passed = {name: value for name, value in bound.arguments.items() if name in bound.passed} + validated = validate_call(self.request_model, passed, self.signature.qualname) + url, request_arguments = build_request(self.request_path, self.request_routes, validated) request_arguments["timeout"] = self.timeout return url, request_arguments diff --git a/src/clientx/_method.py b/src/clientx/_method.py index b6fd52c..f9ca0f8 100644 --- a/src/clientx/_method.py +++ b/src/clientx/_method.py @@ -10,7 +10,7 @@ from clientx._decoding import adecode, araise_status_error, decode, raise_status_error from clientx._endpoint import Endpoint from clientx._registry import register_endpoint_function -from clientx._signature import BoundCall, inspect_definition +from clientx._signature import inspect_definition from clientx._types import Decoder, MethodType, ToolOptions, UseClientDefault from clientx.exceptions import DefinitionError @@ -173,7 +173,6 @@ def wrapper(_self: T, /, *args: P.args, **kwargs: P.kwargs) -> R: warnings.warn(endpoint.deprecated, DeprecationWarning, stacklevel=2) client = client_of(_self, ClientX) bound = endpoint.bind(_self, *args, **kwargs) - _check_arguments(endpoint, client, bound) url, request_arguments = endpoint.request_arguments(bound) request = client.build_request(endpoint.method, url, **request_arguments) response = client.send(request, stream=endpoint.stream) @@ -189,7 +188,6 @@ async def async_wrapper(_self: T, /, *args: P.args, **kwargs: P.kwargs) -> objec warnings.warn(endpoint.deprecated, DeprecationWarning, stacklevel=2) client = client_of(_self, AsyncClientX) bound = endpoint.bind(_self, *args, **kwargs) - _check_arguments(endpoint, client, bound) url, request_arguments = endpoint.request_arguments(bound) request = client.build_request(endpoint.method, url, **request_arguments) response = await client.send(request, stream=endpoint.stream) @@ -221,16 +219,6 @@ def _checked_path(method: MethodType, path: str | Callable[..., object]) -> str: return path -def _check_arguments(endpoint: Endpoint, client: ClientX | AsyncClientX, bound: BoundCall) -> None: - """Check a call's arguments if the client has ``validate_arguments=True``. - - Raises: - ArgumentError: If an argument the caller passed doesn't fit. - """ - if client.__clientx_validate_arguments__: - endpoint.check_arguments(bound) - - def _raises_for_status(endpoint: Endpoint, client: ClientX | AsyncClientX) -> bool: """Return whether ``endpoint`` raises for a 4xx or 5xx response. diff --git a/src/clientx/_paths.py b/src/clientx/_paths.py new file mode 100644 index 0000000..ce26810 --- /dev/null +++ b/src/clientx/_paths.py @@ -0,0 +1,79 @@ +"""Parse an endpoint's path template into text and placeholders. + +The template has ``{name}``, filled with one segment, and ``{name:path}``, +whose value keeps its slashes. There are no literal braces: any brace that +isn't part of a placeholder raises ``DefinitionError``, as does a placeholder +written any other way, such as ``{user-id}`` or ``{page:int}``. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from string import Formatter + +from clientx.exceptions import DefinitionError + + +@dataclass(frozen=True) +class PathPlaceholder: + """A ``{name}`` slot in the path template. + + Attributes: + keep_slashes: ``{name:path}`` was written, so the builder sends any + ``/`` in the value as it is, rather than encoding it as ``%2F``. + """ + + name: str + keep_slashes: bool = False + + def __str__(self) -> str: + return f"{{{self.name}:path}}" if self.keep_slashes else f"{{{self.name}}}" + + +_PATH_SYNTAX = ( + "A placeholder is {name}, for one path segment, or {name:path}, for a value that keeps its " + "slashes, where name is a parameter's name." +) + + +def _check_placeholder(path_template: str, name: str, spec: str | None, conversion: str | None) -> None: + """Raise ``DefinitionError`` unless it's ``{name}`` or ``{name:path}``. + + ``Formatter`` only checks the braces, so ``{user-id}``, ``{a.b}``, + ``{c[0]}``, ``{}``, ``{d!r}`` and ``{e:int}`` all reach here. + """ + if name.isidentifier() and conversion is None and spec in {"", "path"}: + return + # Rebuild the placeholder as it was written, for the message. + written = "{" + name + (f"!{conversion}" if conversion else "") + (f":{spec}" if spec else "") + "}" + raise DefinitionError(f"Path {path_template!r}: ClientX can't fill the placeholder {written}. {_PATH_SYNTAX}") + + +def parse_path(path_template: str) -> tuple[str | PathPlaceholder, ...]: + """Split a path template into text and placeholders, in order.""" + # Formatter().parse splits "/user/{user_id}" into (text, name, spec, + # conversion) chunks: ("/user/", "user_id", "", None). + # parse() is lazy, so list() makes it raise here, inside the try, rather + # than partway through the loop. + try: + chunks = list(Formatter().parse(path_template)) + except ValueError as error: + raise DefinitionError( + f"Path {path_template!r} has a brace that isn't part of a placeholder. {_PATH_SYNTAX}" + ) from error + + parts: list[str | PathPlaceholder] = [] + for text, name, spec, conversion in chunks: + # Formatter turns {{ and }} into a brace in the text. ClientX has no + # literal braces, so any brace there is a mistake. + if "{" in text or "}" in text: + raise DefinitionError( + f"Path {path_template!r} has a brace that isn't part of a placeholder. {_PATH_SYNTAX}" + ) + if text: + parts.append(text) + if name is None: + continue + _check_placeholder(path_template, name, spec, conversion) + parts.append(PathPlaceholder(name, keep_slashes=spec == "path")) + return tuple(parts) diff --git a/src/clientx/_planner.py b/src/clientx/_planner.py deleted file mode 100644 index 345396e..0000000 --- a/src/clientx/_planner.py +++ /dev/null @@ -1,1274 +0,0 @@ -"""Plan how an endpoint's calls become requests, when its class is defined. - -``Endpoint.set_up_request_plan`` calls ``plan_request`` with the endpoint's -final path template (any resource prefix joined on), its parameters, and -whether it's ``async def``. It checks that they fit together, raising -``DefinitionError`` if they don't, and returns the ``RequestPlan`` that -``_builder.build_request`` follows on each call. The planner decides -everything, ``Send`` options included, and bakes it into the plan, so the -builder never reads annotations, ``Send`` or the specs. - -Where each parameter goes is decided once, and never guessed: - -1. A parameter that a path placeholder names fills it. It must be a plain value - that can't be ``None``, with no helper but ``Url()``, no alias, and no - ``Send``. -2. Every other parameter has a ``clientx.arguments`` helper in its outermost - ``Annotated``, and goes to that helper's ``build_request`` argument. A - parameter without one is an error, and so is a helper or ``Send`` anywhere - else in its type, a default inside a helper, or a helper or ``Send`` on a - model's field. - -A pydantic serializer in a parameter's type is an error too: the builder sends -a value by its own type, so it wouldn't run. - -What each argument takes is an ``HttpxArgumentSpec`` subclass, one per -argument, so a rule that differs by argument lives in that argument's class: - -- A plain value is on an allow-list: ``str``, ``int``, ``float``, ``bool``, - ``Enum``, ``date``, ``datetime``, ``time``, ``UUID``, ``Decimal``, ``bytes``, - a ``Literal`` of those, or a ``NewType`` of one. ``Any``, or no annotation, - is the escape hatch. -- The query string and the form take a plain value, or a collection of them, - which repeats the key, or either, as ``str | list[str]`` does; headers take - a plain value. A model, dataclass or mapping marked ``Query()``, - ``Header()`` or ``Form()`` is spread into it, one value per field, computed - fields included, and each field follows the same rule. A model with its own - model serializer is spread by what it dumps, like a mapping. -- A file is ``bytes``, a binary file, or a ``(filename, content[, - content_type[, headers]])`` tuple, never ``str``. A list of files repeats the - field, and so can several ``File()`` parameters. -- The raw body, one ``Body()`` parameter, is ``str``, ``bytes``, or a stream of - bytes that matches the client, sync or async. -- A JSON field takes any value. A lone ``Json()`` parameter that isn't a plain - value, ``Any`` included, is the whole body, unless it has - ``Send(embed=True)``. -- A request has one kind of body: JSON, raw content, or a form of ``Form()`` - and ``File()`` parameters. A ``Form()`` parameter with - ``Send(json_part=True)`` takes any value, sent as a JSON part of the form. -- Two values sent to one argument under one key raise, except files; header - keys compare case-insensitively. A header name must be ASCII. A spread - mapping's keys exist only at the call, and so do those of a model with its - own model serializer, so the builder checks those, and a clash with one is - the caller's to avoid. -- ``Send(exclude_unset=True)`` leaves out a parameter the caller didn't pass, - as well as a model's unset fields. The dump options must fit the type, since - pydantic ignores them silently otherwise: ``exclude_none`` and - ``exclude_defaults`` need a model or pydantic dataclass, and - ``exclude_unset`` a default other than ``None``, or a pydantic model, to act - on. A ``Form()`` takes ``exclude_none`` only on a JSON part. - -The path template has ``{name}``, filled with one segment, and ``{name:path}``, -whose value keeps its slashes. There are no literal braces: any brace that -isn't part of a placeholder raises. -""" - -from __future__ import annotations - -import io -from collections.abc import AsyncIterable, Callable, Collection, Iterable, Iterator, Mapping, Sequence -from dataclasses import dataclass, fields, is_dataclass -from datetime import date, datetime, time -from decimal import Decimal -from enum import Enum -from string import Formatter -from types import NoneType, UnionType -from typing import ( - IO, - Any, - ClassVar, - Literal, - TextIO, - TypeAliasType, - Union, - cast, - get_args, - get_origin, - get_type_hints, -) -from uuid import UUID - -from pydantic import BaseModel, PlainSerializer, WrapSerializer -from pydantic.dataclasses import is_pydantic_dataclass -from pydantic_core import PydanticUndefined - -from clientx._arguments import get_httpx_argument -from clientx._signature import NO_VALUE, ParameterInfo, unwrap_annotated -from clientx._types import HttpxArgument, Send -from clientx.exceptions import DefinitionError - - -# --- The plan ----------------------------------------------------------------- -@dataclass(frozen=True, slots=True) -class RequestPlan: - """How a call's arguments become the request, worked out once per endpoint. - - The planner makes it when the class is defined; the builder follows it on - each call. - - Attributes: - path: The path template, split into text and placeholders, for the - builder to fill in. - parameters: The parameters sent under a key, and the ones spread - into an argument, in signature order. - body: The parameter that's the whole body, or ``None``: one - ``Body()`` parameter, or a lone ``Json()`` one. Its ``key`` isn't - used, and a ``None`` value means no body. - """ - - path: tuple[str | PathPlaceholder, ...] - parameters: tuple[PlannedParameter | SpreadParameter, ...] = () - body: PlannedParameter | None = None - - -@dataclass(frozen=True, slots=True) -class DumpOptions: - """Pydantic's dump options for a parameter's value, from its ``Send``. - - The planner sets them; the builder passes them to pydantic as they are, - without reading ``Send``. - """ - - exclude_unset: bool = False - exclude_none: bool = False - exclude_defaults: bool = False - - -@dataclass(frozen=True, slots=True) -class PlannedParameter: - """Where a parameter's value goes, and the key it's sent under. - - Attributes: - name: The parameter's name, and its key in the call's arguments. - httpx_argument: The ``build_request`` argument it goes to. - key: The name it's sent under, such as the query parameter's. - many: The value can be a collection, which repeats the key. Whether - it is one is decided at the call, so ``str | list[str]`` takes - either, and a ``str`` is always one value, not one per character. - sends_null: A ``None`` passed explicitly is sent as ``null``. The - planner sets it from the spec, so the builder needn't read one. - only_if_passed: Left out when the caller didn't pass it, from - ``Send(exclude_unset=True)``, so the server's default applies. - json_part: A form field sent as its own part of a multipart form, as - JSON, from ``Send(json_part=True)``. - dump: How pydantic dumps the value, for a model inside it. - """ - - name: str - httpx_argument: HttpxArgument - key: str - many: bool = False - sends_null: bool = False - only_if_passed: bool = False - json_part: bool = False - dump: DumpOptions = DumpOptions() - - -@dataclass(frozen=True, slots=True) -class SpreadParameter: - """A model, dataclass or mapping parameter spread into a text argument. - - Attributes: - name: The parameter's name, and its key in the call's arguments. - httpx_argument: The ``build_request`` argument its fields go to. - keys: Each field's attribute name, and the key it's sent under. - ``None`` for a mapping, or a model with its own model serializer: - what it dumps is sent, each key as it is, known only at the call. - many: A list in a field repeats the key, since the argument takes - lists. Without it, a list is sent as one text value. - only_if_passed: Left out when the caller didn't pass it, from - ``Send(exclude_unset=True)``. - dump: How pydantic dumps the value before its fields are sent. - """ - - name: str - httpx_argument: HttpxArgument - keys: tuple[tuple[str, str], ...] | None = None - many: bool = False - only_if_passed: bool = False - dump: DumpOptions = DumpOptions() - - -# --- Entry point -------------------------------------------------------------- -def plan_request(path_template: str, parameters: Sequence[ParameterInfo], *, is_async: bool) -> RequestPlan: - """Work out an endpoint's ``RequestPlan`` from its path and parameters. - - ``is_async`` says whether the endpoint is ``async def``, which is also - whether its client is async, since each kind of endpoint goes on its own - kind of client. A streamed body must match it. - """ - path = _parse_path(path_template) - path_placeholders = {part.name: part for part in path if isinstance(part, PathPlaceholder)} - - parameter_names = {parameter.name for parameter in parameters} - for placeholder in path_placeholders.values(): - if placeholder.name not in parameter_names: - raise DefinitionError( - f"Path {path_template!r} has the placeholder {placeholder}, " - f"but no parameter is named {placeholder.name!r}. " - "Add the parameter, or remove the placeholder." - ) - - lone_body = _find_lone_body(parameters) - body: PlannedParameter | None = None - planned: list[PlannedParameter | SpreadParameter] = [] - for parameter in parameters: - # First, so a nested helper gets its own message rather than "needs a - # helper": ParameterInfo only reads the outermost Annotated. - _check_nested(parameter) - _check_helper_default(parameter) - _check_model_fields(parameter) - _check_serializers(parameter) - placeholder = path_placeholders.get(parameter.name) - if placeholder is not None: - _check_path_parameter(parameter, placeholder, path_template) - continue - argument = _helper_argument(parameter, path_template) - if parameter is lone_body or _SPECS[argument].whole_body: - body = _plan_body(parameter, argument, is_async=is_async) - else: - planned.append(_plan_keyed(parameter, argument)) - - # Then the parameters together. - _check_one_body(parameters) - _check_one_whole_body(parameters) - _check_keys(planned) - return RequestPlan(path=path, parameters=tuple(planned), body=body) - - -# --- Specs: what each build_request argument takes ---------------------------- -class HttpxArgumentSpec: - """What one ``build_request`` argument takes. Subclass it per argument. - - The planner asks the spec rather than testing for particular arguments, so - a rule that differs by argument is changed in that argument's class. Each - subclass lists only what differs from the defaults here. The classes are - used as they are, never instantiated. - - Attributes: - argument: The argument the subclass describes. - helper: The helper that sends a parameter there, as written, for - messages: ``"Query()"``. - accepts: Where it goes and what it takes, for messages: ``"the - headers, which take a plain value"``. - body_kind: The kind of body it makes, for the one-body check, or - ``None`` if it isn't a body. - send_options: The ``Send`` options it supports, by field name. Any - other option set on its parameter raises. - whole_body: A parameter going there is the whole of it, so there's - at most one, and it isn't sent under a key. - takes_text: Each value is sent as text under a key, and a model, - dataclass or mapping is spread into it, one value per field. - takes_lists: A collection of values repeats the key, as in - ``?tag=a&tag=b``, or several files under one field. - lone_is_body: The only parameter going to it is the whole body, if - it isn't a plain value and doesn't have ``Send(embed=True)``. - sends_null: A parameter passed explicitly as ``None`` is sent as - ``null``; one that isn't passed is left out. Without it, ``None`` - is always left out. - streams: An iterable value is streamed, so it must match the client: - sync for a sync client, async for an async one. - keys_can_repeat: Two values under one key are both sent, so keys - can't clash. - tuples_are_values: A tuple is one value, not a collection of them. - """ - - argument: ClassVar[HttpxArgument] - helper: ClassVar[str] - accepts: ClassVar[str] - body_kind: ClassVar[str | None] = None - send_options: ClassVar[frozenset[str]] = frozenset() - whole_body: ClassVar[bool] = False - takes_text: ClassVar[bool] = False - takes_lists: ClassVar[bool] = False - lone_is_body: ClassVar[bool] = False - sends_null: ClassVar[bool] = False - streams: ClassVar[bool] = False - keys_can_repeat: ClassVar[bool] = False - tuples_are_values: ClassVar[bool] = False - - @classmethod - def key(cls, name: str, alias: str | None) -> str: - """Return the key a value is sent under: the alias, or else the name.""" - return alias or name - - @classmethod - def clash_key(cls, key: str) -> str: - """Return the form of a key that's compared to find clashes: as is.""" - return key - - @classmethod - def check_key(cls, key: str, source: str) -> None: - """Raise ``DefinitionError`` if the argument can't send under ``key``. - - ``source`` says where the key comes from, for messages, such as - ``"parameter 'note'"``. Any key can be sent, by default. - """ - - @classmethod - def takes_value(cls, annotation: Any) -> bool: - """Return whether one value of this type can go there: a plain value. - - It takes one type, not a union: the planner splits one first. - """ - return _is_plain(annotation) - - @classmethod - def check_send(cls, send: Send, name: str) -> None: - """Raise ``DefinitionError`` if ``Send`` options don't go together here. - - ``send_options`` says which options the argument takes; this checks how - they combine. Nothing to check, by default. - """ - - @classmethod - def what_fits(cls) -> str: - """Return what a value can be, for messages: a plain value.""" - plain_names = ", ".join(plain_type.__name__ for plain_type in _PLAIN_TYPES) - return ( - f"A plain value is one of {plain_names}, or Any. For another type, annotate the parameter as str " - "and convert the value at the call." - ) - - -class UrlSpec(HttpxArgumentSpec): - argument = HttpxArgument.URL - helper = "Url()" - accepts = "the path, which takes a plain value" - - -class ParamsSpec(HttpxArgumentSpec): - argument = HttpxArgument.PARAMS - helper = "Query()" - accepts = "the query string, which takes a plain value or a collection of them" - takes_text = True - takes_lists = True - # exclude_unset for a parameter with a default, or a model; exclude_defaults - # for a spread model. Not exclude_none: a query string leaves out None. - send_options = frozenset({"exclude_unset", "exclude_defaults"}) - - -class HeadersSpec(HttpxArgumentSpec): - argument = HttpxArgument.HEADERS - helper = "Header()" - accepts = "the headers, which take a plain value" - takes_text = True - # exclude_unset for a parameter with a default, or a model; exclude_defaults - # for a spread model. Not exclude_none: headers leave out None. - send_options = frozenset({"exclude_unset", "exclude_defaults"}) - - @classmethod - def key(cls, name: str, alias: str | None) -> str: - # Python names can't have "-", so request_id is sent as request-id, as - # FastAPI's Header() does. An alias is sent as written. - return alias or name.replace("_", "-") - - @classmethod - def clash_key(cls, key: str) -> str: - # Header names are case-insensitive in HTTP: X-Trace is x-trace. - return key.lower() - - @classmethod - def check_key(cls, key: str, source: str) -> None: - # httpx2 sends header names as ASCII, and would raise UnicodeEncodeError - # at the call. A Python name can be any letter, so check them all. - if not key.isascii(): - raise DefinitionError( - f"{source.capitalize()} is sent by Header() as {key!r}, which isn't ASCII, and header names must be. " - "Give it an ASCII alias." - ) - - -class DataSpec(HttpxArgumentSpec): - argument = HttpxArgument.DATA - helper = "Form()" - accepts = "the form, which takes a plain value or a collection of them" - takes_text = True - takes_lists = True - body_kind = "a form" - # json_part sends a value as a JSON part of a multipart form, as some APIs - # take next to files. The dump options act on a spread model or a JSON - # part; exclude_none on a JSON part only, since a form leaves out None. - send_options = frozenset({"exclude_unset", "exclude_none", "exclude_defaults", "json_part"}) - - @classmethod - def check_send(cls, send: Send, name: str) -> None: - if send.exclude_none is not None and not send.json_part: - raise DefinitionError( - f"Parameter {name!r} has Send(exclude_none=...), but a Form() field leaves out None already. It " - "applies only to a JSON part, with Send(json_part=True). Remove it." - ) - - -class FilesSpec(HttpxArgumentSpec): - argument = HttpxArgument.FILES - helper = "File()" - accepts = "the form's files, which take a file or a collection of them" - body_kind = "a form" - # Several files under one field, as from . They - # go to httpx2 as a list of pairs, so two File() parameters can share a - # field too. - takes_lists = True - keys_can_repeat = True - # A tuple is one file, (filename, content...), so a list of files is a - # list, not a tuple. - tuples_are_values = True - - @classmethod - def takes_value(cls, annotation: Any) -> bool: - return _is_file(annotation) - - @classmethod - def what_fits(cls) -> str: - return ( - 'A file is bytes, a binary file such as open(path, "rb"), or a (filename, content[, content_type[, ' - "headers]]) tuple, or Any. Pass text as bytes, with text.encode(), and open a path yourself." - ) - - -class ContentSpec(HttpxArgumentSpec): - argument = HttpxArgument.CONTENT - helper = "Body()" - accepts = "the raw body" - body_kind = "raw content" - # A Body() parameter is the whole raw body, so there's one. - whole_body = True - # httpx2 streams an iterable body: a sync Client takes only a sync one, and - # an AsyncClient only an async one. - streams = True - - @classmethod - def takes_value(cls, annotation: Any) -> bool: - return _is_content(annotation) - - @classmethod - def what_fits(cls) -> str: - return "The raw body is str, bytes, or an iterable or async iterable of bytes, or Any." - - -class JsonSpec(HttpxArgumentSpec): - argument = HttpxArgument.JSON - helper = "Json()" - accepts = "the JSON body" - body_kind = "JSON" - # A lone model is the body, {"name": ...}, as in FastAPI; Send(embed=True) - # sends it under its name instead, {"user": {"name": ...}}. - lone_is_body = True - send_options = frozenset({"embed", "exclude_unset", "exclude_none", "exclude_defaults"}) - # JSON has null: update(nickname=None) sends {"nickname": null}, to clear - # it. Query strings, headers and forms have no null. - sends_null = True - - @classmethod - def takes_value(cls, annotation: Any) -> bool: - # Pydantic serializes any value, so a JSON field takes anything, and - # what_fits is never asked for. - return True - - -# Each argument a helper can mark, to its spec. COOKIES has no helper. -_SPECS: dict[HttpxArgument, type[HttpxArgumentSpec]] = { - spec.argument: spec for spec in (UrlSpec, ParamsSpec, HeadersSpec, DataSpec, FilesSpec, ContentSpec, JsonSpec) -} - - -# --- The path ----------------------------------------------------------------- -_PATH_SYNTAX = ( - "A placeholder is {name}, for one path segment, or {name:path}, for a value that keeps its " - "slashes, where name is a parameter's name." -) - - -def _check_path_parameter(parameter: ParameterInfo, placeholder: PathPlaceholder, path_template: str) -> None: - """Raise ``DefinitionError`` if a parameter can't fill its placeholder. - - It must be a plain value that can't be ``None``, with no helper but - ``Url()``, no alias, and no ``Send``. - """ - fills = f"Parameter {parameter.name!r} fills {placeholder} in the path {path_template!r}" - argument = parameter.httpx_argument - if argument is not None and argument is not HttpxArgument.URL: - raise DefinitionError( - f"{fills}, so it can't also be marked {_SPECS[argument].helper}. " - "Remove its helper, or rename the parameter or the placeholder." - ) - field_info = parameter.clientx_field_info - if field_info is not None and field_info.serialization_alias not in {None, parameter.name}: - raise DefinitionError( - f"{fills}, so its Url(alias=...) has no effect: a path parameter is matched to its placeholder by " - "name. Remove the alias, or rename the parameter." - ) - if _allows_none(parameter.annotation): - raise DefinitionError( - f"{fills}, so it can't be None: a None value would always fail at the call. Remove None from its type." - ) - if not all(UrlSpec.takes_value(arm) for arm in _arms(parameter.annotation)): - raise DefinitionError(f"{fills}, so it must be a plain value. {UrlSpec.what_fits()}") - if parameter.send != Send(): - raise DefinitionError(f"{fills}, so Send doesn't apply to it. Remove it.") - - -@dataclass(frozen=True) -class PathPlaceholder: - """A ``{name}`` slot in the path template. - - Attributes: - keep_slashes: ``{name:path}`` was written, so the builder sends any - ``/`` in the value as it is, rather than encoding it as ``%2F``. - """ - - name: str - keep_slashes: bool = False - - def __str__(self) -> str: - return f"{{{self.name}:path}}" if self.keep_slashes else f"{{{self.name}}}" - - -def _parse_path(path_template: str) -> tuple[str | PathPlaceholder, ...]: - """Split a path template into text and placeholders, in order.""" - # Formatter().parse splits "/user/{user_id}" into (text, name, spec, - # conversion) chunks: ("/user/", "user_id", "", None). - # parse() is lazy, so list() makes it raise here, inside the try, rather - # than partway through the loop. - try: - chunks = list(Formatter().parse(path_template)) - except ValueError as error: - raise DefinitionError( - f"Path {path_template!r} has a brace that isn't part of a placeholder. {_PATH_SYNTAX}" - ) from error - - parts: list[str | PathPlaceholder] = [] - for text, name, spec, conversion in chunks: - # Formatter turns {{ and }} into a brace in the text. ClientX has no - # literal braces, so any brace there is a mistake. - if "{" in text or "}" in text: - raise DefinitionError( - f"Path {path_template!r} has a brace that isn't part of a placeholder. {_PATH_SYNTAX}" - ) - if text: - parts.append(text) - if name is None: - continue - _check_placeholder(path_template, name, spec, conversion) - parts.append(PathPlaceholder(name, keep_slashes=spec == "path")) - return tuple(parts) - - -def _check_placeholder(path_template: str, name: str, spec: str | None, conversion: str | None) -> None: - """Raise ``DefinitionError`` unless it's ``{name}`` or ``{name:path}``. - - ``Formatter`` only checks the braces, so ``{user-id}``, ``{a.b}``, - ``{c[0]}``, ``{}``, ``{d!r}`` and ``{e:int}`` all reach here. - """ - if name.isidentifier() and conversion is None and spec in {"", "path"}: - return - # Rebuild the placeholder as it was written, for the message. - written = "{" + name + (f"!{conversion}" if conversion else "") + (f":{spec}" if spec else "") + "}" - raise DefinitionError(f"Path {path_template!r}: ClientX can't fill the placeholder {written}. {_PATH_SYNTAX}") - - -# --- Parameters outside the path ---------------------------------------------- -def _helper_argument(parameter: ParameterInfo, path_template: str) -> HttpxArgument: - """Return the argument a parameter outside the path goes to: its helper's. - - It needs a helper that says where it goes, ``Url()`` only fits a parameter - that fills a placeholder, each ``Send`` option must be in its spec's - ``send_options``, and a dump option must fit the type. An option set to - ``False`` counts too: it can't apply there either. - - Raises: - DefinitionError: If any of those doesn't hold. - """ - argument = parameter.httpx_argument - if argument is None: - raise DefinitionError( - f"Parameter {parameter.name!r} needs a helper that says where it goes: Query(), Header(), " - f"Json(), Body(), Form() or File(), as in {_example(parameter)}. Only a parameter named like a path " - "placeholder goes without one." - ) - if argument is HttpxArgument.URL: - raise DefinitionError( - f"Parameter {parameter.name!r} is marked Url(), but the path {path_template!r} has no " - f"placeholder {{{parameter.name}}}. Add the placeholder, or remove Url()." - ) - # Each Send option that's set must be one the argument's spec supports. - spec = _SPECS[argument] - for option in fields(Send): - if getattr(parameter.send, option.name) is None or option.name in spec.send_options: - continue - helpers = [s.helper for s in _SPECS.values() if option.name in s.send_options] - supported_by = helpers[0] if len(helpers) == 1 else f"{', '.join(helpers[:-1])} or {helpers[-1]}" - raise DefinitionError( - f"Parameter {parameter.name!r} has Send({option.name}=...), which applies only to a " - f"{supported_by} parameter, but it's marked {spec.helper}. Remove it." - ) - spec.check_send(parameter.send, parameter.name) - _check_dump_options(parameter) - return argument - - -def _example(parameter: ParameterInfo) -> str: - """Return the parameter with the helper it most likely needs, for a message. - - That's ``Query()`` for a plain value and ``Json()`` for anything else. - """ - if parameter.annotation is NO_VALUE: - return f"{parameter.name}: Annotated[str, Query()]" - base = parameter.base_type - type_text = base.__qualname__ if isinstance(base, type) else repr(base) - helper = "Query()" if _all_plain(parameter.annotation) else "Json()" - return f"{parameter.name}: Annotated[{type_text}, {helper}]" - - -# --- Send's dump options ------------------------------------------------------ -_PYDANTIC_CLASS = ( - "a pydantic model or pydantic dataclass (pydantic doesn't apply it to a stdlib dataclass: make it a " - "pydantic.dataclasses.dataclass)" -) - - -def _is_model(cls: type[Any]) -> bool: - return issubclass(cls, BaseModel) - - -def _is_model_or_pydantic_dataclass(cls: type[Any]) -> bool: - return issubclass(cls, BaseModel) or is_pydantic_dataclass(cls) - - -# Each field-only dump option, the classes whose fields it affects, and those in -# words, for messages. Dumping a value by its own type, pydantic silently -# ignores them on a stdlib dataclass and a dict, so an option on a type it -# can't affect raises instead. exclude_unset isn't here: it also leaves out the -# parameter itself, so _check_dump_options checks it on its own. -_DUMP_OPTIONS: dict[str, tuple[Callable[[type[Any]], bool], str]] = { - "exclude_none": (_is_model_or_pydantic_dataclass, _PYDANTIC_CLASS), - "exclude_defaults": (_is_model_or_pydantic_dataclass, _PYDANTIC_CLASS), -} - - -def _check_dump_options(parameter: ParameterInfo) -> None: - """Raise ``DefinitionError`` for a dump option that would do nothing. - - ``exclude_none`` and ``exclude_defaults`` affect the fields of some classes - only (``_DUMP_OPTIONS``), so the type must have one, at any depth: - ``list[User]`` counts. ``exclude_unset`` leaves out the parameter when it - isn't passed, and a pydantic model's unset fields, so it needs a default - other than ``None``, which is left out anyway, or a model. - """ - for option, (affects, described) in _DUMP_OPTIONS.items(): - if getattr(parameter.send, option) is None: - continue - if not _contains_class(parameter.annotation, affects): - hint = ( - " To leave out the parameter itself when the caller doesn't pass it, use Send(exclude_unset=True)." - if option == "exclude_defaults" - else "" - ) - raise DefinitionError( - f"Parameter {parameter.name!r} has Send({option}=...), which leaves out fields of " - f"{described}, but its type has none. Remove it.{hint}" - ) - if ( - parameter.send.exclude_unset is not None - and (parameter.default is NO_VALUE or parameter.default is None) - and not _contains_class(parameter.annotation, _is_model) - ): - why = ( - "it has no default, so it's always passed" - if parameter.default is NO_VALUE - else "its default is None, which is left out anyway" - ) - raise DefinitionError( - f"Parameter {parameter.name!r} has Send(exclude_unset=...), but {why}, and its type has no pydantic " - "model, whose unset fields it would leave out. Give it another default, or remove it." - ) - - -def _dump_options(parameter: ParameterInfo) -> DumpOptions: - """Return the parameter's ``Send`` dump options, for the plan.""" - send = parameter.send - return DumpOptions( - exclude_unset=bool(send.exclude_unset), - exclude_none=bool(send.exclude_none), - exclude_defaults=bool(send.exclude_defaults), - ) - - -def _contains_class(annotation: Any, wanted: Callable[[type[Any]], bool]) -> bool: - """Return whether ``annotation``, or a type inside it, is a wanted class.""" - return any((cls := _class_of(base)) is not None and wanted(cls) for base, _ in _walk(annotation)) - - -# --- Helpers and Send nested in a type ---------------------------------------- -def _check_nested(parameter: ParameterInfo) -> None: - """Raise ``DefinitionError`` if a helper or ``Send`` is inside the type. - - ClientX reads both only in the outermost ``Annotated``, so the helper in - ``Annotated[str, Header()] | None`` would be ignored. - """ - # base_type is the type without the outermost Annotated, which - # ParameterInfo has already read, so only what's inside it is searched. - inside = get_args(parameter.base_type) - if any(_contains(arg, _is_helper) for arg in inside): - raise DefinitionError( - f"Parameter {parameter.name!r} has a helper inside its type. ClientX reads a helper only " - "in the outermost Annotated, so move it there: for example, Annotated[str | None, Header()] " - "rather than Annotated[str, Header()] | None." - ) - if any(_contains(arg, _is_send) for arg in inside): - raise DefinitionError( - f"Parameter {parameter.name!r} has a Send inside its type. ClientX reads Send only in the " - "outermost Annotated, so move it there: for example, Annotated[list[str] | None, Json(), " - "Send(embed=True)] rather than Annotated[list[str], Json(), Send(embed=True)] | None." - ) - - -def _contains(annotation: Any, wanted: Callable[[object], bool]) -> bool: - """Return whether ``annotation``, or a type inside it, has ``wanted``.""" - return any(wanted(meta) for _, metadata in _walk(annotation) for meta in metadata) - - -def _is_helper(meta: object) -> bool: - return get_httpx_argument(meta) is not None - - -def _is_send(meta: object) -> bool: - return isinstance(meta, Send) - - -# --- Serializers in a parameter's type ---------------------------------------- -def _check_serializers(parameter: ParameterInfo) -> None: - """Raise ``DefinitionError`` for a pydantic serializer in the type. - - ClientX sends a value by its own type, at the call, so a - ``PlainSerializer`` or ``WrapSerializer`` in the parameter's annotation - would be ignored silently. A model's own serializers do run. - """ - if _contains(parameter.annotation, _is_serializer): - raise DefinitionError( - f"Parameter {parameter.name!r} has a pydantic serializer in its type, but ClientX sends a value by its " - "own type, so the serializer wouldn't run. Convert the value at the call, or make it a field of a " - "model, where its serializers apply." - ) - - -def _is_serializer(meta: object) -> bool: - return isinstance(meta, PlainSerializer | WrapSerializer) - - -# --- Defaults inside a helper ------------------------------------------------- -def _check_helper_default(parameter: ParameterInfo) -> None: - """Raise ``DefinitionError`` if the helper has a default. - - The helpers take ``pydantic.Field``'s arguments, so ``Query(1)``, - ``Query(default=1)`` and ``Query(default_factory=list)`` all set one, but - ClientX reads the default after ``=``, as Python does. - """ - field_info = parameter.clientx_field_info - if field_info is None: - return - if field_info.default is not PydanticUndefined or field_info.default_factory is not None: - raise DefinitionError( - f"Parameter {parameter.name!r} has a default inside its helper, where ClientX doesn't read it. " - "Put the default after = instead, as in page: Annotated[int, Query()] = 1." - ) - - -# --- Helpers and Send on a model's fields ------------------------------------- -def _check_model_fields(parameter: ParameterInfo) -> None: - """Raise ``DefinitionError`` if a model's field has a helper or ``Send``. - - The parameter's helper decides where the whole model goes, so ClientX - doesn't read either on a field. Each arm of a union is checked, so - ``Filters | None`` counts. - """ - for arm in _arms(parameter.annotation): - cls = _class_of(arm) - if cls is None or not issubclass(cls, BaseModel): - continue - for field_name, field_info in cls.model_fields.items(): - if _is_helper(field_info): - raise DefinitionError( - f"Field {field_name!r} of {cls.__name__} has a clientx.arguments helper, but ClientX reads " - f"helpers only on endpoint parameters. Put the helper on parameter {parameter.name!r} " - f"instead, as in Annotated[{cls.__name__}, Query()]: all of the model's fields then go there." - ) - if any(_is_send(meta) for meta in field_info.metadata): - raise DefinitionError( - f"Field {field_name!r} of {cls.__name__} has a Send, but ClientX reads Send only on " - f"endpoint parameters. Put it on parameter {parameter.name!r} instead." - ) - - -# --- Parameters sent under a key ---------------------------------------------- -def _plan_keyed(parameter: ParameterInfo, argument: HttpxArgument) -> PlannedParameter | SpreadParameter: - """Return where a parameter sent under a key goes, and its key. - - A value the argument's spec takes is sent once. If the spec - ``takes_lists``, a collection of them repeats the key, and a type that - takes either, such as ``str | list[str]``, is decided at the call. A - model, dataclass or mapping is spread, one value per field or item, if the - spec ``takes_text``. Anything else raises ``DefinitionError``, saying what - fits. - """ - spec = _SPECS[argument] - field_info = parameter.clientx_field_info - alias = field_info.serialization_alias if field_info is not None else None - key = spec.key(parameter.name, alias) - dump = _dump_options(parameter) - # Send(exclude_none=True) leaves out None, so it isn't sent as null. - sends_null = spec.sends_null and not dump.exclude_none - only_if_passed = dump.exclude_unset - if parameter.send.json_part: - # Any value pydantic can serialize: it's sent as JSON, not as text. - return PlannedParameter(parameter.name, argument, key, only_if_passed=only_if_passed, json_part=True, dump=dump) - arms = _arms(parameter.annotation) - if all(spec.takes_value(arm) for arm in arms): - return PlannedParameter( - parameter.name, argument, key, sends_null=sends_null, only_if_passed=only_if_passed, dump=dump - ) - if spec.takes_lists and all(spec.takes_value(arm) or _is_list_of(arm, spec) for arm in arms): - return PlannedParameter(parameter.name, argument, key, many=True, only_if_passed=only_if_passed) - if spec.takes_text and len(arms) == 1 and _has_fields(arms[0]): - return _plan_spread(parameter, argument, arms[0]) - raise DefinitionError( - f"Parameter {parameter.name!r} is marked {spec.helper}, so it goes to {spec.accepts}. {spec.what_fits()}" - ) - - -def _plan_spread(parameter: ParameterInfo, argument: HttpxArgument, annotation: Any) -> SpreadParameter: - """Plan a model, dataclass or mapping parameter spread into ``argument``. - - Each field, computed fields included, is sent under the key the - argument's spec gives its alias or attribute name, so a header field's - ``_`` becomes ``-`` too. A mapping's items are sent under their own keys, - as they are, and so is what a model with its own model serializer dumps: - its keys exist only at the call. Each field, or the mapping's value type, - must be something the argument takes, as a parameter must, so a nested - model raises ``DefinitionError``. - """ - spec = _SPECS[argument] - dump = _dump_options(parameter) - cls = cast("type[Any]", _class_of(annotation)) - if issubclass(cls, Mapping): - # dict[str, int] lists the key and value types; a bare dict, neither. - type_args = get_args(annotation) - value_type = type_args[1] if len(type_args) == 2 else Any - if not _fits(value_type, spec): - raise DefinitionError( - f"Parameter {parameter.name!r} is marked {spec.helper}, so each item of the mapping goes to " - f"{spec.accepts}. Its value type isn't one." - ) - return SpreadParameter(parameter.name, argument, many=spec.takes_lists, only_if_passed=dump.exclude_unset) - if _has_model_serializer(cls): - # It decides its own keys, so what it dumps is sent, as a mapping is. - return SpreadParameter( - parameter.name, argument, many=spec.takes_lists, only_if_passed=dump.exclude_unset, dump=dump - ) - keys: list[tuple[str, str]] = [] - for attribute, (field_type, alias) in _fields_of(cls).items(): - if not _fits(field_type, spec): - raise DefinitionError( - f"Parameter {parameter.name!r} is marked {spec.helper}, so each field of {cls.__name__} goes to " - f"{spec.accepts}. Field {attribute!r} isn't one." - ) - keys.append((attribute, spec.key(attribute, alias))) - return SpreadParameter( - parameter.name, argument, tuple(keys), many=spec.takes_lists, only_if_passed=dump.exclude_unset, dump=dump - ) - - -def _fields_of(cls: type[Any]) -> dict[str, tuple[Any, str | None]]: - """Return each field's type and serialization alias, by attribute name. - - A model's computed fields count too: they're dumped like fields. - """ - if issubclass(cls, BaseModel): - model_fields = {name: (info.annotation, info.serialization_alias) for name, info in cls.model_fields.items()} - computed = {name: (info.return_type, info.alias) for name, info in cls.model_computed_fields.items()} - return model_fields | computed - if is_pydantic_dataclass(cls): - return {name: (info.annotation, info.serialization_alias) for name, info in cls.__pydantic_fields__.items()} - # A standard library dataclass: its fields have no aliases. - hints = get_type_hints(cls) - return {field.name: (hints.get(field.name, Any), None) for field in fields(cls)} - - -def _has_model_serializer(cls: type[Any]) -> bool: - """Return whether a model or pydantic dataclass has a model serializer.""" - decorators = getattr(cls, "__pydantic_decorators__", None) - return decorators is not None and bool(decorators.model_serializers) - - -def _fits(annotation: Any, spec: type[HttpxArgumentSpec]) -> bool: - """Return whether a value of this type can go to the spec's argument. - - That's a value the spec takes, or, if it ``takes_lists``, a collection of - them, or a type that takes either. - """ - return all(spec.takes_value(arm) or (spec.takes_lists and _is_list_of(arm, spec)) for arm in _arms(annotation)) - - -def _check_keys(planned: Sequence[PlannedParameter | SpreadParameter]) -> None: - """Raise ``DefinitionError`` for a key that can't be sent or that clashes. - - Each key is checked by its argument's spec, as a header name must be ASCII. - Two values going to one argument under one key clash: httpx2 would keep - only one of them, silently. Only keys known now count: a mapping's keys - exist only at the call, so a clash with one is the caller's to avoid. An - argument whose spec ``keys_can_repeat``, such as files, sends both, so it - can't clash. - """ - # Each (argument, clash key) seen so far, to where it came from and its key. - sources: dict[tuple[HttpxArgument, str], tuple[str, str]] = {} - for item in planned: - if isinstance(item, PlannedParameter): - keyed = [(item.key, f"parameter {item.name!r}")] - elif item.keys is not None: - keyed = [(key, f"field {attribute!r} of parameter {item.name!r}") for attribute, key in item.keys] - else: - continue - spec = _SPECS[item.httpx_argument] - for key, source in keyed: - spec.check_key(key, source) - if spec.keys_can_repeat: - continue - for key, source in keyed: - where = (item.httpx_argument, spec.clash_key(key)) - if where not in sources: - sources[where] = (source, key) - continue - earlier_source, earlier_key = sources[where] - sent_as = f"both sent as {key!r}" if key == earlier_key else f"sent as {earlier_key!r} and {key!r}" - raise DefinitionError( - f"{earlier_source.capitalize()} and {source} are {sent_as} by {spec.helper}, the same key, so " - "one would be lost. Rename one, or give it an alias." - ) - - -# --- The body ----------------------------------------------------------------- -def _find_lone_body(parameters: Sequence[ParameterInfo]) -> ParameterInfo | None: - """Return the parameter that's the whole body by the lone rule, or ``None``. - - That's the only parameter going to an argument whose spec has - ``lone_is_body`` (JSON), unless it has ``Send(embed=True)``, or it's a - plain value, which is sent under its name. ``Any`` isn't plain here: it's - the whole body, like a model. Adding a second ``Json()`` parameter moves - the first under its name, as FastAPI does. - """ - candidates = [p for p in parameters if p.httpx_argument is not None and _SPECS[p.httpx_argument].lone_is_body] - if len(candidates) != 1: - return None - (parameter,) = candidates - arms = _arms(parameter.annotation) - if parameter.send.embed or (_all_plain(parameter.annotation) and Any not in arms): - return None - return parameter - - -def _plan_body(parameter: ParameterInfo, argument: HttpxArgument, *, is_async: bool) -> PlannedParameter: - """Plan a parameter that's the whole body: ``Body()``, or a lone ``Json()``. - - Its value must be one the argument's spec takes, and a stream must match - the client, or ``DefinitionError`` is raised. ``None`` means no body, never - ``null``, for JSON too: an API that takes an object rarely wants the body - ``null``. - """ - spec = _SPECS[argument] - if not all(spec.takes_value(arm) for arm in _arms(parameter.annotation)): - raise DefinitionError( - f"Parameter {parameter.name!r} is marked {spec.helper}, so it goes to {spec.accepts}. {spec.what_fits()}" - ) - if spec.streams: - _check_stream_kind(parameter, spec, is_async=is_async) - # The key isn't used: the value is the whole body. - dump = _dump_options(parameter) - return PlannedParameter(parameter.name, argument, key=parameter.name, only_if_passed=dump.exclude_unset, dump=dump) - - -def _check_stream_kind(parameter: ParameterInfo, spec: type[HttpxArgumentSpec], *, is_async: bool) -> None: - """Raise ``DefinitionError`` if a streamed body doesn't match the client. - - httpx2 raises ``RuntimeError`` at the call otherwise: a sync ``Client`` - can't send an async iterable, and an ``AsyncClient`` can't send a sync one, - a ``list[bytes]`` included. ``str``, ``bytes`` and ``Any`` fit both. - """ - for arm in _arms(parameter.annotation): - cls = _class_of(arm) - if cls is None or issubclass(cls, str | bytes): - continue - if is_async and issubclass(cls, Iterable): - raise DefinitionError( - f"Parameter {parameter.name!r} is marked {spec.helper} with a sync iterable, but the endpoint is " - "async, and an async client streams only an async iterable of bytes. Make it an " - "AsyncIterator[bytes], or bytes." - ) - if not is_async and issubclass(cls, AsyncIterable): - raise DefinitionError( - f"Parameter {parameter.name!r} is marked {spec.helper} with an async iterable, but the endpoint is " - "sync, and a sync client streams only an iterable of bytes. Make it an Iterator[bytes], or bytes, " - "or move the endpoint to an AsyncClientX." - ) - - -def _check_one_body(parameters: Sequence[ParameterInfo]) -> None: - """Raise ``DefinitionError`` if the parameters mix kinds of body. - - httpx2 sends one body, and given several, it silently drops the others. - """ - body_parameters: list[tuple[str, str]] = [] - for parameter in parameters: - if parameter.httpx_argument is None: # A path parameter without Url(). - continue - kind = _SPECS[parameter.httpx_argument].body_kind - if kind is not None: - body_parameters.append((parameter.name, kind)) - if len({kind for _, kind in body_parameters}) > 1: - listed = ", ".join(f"{name!r} ({kind})" for name, kind in body_parameters) - raise DefinitionError( - f"The parameters make more than one kind of body: {listed}. A request has one body: JSON, " - "the raw content of one Body() parameter, or a form of Form() and File() parameters." - ) - - -def _check_one_whole_body(parameters: Sequence[ParameterInfo]) -> None: - """Raise ``DefinitionError`` if two parameters go where only one can. - - That's an argument whose spec has ``whole_body``, such as ``content``: a - ``Body()`` parameter is the whole raw body. - """ - names_by_argument: dict[HttpxArgument, list[str]] = {} - for parameter in parameters: - if parameter.httpx_argument is not None and _SPECS[parameter.httpx_argument].whole_body: - names_by_argument.setdefault(parameter.httpx_argument, []).append(repr(parameter.name)) - for argument, names in names_by_argument.items(): - if len(names) > 1: - raise DefinitionError( - f"Parameters {', '.join(names)} are all marked {_SPECS[argument].helper}, but an endpoint " - "can have only one." - ) - - -# --- What a type is ----------------------------------------------------------- -# The plain-value allow-list: each has one defined text form. A subclass counts -# too, so bool (an int), datetime (a date) and any Enum are in. -_PLAIN_TYPES = (str, int, float, bool, Enum, date, datetime, time, UUID, Decimal, bytes) - - -def _is_plain(annotation: Any) -> bool: - """Return whether a value of this type is sent as one piece of text. - - It is if it's on the allow-list (a ``NewType`` of one counts), a - ``Literal`` of values on it, or ``Any`` or no annotation, the escape hatch. - It takes one type: ``_all_plain`` splits a union first. - """ - if annotation is Any or annotation is NO_VALUE: - return True - if get_origin(annotation) is Literal: - # Literal["asc", "desc"]: each value is plain. None is left out. - return all(value is None or isinstance(value, _PLAIN_TYPES) for value in get_args(annotation)) - cls = _class_of(annotation) - return cls is not None and issubclass(cls, _PLAIN_TYPES) - - -# How deep _arms follows unions inside unions, so a type alias that contains -# itself, such as ``type U = int | U``, can't recurse forever. -_MAX_UNION_DEPTH = 100 - - -def _arms(annotation: Any, depth: int = 0) -> list[Any]: - """Return the types a value of ``annotation`` can have, without ``None``. - - For a union, they're its members, each without ``Annotated`` or a ``type`` - alias, and a union inside a union is flattened: ``int | (str | None)`` gives - ``[int, str]``. A type that isn't a union is the only one. - """ - base, _ = unwrap_annotated(annotation) - if base is NoneType: - return [] - # Union is Optional[int] and Union[int, str]; UnionType is int | str. - if get_origin(base) not in {Union, UnionType} or depth > _MAX_UNION_DEPTH: - return [base] - return [arm for member in get_args(base) for arm in _arms(member, depth + 1)] - - -def _all_plain(annotation: Any) -> bool: - return all(_is_plain(arm) for arm in _arms(annotation)) - - -def _allows_none(annotation: Any, depth: int = 0) -> bool: - """Return whether ``None`` is one of the types a value can have. - - ``_arms`` drops ``None``, so this is how to ask about it: ``int | None``, - ``Optional[int]`` and ``Literal["a", None]`` allow it. - """ - base, _ = unwrap_annotated(annotation) - if base is NoneType or base is None: - return True - if get_origin(base) is Literal: - return None in get_args(base) - if get_origin(base) not in {Union, UnionType} or depth > _MAX_UNION_DEPTH: - return False - return any(_allows_none(member, depth + 1) for member in get_args(base)) - - -def _class_of(annotation: Any) -> type[Any] | None: - """Return the class a type stands for, or ``None`` if it isn't one. - - ``list[str]`` stands for ``list``, and ``NewType("UserId", int)`` for - ``int``. ``Literal["a"]`` and a ``TypeVar``, for example, aren't classes. - """ - # A NewType isn't a class; the type it's made from is. - while hasattr(annotation, "__supertype__"): - annotation = annotation.__supertype__ - # get_origin gives list for list[str], and None for a plain class like int. - cls: object = get_origin(annotation) or annotation - return cast("type[Any]", cls) if isinstance(cls, type) else None - - -def _walk(annotation: Any, seen: frozenset[TypeAliasType] = frozenset()) -> Iterator[tuple[Any, tuple[Any, ...]]]: - """Yield the type and each type inside it, outermost first. - - Each comes split by ``unwrap_annotated`` into its type and its metadata. - That expands a ``type`` alias too, so metadata inside one counts. ``seen`` - holds the aliases already expanded on the way here, so one that contains - itself, such as ``type Value = dict[str, Value] | str``, is expanded only - once. - """ - alias = annotation if isinstance(annotation, TypeAliasType) else get_origin(annotation) - if isinstance(alias, TypeAliasType): - if alias in seen: - return - seen |= {alias} - base, metadata = unwrap_annotated(annotation) - yield base, metadata - for arg in get_args(base): - yield from _walk(arg, seen) - - -def _has_fields(annotation: Any) -> bool: - """Return whether the type is a model, dataclass or mapping: has fields.""" - cls = _class_of(annotation) - return cls is not None and (issubclass(cls, BaseModel | Mapping) or is_dataclass(cls)) - - -def _is_list_of(annotation: Any, spec: type[HttpxArgumentSpec]) -> bool: - """Return whether the type is a collection of values the spec takes. - - Any collection but a mapping counts: ``list``, ``tuple``, ``set`` and - ``frozenset``, but not a tuple where the spec says ``tuples_are_values``. - A set's order can change from run to run, and the request with it. - ``str``, ``bytes`` and ``bytearray`` are collections too, but of - characters and numbers, not of values, so they don't count. - """ - cls = _class_of(annotation) - if cls is None or issubclass(cls, str | bytes | bytearray | Mapping) or not issubclass(cls, Collection): - return False - if spec.tuples_are_values and issubclass(cls, tuple): - return False - # tuple[str, ...] lists str and then Ellipsis. A bare list has no item - # types, so its items count as Any. - item_types = [item for item in get_args(annotation) if item is not Ellipsis] - return all(spec.takes_value(arm) for item in item_types for arm in _arms(item)) - - -def _is_file(annotation: Any) -> bool: - """Return whether a value of this type is one file httpx2 can send. - - That's file content (``bytes`` or a binary file), a ``(filename, - content[, content_type[, headers]])`` tuple, or ``Any``. Not ``str``: - httpx2 would send the string as the file's content, so ``"report.pdf"`` - would upload that text, named ``upload``. - """ - cls = _class_of(annotation) - if cls is not None and issubclass(cls, tuple): - return _is_file_tuple(annotation) - return _is_file_content(annotation) - - -def _is_file_content(annotation: Any) -> bool: - """Return whether the type is ``bytes``, a binary file, or ``Any``.""" - if annotation is Any or annotation is NO_VALUE: - return True - cls = _class_of(annotation) - return cls is not None and (issubclass(cls, bytes) or _is_binary_file(cls, annotation)) - - -def _is_binary_file(cls: type[Any], annotation: Any) -> bool: - """Return whether the type, whose class is ``cls``, is a file of bytes. - - ``IO[bytes]`` and ``BinaryIO`` are; so are ``io.BytesIO`` and what - ``open(path, "rb")`` returns. ``IO[str]``, ``TextIO`` and a text file - aren't. A bare ``IO`` has no item type, so it counts as ``Any``. - """ - if issubclass(cls, IO): - type_args = get_args(annotation) - return not issubclass(cls, TextIO) and (not type_args or type_args[0] is bytes or type_args[0] is Any) - return issubclass(cls, io.RawIOBase | io.BufferedIOBase) - - -def _is_file_tuple(annotation: Any) -> bool: - """Return whether the type is ``(filename, content[, type[, headers]])``. - - The filename and content type are ``str`` or ``None``; the content is file - content; the headers, the file part's own, a mapping of ``str`` to - ``str``. A bare ``tuple`` has no item types, so it counts as ``Any``. - """ - type_args = get_args(annotation) - if not type_args: - return True - if len(type_args) not in {2, 3, 4} or Ellipsis in type_args: - return False - filename, content, *rest = type_args - content_arms = _arms(content) - return ( - _is_text_or_none(filename) - and bool(content_arms) - and all(_is_file_content(arm) for arm in content_arms) - and all(_is_text_or_none(item) for item in rest[:1]) - and all(_is_text_mapping(item) for item in rest[1:]) - ) - - -def _is_text_mapping(annotation: Any) -> bool: - """Return whether the type is a mapping of ``str`` to ``str``, or ``Any``. - - A bare ``Mapping`` or ``dict`` has no item types, so it counts as ``Any``. - """ - arms = _arms(annotation) - for arm in arms: - if arm is Any: - continue - cls = _class_of(arm) - if cls is None or not issubclass(cls, Mapping): - return False - if not all(_is_text_or_none(item) for item in get_args(arm)): - return False - return bool(arms) - - -def _is_text_or_none(annotation: Any) -> bool: - """Return whether the type is ``str``, ``None``, both, or ``Any``.""" - return all(arm is Any or (isinstance(arm, type) and issubclass(arm, str)) for arm in _arms(annotation)) - - -def _is_content(annotation: Any) -> bool: - """Return whether a value of this type is a raw body httpx2 can send. - - That's ``str`` (sent as UTF-8), ``bytes``, or an iterable or async - iterable of bytes, which is streamed; or ``Any``. A model, mapping, - ``bytearray`` or ``memoryview`` is iterable too, but not of bytes. - """ - if annotation is Any or annotation is NO_VALUE: - return True - cls = _class_of(annotation) - if cls is None: - return False - if issubclass(cls, str | bytes): - return True - if issubclass(cls, BaseModel | Mapping | bytearray | memoryview) or not issubclass(cls, Iterable | AsyncIterable): - return False - # The item type comes first: Iterator[bytes], Generator[bytes, None, None]. - # A bare Iterator has none, so its items count as Any. - type_args = get_args(annotation) - return not type_args or all(arm is Any or arm is bytes for arm in _arms(type_args[0])) diff --git a/src/clientx/_request_model.py b/src/clientx/_request_model.py new file mode 100644 index 0000000..9b0478c --- /dev/null +++ b/src/clientx/_request_model.py @@ -0,0 +1,255 @@ +"""Build an endpoint's request model: a pydantic model of its parameters. + +``arguments_model`` builds the model itself, and a ``@tool`` method's too, +with only the shared settings in ``ARGUMENTS_CONFIG``. + +``Endpoint.set_up_request_plan`` calls ``build_request_model`` when the owner +class is defined. Each parameter but the first, ``self``, becomes a field, with +its full annotation, so the helper's alias and constraints apply and the rest +of the ``Annotated`` metadata, such as ``Send``, stays on the field, and with +the default after ``=``. A ``type`` alias is expanded first: pydantic doesn't +read a helper inside one. A parameter without an annotation is ``Any``. + +The model reads arguments by parameter name, never by alias, which is only the +key a value is sent under, and rejects an argument the endpoint doesn't have, +which a tool's caller can send. It validates in pydantic's lax mode, converting +what it can, such as ``"7"`` for an ``int`` or a ``dict`` for a model; a +helper's ``strict=True`` makes one parameter strict. An ``Enum`` field holds +its value. Defaults are the endpoint author's, so they aren't validated. + +Pydantic reads a helper only where ClientX does, building the model merges a +helper's default with the signature's, and it drops some names, so these are +checked first, on the parameters: + +- A helper or ``Send`` must be in the outermost ``Annotated``, not nested in + the type, as in ``Annotated[str, Header()] | None``, where it would be + ignored. +- A helper can't set ``default``: type checkers don't see it, so it goes after + ``=``. +- A helper's ``default_factory`` needs ``= None``, which marks the argument + optional for type checkers. +- A parameter can't have a name pydantic leaves out of a model, one starting + with ``_`` or ``model_config``, nor the name of a ``BaseModel`` attribute, + such as ``json``. Another name with ``alias=`` on the helper sends the same + key. ``arguments_model`` checks this one, for a ``@tool`` method too. + +Each call's arguments are validated with the model by ``validate_call``: only +the ones the caller passed, so the model fills in the defaults and runs the +default factories itself. A failure raises ``ArgumentError`` for the first +parameter that doesn't fit, with every problem in its message and pydantic's +``ValidationError`` as its cause. ``describe_errors`` writes those problems, +and ``clientx.tools`` uses it for its own messages too. +""" + +from collections.abc import Callable, Mapping, Sequence +from typing import Annotated, Any, get_args + +from pydantic import BaseModel, ConfigDict, ValidationError, create_model +from pydantic_core import PydanticUndefined + +from clientx._annotations import contains_metadata, is_helper, is_send +from clientx._signature import NO_VALUE, ParameterInfo, unwrap_annotated +from clientx.exceptions import ArgumentError, DefinitionError + +# The settings of every model of a method's arguments. +ARGUMENTS_CONFIG = ConfigDict( + arbitrary_types_allowed=True, + # A call's arguments are keyed by parameter name; an alias is only the key + # a value is sent under. + validate_by_name=True, + validate_by_alias=False, + # A call can't pass an argument the method doesn't have, and neither can + # a tool's caller. + extra="forbid", +) +# An endpoint's request model's, which the builder dumps. +_CONFIG = ARGUMENTS_CONFIG | ConfigDict( + use_enum_values=True, + # NaN and infinity stay floats when dumped, so JSON raises for them and + # text sends NaN and Infinity, rather than pydantic's null. + ser_json_inf_nan="constants", +) + + +# --- Entry point -------------------------------------------------------------- +def build_request_model(qualname: str, parameters: Sequence[ParameterInfo]) -> type[BaseModel]: + """Return the model that validates a call's arguments to the endpoint. + + ``parameters`` are the endpoint's, without the first, ``self``, which + receives the client or resource. The model is named after the endpoint's + ``qualname``. + + Raises: + DefinitionError: If a parameter's default or name can't go in a model, + by the rules in the module docstring. + """ + for parameter in parameters: + if _has_nested(parameter, is_helper): + raise _nested_helper_error(parameter.name) + if _has_nested(parameter, is_send): + raise _nested_send_error(parameter.name) + if _has_helper_default(parameter): + raise _helper_default_error(parameter.name) + if _has_factory_without_none_default(parameter): + raise _factory_without_none_default_error(parameter.name) + return arguments_model(qualname, parameters, _CONFIG) + + +def arguments_model( + qualname: str, parameters: Sequence[ParameterInfo], config: ConfigDict = ARGUMENTS_CONFIG +) -> type[BaseModel]: + """Return a model with a field for each parameter, named ``qualname``. + + ``build_request_model`` checks an endpoint's parameters first, and gives + its own ``config``; a ``@tool`` method's model has ``ARGUMENTS_CONFIG``. + + Raises: + DefinitionError: If a parameter has a name a model can't hold, by the + rules in the module docstring. + """ + for parameter in parameters: + if _is_dropped_by_pydantic(parameter.name): + raise _dropped_name_error(parameter.name) + if hasattr(BaseModel, parameter.name): + raise _base_model_name_error(parameter.name) + fields = {parameter.name: _field_definition(parameter) for parameter in parameters} + return create_model(qualname, __config__=config, **fields) + + +def _field_definition(parameter: ParameterInfo) -> Any: + """Return the field ``create_model`` takes for a parameter. + + That's the annotation alone, for a required field, or with the default + after ``=``. A helper's ``default_factory`` is the default: its ``= None`` + only tells type checkers the argument is optional. The annotation is + rebuilt from ``unwrap_annotated``, which expands a ``type`` alias, as in + ``type UserId = Annotated[int, Query(alias="userId")]``. + """ + if parameter.annotation is NO_VALUE: + annotation: Any = Any + else: + base, metadata = unwrap_annotated(parameter.annotation) + annotation = Annotated[base, *metadata] if metadata else base + field_info = parameter.clientx_field_info + if parameter.default is NO_VALUE or (field_info is not None and field_info.default_factory is not None): + return annotation + return (annotation, parameter.default) + + +def validate_call(model: type[BaseModel], arguments: Mapping[str, Any], endpoint: str) -> BaseModel: + """Return the request model validated from a call's arguments. + + ``arguments`` are the ones the caller passed, by parameter name. + ``endpoint`` is the endpoint's qualified name, for the message. + + Raises: + ArgumentError: If an argument doesn't fit its annotation. + """ + try: + return model.model_validate(arguments) + except ValidationError as error: + parameter = str(error.errors()[0]["loc"][0]) + raise ArgumentError( + f"The arguments to '{endpoint}' don't fit their annotations: {describe_errors(error, values=True)}. " + "No request was sent.", + parameter=parameter, + ) from error + + +# --- Error messages ----------------------------------------------------------- +def describe_errors(error: ValidationError, *, values: bool) -> str: + """Return each of Pydantic's errors as ``where: what``, without its URL. + + With ``values``, a value that's there but doesn't fit is shown too, short: + it's the caller's own argument. A response's values aren't. + """ + problems: list[str] = [] + for problem in error.errors(include_url=False, include_context=False): + where = ".".join(str(part) for part in problem["loc"]) or "the arguments" + # A tool method's stand-in reports "missing_keyword_only_argument". + if problem["type"].startswith("missing"): + problems.append(f"{where}: is required") + continue + text = f"{where}: {problem['msg']}" + if values: + text += f" (got {problem['input']!r:.80})" + problems.append(text) + return "; ".join(problems) + + +# --- Helpers and Send nested in a type ---------------------------------------- +def _has_nested(parameter: ParameterInfo, wanted: Callable[[object], bool]) -> bool: + """Return whether metadata ``wanted`` accepts is nested inside the type. + + ``base_type`` is the type without the outermost ``Annotated``, which + ``ParameterInfo`` has read, so only what's inside it is searched, through + unions, item types and ``type`` aliases. + """ + return any(contains_metadata(arg, wanted) for arg in get_args(parameter.base_type)) + + +def _nested_helper_error(name: str) -> DefinitionError: + return DefinitionError( + f"Parameter {name!r} has a helper inside its type. ClientX reads a helper only in the outermost " + "Annotated, so move it there: for example, Annotated[str | None, Header()] rather than " + "Annotated[str, Header()] | None." + ) + + +def _nested_send_error(name: str) -> DefinitionError: + return DefinitionError( + f"Parameter {name!r} has a Send inside its type. ClientX reads Send only in the outermost Annotated, so " + "move it there: for example, Annotated[list[str] | None, Json(), Send(embed=True)] rather than " + "Annotated[list[str], Json(), Send(embed=True)] | None." + ) + + +# --- Defaults ----------------------------------------------------------------- +def _has_helper_default(parameter: ParameterInfo) -> bool: + field_info = parameter.clientx_field_info + return field_info is not None and field_info.default is not PydanticUndefined + + +def _helper_default_error(name: str) -> DefinitionError: + return DefinitionError( + f"Parameter {name!r} has a default inside its helper, where type checkers don't see it. Put the default " + "after = instead, as in page: Annotated[int, Query()] = 1." + ) + + +def _has_factory_without_none_default(parameter: ParameterInfo) -> bool: + field_info = parameter.clientx_field_info + return field_info is not None and field_info.default_factory is not None and parameter.default is not None + + +def _factory_without_none_default_error(name: str) -> DefinitionError: + return DefinitionError( + f"Parameter {name!r} has a default_factory in its helper, so its default must be = None, which marks it " + "optional for type checkers. For example, tags: Annotated[list[str] | None, Json(default_factory=list)] = " + "None." + ) + + +# --- Names -------------------------------------------------------------------- +def _is_dropped_by_pydantic(name: str) -> bool: + """Return whether pydantic leaves the name out of a model, without a word. + + A name starting with ``_`` becomes a private attribute, and + ``model_config`` is read as the model's configuration. + """ + return name.startswith("_") or name == "model_config" + + +def _dropped_name_error(name: str) -> DefinitionError: + return DefinitionError( + f"Parameter {name!r} can't be a parameter here: pydantic leaves names starting with _, and " + "model_config, out of a model, so its value would never arrive. Rename it; on an endpoint, give its " + "helper alias=... if the API needs that name." + ) + + +def _base_model_name_error(name: str) -> DefinitionError: + return DefinitionError( + f"Parameter {name!r} has the name of a pydantic BaseModel attribute, which the model of the arguments " + "needs. Rename it; on an endpoint, give its helper alias=... if the API needs that name." + ) diff --git a/src/clientx/_request_routes.py b/src/clientx/_request_routes.py new file mode 100644 index 0000000..61b59d8 --- /dev/null +++ b/src/clientx/_request_routes.py @@ -0,0 +1,102 @@ +"""Work out where each of an endpoint's arguments goes, from its request model. + +``Endpoint.set_up_request_plan`` calls ``plan_routes`` once the request model +is built and checked (``_request_rules``), so every field outside the path has +a helper. Each field becomes a ``FieldRoute``, which the builder follows on +each call without reading annotations: + +- A field that fills a placeholder goes to the URL, under its own name. +- Every other field goes to its helper's ``build_request`` argument, under the + key the rules checked: its alias, or else its name, a header's ``_`` sent as + ``-``. +- A spread model, dataclass or mapping sends each field under its own key + instead; a mapping, or a model with its own model serializer, sends the keys + it dumps. +- The lone ``Json()`` parameter is the whole JSON body, unless it has + ``Send(embed=True)`` or dumps to a plain value, which is sent under its + name, as FastAPI does. ``Any``, and a type whose dump can't be known, aren't + plain here. +""" + +from dataclasses import dataclass, field +from typing import Any, cast + +from pydantic import BaseModel +from pydantic.fields import FieldInfo +from pydantic.json_schema import JsonSchemaValue + +from clientx._annotations import union_arms +from clientx._arguments import get_httpx_argument +from clientx._paths import PathPlaceholder, parse_path +from clientx._request_schema import has_unknown_schema, is_plain_schema, is_spread, resolve_refs, sent_key, spread_keys +from clientx._types import HttpxArgument, Send + + +@dataclass(frozen=True, slots=True) +class FieldRoute: + """Where one field of the request model goes, and the key it's sent under. + + Attributes: + name: The field's name, which is the parameter's. + key: The key it's sent under: its name in the path. + argument: The ``build_request`` argument it goes to. + send: Its ``Send`` options; an empty ``Send`` if it has none. + spread_keys: For a spread field, each field of its type as + ``(attribute, key)``; empty for a mapping or a model with its own + model serializer, which send the keys they dump. ``None`` if the + field isn't spread. + whole_body: Whether it's the lone ``Json()`` parameter, sent as the + whole JSON body rather than under ``key``. + """ + + name: str + key: str + argument: HttpxArgument + send: Send = field(default_factory=Send) + spread_keys: tuple[tuple[str, str], ...] | None = None + whole_body: bool = False + + +def plan_routes(model: type[BaseModel], path_template: str, schema: JsonSchemaValue) -> tuple[FieldRoute, ...]: + """Return each of the request model's fields as a ``FieldRoute``, in order. + + ``path_template`` is the endpoint's final path, a resource's prefix joined + on, and ``schema`` the model's, from ``request_schema``. + """ + defs: dict[str, JsonSchemaValue] = schema.get("$defs", {}) + in_path = {part.name for part in parse_path(path_template) if isinstance(part, PathPlaceholder)} + fields = model.model_fields + json_fields = [name for name, info in fields.items() if get_httpx_argument(info) is HttpxArgument.JSON] + routes: list[FieldRoute] = [] + for name, field_info in fields.items(): + send = _send_of(field_info) + if name in in_path: + routes.append(FieldRoute(name, name, HttpxArgument.URL, send)) + continue + # The rules checked that every field outside the path has a helper. + argument = cast("HttpxArgument", get_httpx_argument(field_info)) + key = sent_key(name, field_info.serialization_alias, argument) + keys = (spread_keys(field_info, argument) or ()) if is_spread(field_info, argument) else None + field_schema = resolve_refs(schema["properties"][name], defs) + whole_body = json_fields == [name] and _is_whole_json_body(field_info, field_schema, send) + routes.append(FieldRoute(name, key, argument, send, spread_keys=keys, whole_body=whole_body)) + return tuple(routes) + + +def _send_of(field_info: FieldInfo) -> Send: + """Return the field's ``Send``, or an empty one; the last one wins.""" + return next((meta for meta in reversed(field_info.metadata) if isinstance(meta, Send)), Send()) + + +def _is_whole_json_body(field_info: FieldInfo, field_schema: JsonSchemaValue, send: Send) -> bool: + """Return whether the lone ``Json()`` field is the whole JSON body. + + It is unless it has ``Send(embed=True)`` or dumps to a plain value. ``Any`` + isn't plain here, whose schema says nothing, nor is a type whose dump can't + be known: a value of any type is the whole body. + """ + if send.embed: + return False + if Any in union_arms(field_info.annotation) or has_unknown_schema(field_schema): + return True + return not is_plain_schema(field_schema) diff --git a/src/clientx/_request_rules.py b/src/clientx/_request_rules.py new file mode 100644 index 0000000..e233422 --- /dev/null +++ b/src/clientx/_request_rules.py @@ -0,0 +1,613 @@ +"""Check an endpoint's request model when its class is defined. + +``Endpoint.set_up_request_plan`` calls ``check_request_model`` right after +``build_request_model``. The rules read the model's fields, which hold what +routing and calls use: each field's helper mark, alias, type and metadata. +Each rule is one ``if`` in ``check_request_model``, with the function that +builds its error next to it. + +- Every placeholder in the path needs a parameter of its name. +- A parameter's type can't be, or hold, a pydantic secret (``SecretStr``, + ``SecretBytes``, ``Secret[...]``): pydantic dumps one as ``"**********"``, + so the API would get the stars. Credentials go in the client's ``auth=``. + A model's own secret fields are its author's to serialize. +- A model's field can't have a helper or ``Send``: the parameter's helper + decides where all of its fields go. +- A parameter that fills a placeholder takes no helper but ``Url()``, no + alias, since it's matched to its placeholder by name, no ``Send``, and a + type that can't be ``None``, which would always fail at the call, and that + dumps to a plain value. +- Every other parameter needs a helper, which says where it goes, and that + helper can't be ``Url()``: there's no placeholder for it to fill. +- A value is judged by what it dumps to, from the model's serialization + schema, so a serializer's ``return_type`` counts: a plain value dumps to a + string, number or boolean. The query string and a form take a plain value + or a list of them, and headers a plain value. A spread model, dataclass or + mapping is spread into them, each field or value fitting the same way. A + type whose dump can't be known, such as a class of your own without a + serializer, raises. +- A file (``File()``) is ``bytes``, a binary file, or a ``(filename, + content[, content_type[, headers]])`` tuple, or a list of them, never + ``str``. The raw body (``Body()``) is ``str``, ``bytes``, or a stream of + bytes that matches the endpoint: sync for ``def``, async for ``async def``. +- A ``File()`` or ``Body()`` whose type holds anything but ``str``, + ``bytes``, ``None``, tuples, lists and dicts, such as a binary file, a + stream or ``Any``, needs ``SkipValidation`` in its annotation, as in + ``Annotated[BinaryIO, File(), SkipValidation]``. Pydantic can't validate + ``typing``'s IO types, and its dump would wrap a file or stream in an + iterator, so such a value is passed on as it is; ``SkipValidation`` says so + in the signature. A file tuple such as ``tuple[str, bytes, str]``, or a + list of them, validates and dumps as it is, so it needs none. +- A request has one kind of body: JSON, the raw content of one ``Body()`` + parameter, or a form of ``Form()`` and ``File()`` parameters. +- Two values sent to one argument under one key clash, as httpx2 would keep + only one, but files, which repeat the field. Header names compare + case-insensitively, and must be ASCII. A key is the alias, or else the + name, a header's ``_`` sent as ``-``; a spread model or dataclass sends each + field under its own. A spread mapping's keys, and those of a model with its + own model serializer, exist only at the call, so they aren't checked. + +The rules read each field's serialization schema, from ``request_schema``, and +its keys through the helpers in ``_request_schema``, which the routes share. +""" + +from collections.abc import AsyncIterable, Collection, Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from typing import Any, Literal, cast, get_args + +from pydantic import BaseModel, PlainSerializer, SkipValidation, WrapSerializer +from pydantic.fields import FieldInfo +from pydantic.json_schema import JsonSchemaValue + +from clientx._annotations import ( + all_plain, + allows_none, + class_of, + contains_metadata, + contains_secret, + fields_of, + has_model_serializer, + holds_only_text_and_bytes, + is_content, + is_file, + is_helper, + is_plain, + is_send, + union_arms, +) +from clientx._arguments import get_httpx_argument +from clientx._paths import PathPlaceholder, parse_path +from clientx._request_schema import ( + has_unknown_schema, + is_plain_or_list_schema, + is_plain_schema, + is_spread, + resolve_refs, + sent_key, + spread_keys, +) +from clientx._types import HttpxArgument, Send +from clientx.exceptions import DefinitionError + +# Each helper as written, for messages. +_HELPER_NAMES: dict[HttpxArgument, str] = { + HttpxArgument.URL: "Url()", + HttpxArgument.PARAMS: "Query()", + HttpxArgument.HEADERS: "Header()", + HttpxArgument.DATA: "Form()", + HttpxArgument.FILES: "File()", + HttpxArgument.CONTENT: "Body()", + HttpxArgument.JSON: "Json()", +} + +# The kind of body each body argument makes. Form() and File() make the same +# one, a form. +_BODY_KINDS: dict[HttpxArgument, str] = { + HttpxArgument.JSON: "JSON", + HttpxArgument.CONTENT: "raw content", + HttpxArgument.DATA: "a form", + HttpxArgument.FILES: "a form", +} + +# The arguments whose values are sent under a key that can clash. Files can +# share a key, and Url() and Body() have none. +_KEYED_ARGUMENTS = frozenset({HttpxArgument.PARAMS, HttpxArgument.HEADERS, HttpxArgument.DATA, HttpxArgument.JSON}) + +# Where a query, header or form value goes and what it takes, for messages. +_ACCEPTS: dict[HttpxArgument, str] = { + HttpxArgument.PARAMS: "the query string, which takes a plain value or a collection of them", + HttpxArgument.HEADERS: "the headers, which take a plain value", + HttpxArgument.DATA: "the form, which takes a plain value or a collection of them", +} + +# How to send a type that doesn't fit, for messages. +_ANOTHER_TYPE = ( + "For another type, add a PlainSerializer with a plain return_type, or annotate it as str and convert the value " + "at the call." +) + + +# --- Entry point -------------------------------------------------------------- +def check_request_model(path_template: str, model: type[BaseModel], schema: JsonSchemaValue, *, is_async: bool) -> None: + """Raise ``DefinitionError`` at the first rule the model breaks. + + ``path_template`` is the endpoint's final path, a resource's prefix joined + on; ``schema`` is the model's, from ``request_schema``; and ``is_async`` + says whether the endpoint is ``async def``, which a streamed body must + match. The rules are in the module docstring. + """ + placeholders = [part for part in parse_path(path_template) if isinstance(part, PathPlaceholder)] + if missing := [placeholder for placeholder in placeholders if placeholder.name not in model.model_fields]: + raise _unfilled_placeholder_error(path_template, missing) + + by_name = {placeholder.name: placeholder for placeholder in placeholders} + defs: dict[str, JsonSchemaValue] = schema.get("$defs", {}) + together = _Parameters() + for name, field_info in model.model_fields.items(): + field_schema = resolve_refs(schema["properties"][name], defs) + if error := _find_secret_error(name, field_info) or _find_marked_model_field_error(name, field_info): + raise error + if placeholder := by_name.get(name): + if error := _find_path_parameter_error(path_template, placeholder, name, field_info, field_schema): + raise error + continue + argument = get_httpx_argument(field_info) + if argument is None: + raise _missing_helper_error(name, field_info) + if argument is HttpxArgument.URL: + raise _url_without_placeholder_error(path_template, name) + value_error = _find_value_error(name, field_info, argument, field_schema, defs) + if error := value_error or _find_file_or_body_error(name, field_info, argument, is_async=is_async): + raise error + together.add(name, field_info, argument) + + if error := together.find_error(): + raise error + + +@dataclass +class _Parameters: + """What the parameters outside the path are checked for together. + + ``check_request_model`` adds each in its one pass, then asks for the first + error: more than one kind of body, more than one ``Body()``, then a key that + can't be sent or that clashes. + """ + + # Each body parameter's kind of body, by name. + body_kinds: dict[str, str] = field(default_factory=dict[str, str]) + # The Body() parameters. + raw_bodies: list[str] = field(default_factory=list[str]) + # Each key sent, as (argument, key, source), in parameter order. + keys: list[tuple[HttpxArgument, str, str]] = field(default_factory=list[tuple[HttpxArgument, str, str]]) + + def add(self, name: str, field_info: FieldInfo, argument: HttpxArgument) -> None: + if argument in _BODY_KINDS: + self.body_kinds[name] = _BODY_KINDS[argument] + if argument is HttpxArgument.CONTENT: + self.raw_bodies.append(name) + if argument in _KEYED_ARGUMENTS: + self.keys.extend((argument, key, source) for key, source in _sent_keys(name, field_info, argument)) + + def find_error(self) -> DefinitionError | None: + if len(set(self.body_kinds.values())) > 1: + return _mixed_body_error(self.body_kinds) + if len(self.raw_bodies) > 1: + return _several_raw_bodies_error(self.raw_bodies) + return _find_key_error(self.keys) + + +# --- Helpers and Send on a model's fields ------------------------------------- +def _find_marked_model_field_error(name: str, field_info: FieldInfo) -> DefinitionError | None: + """Return the error for a helper or ``Send`` on a model's field, if any. + + Each arm of a union is checked, so ``Filters | None`` counts. + """ + for arm in union_arms(field_info.annotation): + cls = class_of(arm) + if cls is None or not issubclass(cls, BaseModel): + continue + for model_field_name, model_field in cls.model_fields.items(): + if is_helper(model_field): + return DefinitionError( + f"Field {model_field_name!r} of {cls.__name__} has a clientx.arguments helper, but ClientX " + f"reads helpers only on endpoint parameters. Put the helper on parameter {name!r} instead, as " + f"in Annotated[{cls.__name__}, Query()]: all of the model's fields then go there." + ) + if any(is_send(meta) for meta in model_field.metadata): + return DefinitionError( + f"Field {model_field_name!r} of {cls.__name__} has a Send, but ClientX reads Send only on " + f"endpoint parameters. Put it on parameter {name!r} instead." + ) + return None + + +# --- The path ----------------------------------------------------------------- +def _find_secret_error(name: str, field_info: FieldInfo) -> DefinitionError | None: + if not contains_secret(field_info.annotation): + return None + return DefinitionError( + f"Parameter {name!r} is a pydantic secret, such as SecretStr, which pydantic sends as '**********'. Pass " + "credentials with the client's auth=, httpx2's authentication option, rather than as a parameter. To send " + "the value anyway, annotate it str." + ) + + +def _unfilled_placeholder_error(path_template: str, missing: list[PathPlaceholder]) -> DefinitionError: + """Return the error for placeholders no parameter is named after. + + They're listed in path order, as written, ``{name:path}`` included. + """ + if len(missing) == 1: + (placeholder,) = missing + return DefinitionError( + f"Path {path_template!r} has the placeholder {placeholder}, but no parameter is named " + f"{placeholder.name!r}. Add the parameter, or remove the placeholder." + ) + listed = ", ".join(str(placeholder) for placeholder in missing) + return DefinitionError( + f"Path {path_template!r} has the placeholders {listed}, but no parameters with those names. Add the " + "parameters, or remove the placeholders." + ) + + +def _find_path_parameter_error( + path_template: str, placeholder: PathPlaceholder, name: str, field_info: FieldInfo, field_schema: JsonSchemaValue +) -> DefinitionError | None: + """Return the error for a parameter that can't fill its placeholder.""" + fills = f"Parameter {name!r} fills {placeholder} in the path {path_template!r}" + argument = get_httpx_argument(field_info) + if argument is not None and argument is not HttpxArgument.URL: + return DefinitionError( + f"{fills}, so it can't also be marked {_HELPER_NAMES[argument]}. Remove its helper, or rename the " + "parameter or the placeholder." + ) + if field_info.serialization_alias not in {None, name}: + return DefinitionError( + f"{fills}, so its Url(alias=...) has no effect: a path parameter is matched to its placeholder by " + "name. Remove the alias, or rename the parameter." + ) + if allows_none(field_info.annotation): + return DefinitionError( + f"{fills}, so it can't be None: a None value would always fail at the call. Remove None from its type." + ) + judged = _judge(field_schema, field_info.annotation, field_info.metadata, lists=False) + if judged == "unknown": + return _unknown_dump_error(f"parameter {name!r}") + if judged == "doesn't fit": + return DefinitionError( + f"{fills}, so it must be a plain value: one that dumps to a string, number or boolean, as str, int, an " + f"Enum or a UUID do. {_ANOTHER_TYPE}" + ) + if any(isinstance(meta, Send) for meta in field_info.metadata): + return DefinitionError(f"{fills}, so Send doesn't apply to it. Remove it.") + return None + + +# --- Where a parameter goes --------------------------------------------------- +def _missing_helper_error(name: str, field_info: FieldInfo) -> DefinitionError: + return DefinitionError( + f"Parameter {name!r} needs a helper that says where it goes: Query(), Header(), Json(), Body(), Form() " + f"or File(), as in {_example(name, field_info.annotation)}. Only a parameter named like a path " + "placeholder goes without one." + ) + + +def _example(name: str, annotation: Any) -> str: + """Return the parameter with the helper it most likely needs, for a message. + + That's ``Query()`` for a plain value, or a parameter without an annotation, + and ``Json()`` for anything else. + """ + if annotation is Any: + return f"{name}: Annotated[str, Query()]" + type_text = annotation.__qualname__ if isinstance(annotation, type) else repr(annotation) + helper = "Query()" if all_plain(annotation) else "Json()" + return f"{name}: Annotated[{type_text}, {helper}]" + + +def _url_without_placeholder_error(path_template: str, name: str) -> DefinitionError: + return DefinitionError( + f"Parameter {name!r} is marked Url(), but the path {path_template!r} has no placeholder {{{name}}}. Add " + "the placeholder, or remove Url()." + ) + + +# --- Query strings, headers and forms ----------------------------------------- +def _find_value_error( + name: str, + field_info: FieldInfo, + argument: HttpxArgument, + field_schema: JsonSchemaValue, + defs: dict[str, JsonSchemaValue], +) -> DefinitionError | None: + """Return the error for a query, header or form value that doesn't fit. + + A form's JSON part takes any value: it's sent as JSON. + """ + if argument not in _ACCEPTS or _send_of(field_info).json_part: + return None + if is_spread(field_info, argument): + return _find_spread_field_error(name, field_info, argument, field_schema, defs) + judged = _judge( + field_schema, field_info.annotation, field_info.metadata, lists=argument is not HttpxArgument.HEADERS + ) + if judged == "unknown": + return _unknown_dump_error(f"parameter {name!r}") + if judged == "fits": + return None + what = ( + "a string, number or boolean" + if argument is HttpxArgument.HEADERS + else "a string, number or boolean, or a list of them" + ) + return DefinitionError( + f"Parameter {name!r} is marked {_HELPER_NAMES[argument]}, so it goes to {_ACCEPTS[argument]}: it must " + f"dump to {what}, as str, int, an Enum or a UUID do. {_ANOTHER_TYPE}" + ) + + +def _find_spread_field_error( + name: str, + field_info: FieldInfo, + argument: HttpxArgument, + field_schema: JsonSchemaValue, + defs: dict[str, JsonSchemaValue], +) -> DefinitionError | None: + """Return the error for a spread field, or mapping value, that doesn't fit. + + Each field of a spread model or dataclass, computed fields included, or + each value of a mapping, is sent under its own key, so it must fit as a + parameter would. A model with its own model serializer decides its keys at + the call, so it isn't checked. + """ + cls = cast("type[Any]", class_of(union_arms(field_info.annotation)[0])) + if has_model_serializer(cls): + return None + # Each part's schema and type: a mapping's values, under an empty name for + # messages, or each field. A bare dict's values are True: anything. + parts: dict[str, tuple[JsonSchemaValue, Any]] + if issubclass(cls, Mapping): + value_schema = field_schema.get("additionalProperties", True) + type_args = get_args(union_arms(field_info.annotation)[0]) + value_type = type_args[1] if len(type_args) == 2 else Any + parts = {"": ({} if value_schema is True else value_schema, value_type)} + else: + types = fields_of(cls) + parts = { + attribute: (schema, types.get(attribute, (Any, None))[0]) + for attribute, schema in field_schema.get("properties", {}).items() + } + lists = argument is not HttpxArgument.HEADERS + for attribute, (unresolved, part_type) in parts.items(): + judged = _judge(resolve_refs(unresolved, defs), part_type, (), lists=lists) + source = f"field {attribute!r} of parameter {name!r}" if attribute else f"each value of parameter {name!r}" + if judged == "unknown": + return _unknown_dump_error(source) + if judged == "fits": + continue + helper, accepts = _HELPER_NAMES[argument], _ACCEPTS[argument] + if not attribute: + return DefinitionError( + f"Parameter {name!r} is marked {helper}, so each item of the mapping goes to {accepts}. Its value " + "type isn't one." + ) + return DefinitionError( + f"Parameter {name!r} is marked {helper}, so each field of {cls.__name__} goes to {accepts}. Field " + f"{attribute!r} isn't one." + ) + return None + + +def _judge( + schema: JsonSchemaValue, annotation: Any, metadata: Sequence[object], *, lists: bool +) -> Literal["fits", "unknown", "doesn't fit"]: + """Return whether a value dumps to a plain value, or a list of them. + + The schema decides, so a serializer's ``return_type`` counts. Where the + schema can't tell, as for ``Collection[str]``, which pydantic only checks + with ``isinstance``, the type does: ``unknown`` only if neither can, such + as for a class of your own. A serializer in the type, ``metadata`` + included, rules the type out: what it returns is unknown without a + ``return_type``. + """ + if has_unknown_schema(schema): + has_serializer = contains_metadata(annotation, _is_serializer) or any(_is_serializer(meta) for meta in metadata) + return "fits" if not has_serializer and _fits_by_type(annotation, lists=lists) else "unknown" + fits = is_plain_or_list_schema(schema) if lists else is_plain_schema(schema) + return "fits" if fits else "doesn't fit" + + +def _fits_by_type(annotation: Any, *, lists: bool) -> bool: + """Return whether each arm of the type is plain, or a collection of them.""" + return all(is_plain(arm) or (lists and _is_collection_of_plain(arm)) for arm in union_arms(annotation)) + + +def _is_collection_of_plain(annotation: Any) -> bool: + """Return whether the type is a collection of plain values. + + ``str``, ``bytes`` and mappings are collections too, but not of values. + """ + cls = class_of(annotation) + if cls is None or not issubclass(cls, Collection) or issubclass(cls, str | bytes | bytearray | Mapping): + return False + return all(is_plain(arm) for item in get_args(annotation) if item is not Ellipsis for arm in union_arms(item)) + + +def _is_serializer(meta: object) -> bool: + return isinstance(meta, PlainSerializer | WrapSerializer) + + +def _unknown_dump_error(source: str) -> DefinitionError: + """Return the error for a value whose dump can't be known. + + ``source`` says where it comes from: ``"parameter 'pet'"`` or ``"field + 'owner' of parameter 'filters'"``. + """ + return DefinitionError( + f"{source.capitalize()} has a type ClientX can't tell the dumped form of, such as a class of your own " + "without a serializer. Give it a PlainSerializer with a plain return_type, as in PlainSerializer(str, " + "return_type=str), or annotate it with a plain type." + ) + + +def _send_of(field_info: FieldInfo) -> Send: + """Return the field's ``Send``, or an empty one; the last one wins.""" + return next((meta for meta in reversed(field_info.metadata) if isinstance(meta, Send)), Send()) + + +# --- Files and the raw body --------------------------------------------------- +def _find_file_or_body_error( + name: str, field_info: FieldInfo, argument: HttpxArgument, *, is_async: bool +) -> DefinitionError | None: + """Return the error for a file or raw body that can't be sent, if any. + + The schema can't describe files or streams, so this reads the type itself. + A type that isn't a file or raw body at all, such as ``Path``, is reported + before a missing ``SkipValidation``, as that error says more. + """ + if argument not in {HttpxArgument.FILES, HttpxArgument.CONTENT}: + return None + arms = union_arms(field_info.annotation) + if argument is HttpxArgument.FILES: + if not all(is_file(arm) or _is_list_of_files(arm) for arm in arms): + return DefinitionError( + f"Parameter {name!r} is marked File(), so it goes to the form's files, which take a file or a " + 'collection of them. A file is bytes, a binary file such as open(path, "rb"), or a (filename, ' + "content[, content_type[, headers]]) tuple, or Any. Pass text as bytes, with text.encode(), and " + "open a path yourself." + ) + elif not all(is_content(arm) for arm in arms): + return DefinitionError( + f"Parameter {name!r} is marked Body(), so it goes to the raw body. The raw body is str, bytes, or an " + "iterable or async iterable of bytes, or Any." + ) + elif error := _find_wrong_stream_error(name, arms, is_async=is_async): + return error + if not holds_only_text_and_bytes(field_info.annotation) and not _skips_validation(field_info): + return _missing_skip_validation_error(name, argument) + return None + + +def _skips_validation(field_info: FieldInfo) -> bool: + """Return whether the field has ``SkipValidation`` in its annotation. + + ``Annotated[T, SkipValidation]`` adds the class itself to the metadata, and + ``SkipValidation[T]`` an instance of it. + """ + # Pydantic declares SkipValidation as an Annotated alias for type checkers, + # but at runtime it's a class, which isinstance needs. + skip_validation = cast("type[Any]", SkipValidation) + return any(meta is skip_validation or isinstance(meta, skip_validation) for meta in field_info.metadata) + + +def _missing_skip_validation_error(name: str, argument: HttpxArgument) -> DefinitionError: + helper = _HELPER_NAMES[argument] + return DefinitionError( + f"Parameter {name!r} is marked {helper} with a type that holds a binary file, a stream or Any, so it " + "needs SkipValidation: ClientX sends a file or stream as it is, without validating it. Add it, as in " + f"Annotated[BinaryIO, {helper}, SkipValidation]." + ) + + +def _is_list_of_files(annotation: Any) -> bool: + """Return whether the type is a collection of files, sent under one field. + + A tuple is one file, ``(filename, content)``, so it isn't a collection + here; nor are ``str``, ``bytes`` and mappings. A bare collection's items + count as ``Any``. + """ + cls = class_of(annotation) + if cls is None or not issubclass(cls, Collection): + return False + if issubclass(cls, str | bytes | bytearray | Mapping | tuple): + return False + return all(is_file(arm) for item in get_args(annotation) for arm in union_arms(item)) + + +def _find_wrong_stream_error(name: str, arms: list[Any], *, is_async: bool) -> DefinitionError | None: + """Return the error for a stream the endpoint's client can't send, if any. + + httpx2 raises at the call otherwise: a sync ``Client`` can't send an async + iterable, and an ``AsyncClient`` can't send a sync one, a ``list[bytes]`` + included. ``str`` and ``bytes`` fit both. + """ + for arm in arms: + cls = class_of(arm) + if cls is None or issubclass(cls, str | bytes): + continue + if is_async and issubclass(cls, Iterable): + return DefinitionError( + f"Parameter {name!r} is marked Body() with a sync iterable, but the endpoint is async, and an " + "async client streams only an async iterable of bytes. Make it an AsyncIterator[bytes], or bytes." + ) + if not is_async and issubclass(cls, AsyncIterable): + return DefinitionError( + f"Parameter {name!r} is marked Body() with an async iterable, but the endpoint is sync, and a sync " + "client streams only an iterable of bytes. Make it an Iterator[bytes], or bytes, or move the " + "endpoint to an AsyncClientX." + ) + return None + + +# --- The body ----------------------------------------------------------------- +def _mixed_body_error(body_kinds: dict[str, str]) -> DefinitionError: + """Return the error for parameters that make more than one kind of body. + + httpx2 sends one body, and given several, it silently drops the others. + """ + listed = ", ".join(f"{name!r} ({kind})" for name, kind in body_kinds.items()) + return DefinitionError( + f"The parameters make more than one kind of body: {listed}. A request has one body: JSON, the raw " + "content of one Body() parameter, or a form of Form() and File() parameters." + ) + + +def _several_raw_bodies_error(raw_bodies: list[str]) -> DefinitionError: + listed = ", ".join(repr(name) for name in raw_bodies) + return DefinitionError(f"Parameters {listed} are all marked Body(), but an endpoint can have only one.") + + +# --- Keys --------------------------------------------------------------------- +def _sent_keys(name: str, field_info: FieldInfo, argument: HttpxArgument) -> list[tuple[str, str]]: + """Return each key a parameter is sent under, with where it comes from. + + A spread parameter sends each field of its type under its own key. A spread + mapping, or a model with its own model serializer, has its keys only at + the call, so none are known here. + """ + if not is_spread(field_info, argument): + return [(sent_key(name, field_info.serialization_alias, argument), f"parameter {name!r}")] + return [ + (key, f"field {attribute!r} of parameter {name!r}") + for attribute, key in spread_keys(field_info, argument) or () + ] + + +def _find_key_error(keys: list[tuple[HttpxArgument, str, str]]) -> DefinitionError | None: + """Return the error for a key that can't be sent or that clashes, if any. + + ``keys`` are each ``(argument, key, source)``, in parameter order. httpx2 + sends a header name as ASCII, and would raise ``UnicodeEncodeError`` at + the call; a Python name can be any letter. + """ + # Each (argument, compared key) seen so far, to its source and key. + seen: dict[tuple[HttpxArgument, str], tuple[str, str]] = {} + for argument, key, source in keys: + is_header = argument is HttpxArgument.HEADERS + if is_header and not key.isascii(): + return DefinitionError( + f"{source.capitalize()} is sent by Header() as {key!r}, which isn't ASCII, and header names must " + "be. Give it an ASCII alias." + ) + compared = (argument, key.lower() if is_header else key) + if compared not in seen: + seen[compared] = (source, key) + continue + earlier_source, earlier_key = seen[compared] + sent_as = f"both sent as {key!r}" if key == earlier_key else f"sent as {earlier_key!r} and {key!r}" + return DefinitionError( + f"{earlier_source.capitalize()} and {source} are {sent_as} by {_HELPER_NAMES[argument]}, the same key, " + "so one would be lost. Rename one, or give it an alias." + ) + return None diff --git a/src/clientx/_request_schema.py b/src/clientx/_request_schema.py new file mode 100644 index 0000000..0d03cfe --- /dev/null +++ b/src/clientx/_request_schema.py @@ -0,0 +1,180 @@ +"""Read what a request model's fields dump to, and the keys they're sent under. + +The rules (``_request_rules``) and routes (``_request_routes``) both read these +when the class is defined: + +- ``request_schema`` is the model's serialization schema, so a field is + judged by what its value dumps to, a serializer's ``return_type`` included. + A type pydantic can't describe is marked rather than failing the schema + (``has_unknown_schema``). ``resolve_refs`` replaces a ``$ref`` with its + definition, and ``is_plain_schema`` tells a plain value: a string, number, + integer or boolean. +- A model, dataclass or mapping marked ``Query()``, ``Header()`` or ``Form()`` + is spread, a key per field (``is_spread``, ``spread_keys``). A value's key is + its alias, or else its name, a header's ``_`` sent as ``-`` (``sent_key``). +""" + +from collections.abc import Mapping +from typing import Any, cast + +from pydantic import BaseModel +from pydantic.fields import FieldInfo +from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue, JsonSchemaWarningKind +from pydantic_core import core_schema + +from clientx._annotations import class_of, fields_of, has_fields, has_model_serializer, union_arms +from clientx._types import HttpxArgument, Send + +# The key _MarkUnknown puts in the schema of a type pydantic can't describe. +_UNKNOWN = "x-clientx-unknown" + +# The JSON schema types a plain value dumps to. +_PLAIN_SCHEMA_TYPES = frozenset({"string", "number", "integer", "boolean"}) + +# The arguments that spread a model, dataclass or mapping, a key per field. +_SPREAD_ARGUMENTS = frozenset({HttpxArgument.PARAMS, HttpxArgument.HEADERS, HttpxArgument.DATA}) + + +# --- What a type dumps to ----------------------------------------------------- +def request_schema(model: type[BaseModel]) -> JsonSchemaValue: + """Return what each of the request model's fields dumps to. + + It's the model's serialization schema, keyed by field name, not alias. A + field pydantic can't describe is marked rather than failing the schema. + """ + return model.model_json_schema(by_alias=False, mode="serialization", schema_generator=_MarkUnknown) + + +class _MarkUnknown(GenerateJsonSchema): + """Mark a type pydantic can't describe, rather than failing the schema. + + An arbitrary class with no serializer, or a serializer without a + ``return_type``, has no JSON schema. Pydantic would fail the whole model's + schema for one such field; this marks that field and carries on. A default + that can't be serialized is left out of the schema without a warning: the + rules don't read defaults. + """ + + ignored_warning_kinds: set[JsonSchemaWarningKind] = {"skipped-choice", "non-serializable-default"} # noqa: RUF012 + + def handle_invalid_for_json_schema( + self, + schema: core_schema.CoreSchema + | core_schema.ModelField + | core_schema.DataclassField + | core_schema.TypedDictField + | core_schema.ComputedField, + error_info: str, + ) -> JsonSchemaValue: + return {_UNKNOWN: True} + + +def resolve_refs(schema: JsonSchemaValue, defs: dict[str, JsonSchemaValue]) -> JsonSchemaValue: + """Return a schema with its ``$ref`` replaced by the definition. + + Pydantic puts an Enum or a model under ``$defs`` and refers to it. A union's + arms and an array's items are resolved too, which is all the rules read. A + definition is returned as it is, without resolving inside it, so a model + that refers to itself can't loop. + """ + if "$ref" in schema: + return defs[schema["$ref"].removeprefix("#/$defs/")] + resolved = dict(schema) + if "anyOf" in schema: + resolved["anyOf"] = [resolve_refs(arm, defs) for arm in schema["anyOf"]] + if "items" in schema: + resolved["items"] = resolve_refs(schema["items"], defs) + if "prefixItems" in schema: + resolved["prefixItems"] = [resolve_refs(item, defs) for item in schema["prefixItems"]] + return resolved + + +def has_unknown_schema(schema: JsonSchemaValue) -> bool: + """Return whether a schema, or a union arm or item in it, is unknown.""" + if _UNKNOWN in schema: + return True + parts = [*schema.get("anyOf", ()), *schema.get("prefixItems", ())] + if "items" in schema: + parts.append(schema["items"]) + return any(has_unknown_schema(part) for part in parts) + + +def is_plain_schema(schema: JsonSchemaValue) -> bool: + """Return whether a value with this schema dumps to one plain value. + + That's a string, number, integer or boolean, an ``enum`` or ``const`` of + those, a union of them, or no constraint at all, as for ``Any``. A union's + ``null`` arm is skipped: ``None`` is left out of the request, and a path + parameter can't be ``None``. + """ + if "anyOf" in schema: + return all(is_plain_schema(arm) for arm in schema["anyOf"] if arm.get("type") != "null") + if "type" in schema: + return schema["type"] in _PLAIN_SCHEMA_TYPES + if "enum" in schema or "const" in schema: + values = schema.get("enum", [schema.get("const")]) + return all(isinstance(value, str | int | float | bool) for value in values) + # A model resolves to an object schema, caught above; anything else left is + # unconstrained, as Any is. + return True + + +def is_plain_or_list_schema(schema: JsonSchemaValue) -> bool: + """Return whether each arm dumps to a plain value or a list of them. + + A union's ``null`` arm is skipped, as ``None`` is left out. + """ + arms = [arm for arm in schema.get("anyOf", [schema]) if arm.get("type") != "null"] + return all(is_plain_schema(arm) or _is_plain_list_schema(arm) for arm in arms) + + +def _is_plain_list_schema(schema: JsonSchemaValue) -> bool: + """Return whether the schema is an array of plain values. + + A list, set or ``tuple[str, ...]`` has ``items``; a fixed-length tuple has + ``prefixItems``. + """ + if schema.get("type") != "array": + return False + items = [*schema.get("prefixItems", ())] + if "items" in schema: + items.append(schema["items"]) + return all(is_plain_schema(item) for item in items) + + +# --- Keys --------------------------------------------------------------------- +def spread_keys(field_info: FieldInfo, argument: HttpxArgument) -> tuple[tuple[str, str], ...] | None: + """Return each field of a spread parameter's type, with its key. + + The pairs are ``(attribute, key)``, computed fields included. A mapping, or + a model with its own model serializer, has its keys only at the call: + ``None``, and what it dumps is sent under its own keys. + """ + cls = cast("type[Any]", class_of(union_arms(field_info.annotation)[0])) + if issubclass(cls, Mapping) or has_model_serializer(cls): + return None + return tuple((attribute, sent_key(attribute, alias, argument)) for attribute, (_, alias) in fields_of(cls).items()) + + +def is_spread(field_info: FieldInfo, argument: HttpxArgument) -> bool: + """Return whether a parameter is spread, a key per field of its type. + + That's a lone model, dataclass or mapping marked ``Query()``, ``Header()`` + or ``Form()``, unless it's a form's JSON part. The last ``Send`` wins. + """ + send = next((meta for meta in reversed(field_info.metadata) if isinstance(meta, Send)), Send()) + if argument not in _SPREAD_ARGUMENTS or send.json_part: + return False + arms = union_arms(field_info.annotation) + return len(arms) == 1 and has_fields(arms[0]) + + +def sent_key(name: str, alias: str | None, argument: HttpxArgument) -> str: + """Return the key a value is sent under: its alias, or else its name. + + A header name's ``_`` is sent as ``-``, as FastAPI's ``Header()`` does, + since Python names can't have ``-``. An alias is sent as written. + """ + if alias: + return alias + return name.replace("_", "-") if argument is HttpxArgument.HEADERS else name diff --git a/src/clientx/_tools.py b/src/clientx/_tools.py index 9e380ba..b8fd38b 100644 --- a/src/clientx/_tools.py +++ b/src/clientx/_tools.py @@ -47,9 +47,11 @@ class is left out: it's the same endpoint. Pydantic's ``title`` on each property is left out, and a model or ``type`` alias is written in place rather than behind a ``$ref``, unless it refers to itself. -- Calls: a model's arguments are validated as Pydantic validates a call, - leniently, so ``"7"`` fits an ``int``. Only the arguments the model gave are - passed, so a default stays a default, as ``Send(exclude_unset=True)`` and a +- Calls: a model's arguments are validated leniently, so ``"7"`` fits an + ``int``, with a pydantic model of the parameters: an endpoint's request + model, or a ``@tool`` method's own, built by the same ``arguments_model``. + An argument the method doesn't have is rejected. Only the arguments the + model gave are passed, so a default stays a default, as ``exclude_if`` and a JSON field's ``None`` need. A model's fields are taken, and returned, by name, as the schemas list them. The result is JSON-ready data. - Hints: each is worked out on its own, as the endpoint's ``tool_options=`` @@ -71,15 +73,15 @@ class is left out: it's the same endpoint. from contextlib import contextmanager from dataclasses import dataclass, field from types import NoneType -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast import httpx2 -from pydantic import PydanticSchemaGenerationError, TypeAdapter, ValidationError +from pydantic import BaseModel, PydanticSchemaGenerationError, TypeAdapter, ValidationError from pydantic.errors import PydanticInvalidForJsonSchema from clientx._registry import endpoint_for, register_tool_method, tool_method_for +from clientx._request_model import arguments_model, describe_errors from clientx._signature import NO_VALUE, ParameterKind, inspect_definition -from clientx._validation import arguments_adapter, describe_errors from clientx.exceptions import ArgumentError, DefinitionError, ToolError if TYPE_CHECKING: @@ -231,7 +233,7 @@ class _Call: """What a tool needs to call its endpoint or method and report on it.""" function: Callable[..., Any] - adapter: TypeAdapter[dict[str, Any]] + validate: Callable[[dict[str, Any]], dict[str, Any]] # The arguments given, validated, by parameter name. output: TypeAdapter[Any] | None positional: tuple[ParameterInfo, ...] request: str | None # An endpoint's method and path template, for messages: "POST /users". @@ -247,7 +249,7 @@ def arguments(self, name: str, arguments: Mapping[str, Any] | None) -> tuple[lis """ given = dict(arguments or {}) try: - validated = self.adapter.validate_python(given, by_alias=False, by_name=True) + validated = self.validate(given) except ValidationError as error: raise ToolError( f"The arguments don't fit {name}: {describe_errors(error, values=True)}. Nothing was sent.", tool=name @@ -343,8 +345,13 @@ def _tool( signature = definition.signature parameters = signature.parameters[1:] returns = signature.returns - adapter = arguments_adapter(parameters) - input_schema = _compact(adapter.json_schema(by_alias=False)) + if isinstance(definition, ToolMethod): + model = definition.arguments_model + else: + # Each endpoint on a client class has its request model. + model = cast("type[BaseModel]", definition.request_model) + validate = _model_validator(model) + input_schema = _compact(model.model_json_schema(by_alias=False)) returns_nothing = returns.base_type is None or returns.base_type is NoneType output = None if returns_nothing else TypeAdapter[Any](returns.annotation) output_schema = None if output is None else _compact(output.json_schema(mode="serialization", by_alias=False)) @@ -368,10 +375,23 @@ def _tool( tags=tuple(definition.tags), deprecated=deprecated, is_async=signature.is_async, - _call=_Call(function, adapter, output, positional, request), + _call=_Call(function, validate, output, positional, request), ) +def _model_validator(model: type[BaseModel]) -> Callable[[dict[str, Any]], dict[str, Any]]: + """Return a validator of a model's arguments with the arguments model. + + A model's fields are read by name too, as the schema lists them. + """ + + def validate(given: dict[str, Any]) -> dict[str, Any]: + validated = model.model_validate(given, by_alias=False, by_name=True) + return {name: getattr(validated, name) for name in type(validated).model_fields} + + return validate + + # --- Tool methods ------------------------------------------------------------- @dataclass(slots=True) class ToolMethod: @@ -385,6 +405,8 @@ class ToolMethod: idempotent: ``@tool``'s ``idempotent`` hint. tags: ``@tool``'s tags, each once. A resource puts its own in front when its class is defined. + arguments_model: The pydantic model of the parameters, which validates + a model's arguments, set once ``@tool``'s checks pass. """ signature: SignatureInfo @@ -392,6 +414,7 @@ class ToolMethod: destructive: bool idempotent: bool tags: list[str] + arguments_model: type[BaseModel] = field(init=False) def tool[F: Callable[..., Any]]( @@ -420,8 +443,9 @@ def tool[F: Callable[..., Any]]( Raises: DefinitionError: If the method is an endpoint, has a private name, has no docstring or no return annotation, returns ``bytes``, has no - positional first parameter, takes ``*args`` or ``**kwargs``, or is - read-only and destructive. + positional first parameter, takes ``*args`` or ``**kwargs``, is + read-only and destructive, or has a parameter name a pydantic model + can't hold, such as ``json``. """ def decorator(func: F) -> F: @@ -438,6 +462,11 @@ def decorator(func: F) -> F: tags=list(dict.fromkeys(tags or ())), ) _check_tool_method(tool_method) + signature = tool_method.signature + try: + tool_method.arguments_model = arguments_model(signature.qualname, signature.parameters[1:]) + except DefinitionError as error: + raise DefinitionError(f"Tool '{signature.qualname}': {error}") from error register_tool_method(func, tool_method) return func diff --git a/src/clientx/_types.py b/src/clientx/_types.py index b23862b..cbc3392 100644 --- a/src/clientx/_types.py +++ b/src/clientx/_types.py @@ -54,9 +54,10 @@ class Send: parameter's outermost ``Annotated``, next to the helper, as in ``Annotated[list[str], Json(), Send(embed=True)]``. - Each option applies to some parts of the request only, and one where it - can't apply raises ``DefinitionError`` when the class is defined, as does a - ``Send`` on a path parameter, nested inside the type, or on a model's field. + A ``Send`` on a path parameter, nested inside the type, or on a model's + field raises ``DefinitionError`` when the class is defined. To leave out a + value, use pydantic's ``exclude_if`` on the helper, as in + ``Json(exclude_if=lambda v: v is None)``. With several ``Send`` in one ``Annotated``, the last one wins whole, as the last helper does, so one on the parameter replaces one from a ``type`` @@ -69,18 +70,6 @@ class Send: ``{"ids": [...]}`` rather than ``[...]``. Like FastAPI's ``Body(embed=True)``. A parameter that's already keyed, a plain value or one of several ``Json()`` parameters, is sent the same. - exclude_unset: Leave out what the caller didn't set, so the server's - defaults apply: the parameter itself, when the caller didn't pass - it, and a model's fields that weren't set when it was made (a - pydantic model's only: a dataclass doesn't record them). For JSON, - the query string, headers and form. - exclude_none: Leave out the fields of a pydantic model or pydantic - dataclass that are ``None``. For JSON, and a form's JSON part - (``json_part``): the query string, headers and a plain form leave - out ``None`` already. - exclude_defaults: Leave out the fields of a pydantic model or pydantic - dataclass that equal their defaults. For JSON, and for a model - spread into the query string, headers or form. json_part: Send a ``Form()`` parameter's value as its own part of a multipart form, as JSON with the ``application/json`` content type, as some APIs take a JSON document next to files. The value @@ -89,9 +78,6 @@ class Send: """ embed: bool | None = None - exclude_unset: bool | None = None - exclude_none: bool | None = None - exclude_defaults: bool | None = None json_part: bool | None = None diff --git a/src/clientx/_validation.py b/src/clientx/_validation.py deleted file mode 100644 index 627fa8c..0000000 --- a/src/clientx/_validation.py +++ /dev/null @@ -1,131 +0,0 @@ -"""Validate an endpoint's arguments against its parameters' annotations. - -One validator covers all of an endpoint's parameters: Pydantic validates a call -to a stand-in function with the same parameters, so each annotation applies in -full, a helper's constraints (``Query(ge=1)``) included. Arguments are matched -by parameter name, never by a helper's alias, which is the name sent to the -API. ``clientx.tools`` validates a model's arguments with it. - -A client created with ``validate_arguments=True`` checks each call's arguments -before anything is sent: - -- Only the arguments the caller passed, not the defaults filled in, so - ``page: int = None`` doesn't fail when ``page`` is left out. -- Strictly, as a type checker would: ``"7"`` doesn't fit an ``int``. A model - instance isn't validated again, as is Pydantic's default. -- The request is built from the caller's values, not from what Pydantic - returns, so validation never changes what's sent. -- A parameter whose annotation 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 a class Pydantic doesn't know. - A stream's items are never checked: Pydantic validates an ``Iterable`` - lazily, and what it returns is thrown away. -- An endpoint's validator is built on its first checked call, so a client that - doesn't check doesn't pay for it. -- A failure raises ``ArgumentError`` for the first parameter that doesn't fit, - with every problem in its message and Pydantic's ``ValidationError`` as its - cause. -""" - -from __future__ import annotations - -import inspect -from collections.abc import Mapping, Sequence -from dataclasses import replace -from typing import TYPE_CHECKING, Any, cast - -from pydantic import ConfigDict, PydanticSchemaGenerationError, TypeAdapter, ValidationError - -from clientx.exceptions import ArgumentError - -if TYPE_CHECKING: - from clientx._signature import ParameterInfo - - -# --- Validators --------------------------------------------------------------- -_BY_NAME = ConfigDict(validate_by_name=True, validate_by_alias=False) - - -def arguments_adapter(parameters: Sequence[ParameterInfo]) -> TypeAdapter[dict[str, Any]]: - """Return a validator of arguments, by name, for these parameters. - - It validates a call to a stand-in with these parameters, all keyword-only - so a mapping fills them, and returns the arguments, defaults included: the - endpoint itself isn't called, so validating its arguments can't send a - request. - - Raises: - PydanticSchemaGenerationError: If Pydantic can't build a schema for a - parameter's annotation. - """ - - def arguments(**values: Any) -> dict[str, Any]: - return values - - arguments.__signature__ = inspect.Signature( # pyright: ignore[reportFunctionMemberAccess] - [ - inspect.Parameter(p.name, inspect.Parameter.KEYWORD_ONLY, default=p.default, annotation=p.annotation) - for p in parameters - ] - ) - arguments.__annotations__ = {p.name: p.annotation for p in parameters} - # Pydantic validates a call to a function, which its types don't allow. - return TypeAdapter[dict[str, Any]](cast("Any", arguments), config=_BY_NAME) - - -def build_arguments_validator(parameters: Sequence[ParameterInfo]) -> TypeAdapter[dict[str, Any]]: - """Return the validator ``check_arguments`` takes, for these parameters. - - A parameter whose annotation Pydantic can't validate, such as ``BinaryIO``, - is validated as ``Any``, so the others are still checked. - """ - try: - return arguments_adapter(parameters) - except PydanticSchemaGenerationError: - return arguments_adapter([p if _can_validate(p.annotation) else replace(p, annotation=Any) for p in parameters]) - - -def _can_validate(annotation: Any) -> bool: - try: - TypeAdapter[Any](annotation) - except PydanticSchemaGenerationError: - return False - return True - - -# --- Checking a call ---------------------------------------------------------- -def check_arguments(validator: TypeAdapter[dict[str, Any]], arguments: Mapping[str, Any], endpoint: str) -> None: - """Raise ``ArgumentError`` unless ``arguments`` fit, strictly. - - ``endpoint`` is the endpoint's qualified name, for the message. - """ - try: - validator.validate_python(dict(arguments), strict=True) - except ValidationError as error: - parameter = str(error.errors()[0]["loc"][0]) - raise ArgumentError( - f"The arguments to '{endpoint}' don't fit their annotations: {describe_errors(error, values=True)}. " - "No request was sent.", - parameter=parameter, - ) from error - - -# --- Error messages ----------------------------------------------------------- -def describe_errors(error: ValidationError, *, values: bool) -> str: - """Return each of Pydantic's errors as ``where: what``, without its URL. - - With ``values``, a value that's there but doesn't fit is shown too, short: - it's the caller's own argument. A response's values aren't. - """ - problems: list[str] = [] - for problem in error.errors(include_url=False, include_context=False): - where = ".".join(str(part) for part in problem["loc"]) or "the arguments" - # A missing argument is reported as keyword-only, as the stand-in's are. - if problem["type"].startswith("missing"): - problems.append(f"{where}: is required") - continue - text = f"{where}: {problem['msg']}" - if values: - text += f" (got {problem['input']!r:.80})" - problems.append(text) - return "; ".join(problems) diff --git a/test/test_bodies.py b/test/test_bodies.py index fdb8f9e..c0ca26a 100644 --- a/test/test_bodies.py +++ b/test/test_bodies.py @@ -8,11 +8,11 @@ import pathlib import re from collections.abc import AsyncIterator, Callable, Iterator -from typing import Annotated, Any +from typing import Annotated, Any, BinaryIO import httpx2 import pytest -from pydantic import BaseModel, Field, RootModel +from pydantic import BaseModel, Field, RootModel, SerializeAsAny, SkipValidation from pydantic.dataclasses import dataclass as pydantic_dataclass from clientx import ArgumentError, AsyncClientX, Body, ClientX, DefinitionError, File, Form, Json, Query, Send, method @@ -73,12 +73,21 @@ def create(self, user: Annotated[NewUser, Json()]) -> None: ... } -def test_a_model_is_sent_by_its_own_type(mock_transport: MockTransport) -> None: - # A subclass keeps its extra fields, and a field the caller didn't set is - # sent with its default. +@pytest.mark.parametrize( + ("annotation", "level"), + [ + pytest.param(Annotated[NewUser, Json()], {}, id="annotated type"), + pytest.param(Annotated[SerializeAsAny[NewUser], Json()], {"level": 9}, id="SerializeAsAny"), + ], +) +def test_a_model_is_sent_as_its_annotated_type( + annotation: Any, level: dict[str, int], mock_transport: MockTransport +) -> None: + # A subclass's extra fields are dropped, as pydantic does, unless the type + # is SerializeAsAny. A field the caller didn't set is sent with its default. class API(ClientX): @method.post("/users") - def create(self, user: Annotated[NewUser, Json()]) -> None: ... + def create(self, user: annotation) -> None: ... # pyright: ignore[reportInvalidTypeForm] sent: list[httpx2.Request] = [] API(BASE_URL, transport=mock_transport(sent)).create(Admin(name="Root", emailAddress="r@example.com", level=9)) @@ -86,7 +95,7 @@ def create(self, user: Annotated[NewUser, Json()]) -> None: ... "name": "Root", "emailAddress": "r@example.com", "joined": None, - "level": 9, + **level, } @@ -240,18 +249,6 @@ def act(self, ids: Annotated[Embedded[list[str]], Send(embed=False)]) -> None: . @pytest.mark.parametrize( ("path", "annotation", "message"), [ - pytest.param( - "/items", - Annotated[int, Query(), Send(embed=True)], - "has Send(embed=...), which applies only to a Json() parameter, but it's marked Query()", - id="query parameter", - ), - pytest.param( - "/items", - Annotated[int, Query(), Send(embed=False)], - "has Send(embed=...)", - id="embed=False counts too", - ), pytest.param( "/items/{p}", Annotated[int, Send(embed=True)], @@ -319,7 +316,9 @@ def login( def test_files_with_form_fields_are_sent_as_multipart(mock_transport: MockTransport) -> None: class API(ClientX): @method.post("/upload") - def upload(self, file: Annotated[Any, File(alias="attachment")], title: Annotated[str, Form()]) -> None: ... + def upload( + self, file: Annotated[Any, File(alias="attachment"), SkipValidation], title: Annotated[str, Form()] + ) -> None: ... sent: list[httpx2.Request] = [] API(BASE_URL, transport=mock_transport(sent)).upload(("a.txt", b"hello", "text/plain"), title="T") @@ -405,60 +404,29 @@ class Opaque: pass -@pytest.mark.parametrize( - ("annotation", "value", "body"), - [ - pytest.param( - Annotated[Profile, Json(), Send(exclude_defaults=True)], - Profile(name="sam", nickname="s"), - {"nickname": "s"}, - id="exclude_defaults", - ), - pytest.param( - Annotated[list[Profile], Json(), Send(exclude_unset=True)], - [Profile(name="ana")], - [{"name": "ana"}], - id="nested in a list", - ), - pytest.param( - Annotated[Window, Json(), Send(exclude_none=True)], Window(start=3), {"start": 3}, id="pydantic dataclass" - ), - ], -) -def test_send_dump_options_shape_the_json( - annotation: Any, value: object, body: object, mock_transport: MockTransport -) -> None: +def test_a_default_factory_runs_when_the_argument_is_left_out(mock_transport: MockTransport) -> None: + # = None marks it optional for type checkers; a None passed is still null. class API(ClientX): @method.post("/items") - def create(self, p: annotation) -> None: ... # pyright: ignore[reportInvalidTypeForm] - - sent: list[httpx2.Request] = [] - API(BASE_URL, transport=mock_transport(sent)).create(value) - assert json.loads(only_request(sent).content) == body - - -DEFAULT_PROFILE = Profile() - - -def test_send_exclude_unset_leaves_out_a_lone_body_not_passed(mock_transport: MockTransport) -> None: - # A PATCH that sends nothing unless asked, and then only the fields set. - class API(ClientX): - @method.patch("/me") - def update(self, profile: Annotated[Profile, Json(), Send(exclude_unset=True)] = DEFAULT_PROFILE) -> None: ... + def create( + self, tags: Annotated[list[str] | None, Json(default_factory=lambda: ["new"]), Send(embed=True)] = None + ) -> None: ... sent: list[httpx2.Request] = [] api = API(BASE_URL, transport=mock_transport(sent)) - api.update() - api.update(Profile(nickname="s")) - assert [request.content for request in sent] == [b"", b'{"nickname":"s"}'] + api.create() + api.create(tags=None) + assert [json.loads(request.content) for request in sent] == [{"tags": ["new"]}, {"tags": None}] -def test_exclude_none_on_a_json_field_leaves_out_an_explicit_none(mock_transport: MockTransport) -> None: +def test_exclude_if_on_a_helper_leaves_out_a_value(mock_transport: MockTransport) -> None: + # pydantic's exclude_if, here for a None passed explicitly, which is + # otherwise sent as null. class API(ClientX): @method.patch("/me") def update( self, - profile: Annotated[Profile | None, Json(), Send(exclude_none=True)] = None, + profile: Annotated[Profile | None, Json(exclude_if=lambda v: v is None)] = None, bio: Annotated[str | None, Json()] = None, ) -> None: ... @@ -467,31 +435,6 @@ def update( assert json.loads(only_request(sent).content) == {"bio": "x"} -@pytest.mark.parametrize( - ("annotation", "message"), - [ - pytest.param( - Annotated[StdWindow, Json(), Send(exclude_none=True)], - "leaves out fields of a pydantic model or pydantic dataclass (pydantic doesn't apply it to a stdlib " - "dataclass", - id="stdlib dataclass", - ), - pytest.param(Annotated[str, Json(), Send(exclude_defaults=True)], "but its type has none", id="plain value"), - pytest.param( - Annotated[NewUser, Form(), Send(exclude_none=True)], - "but a Form() field leaves out None already. It applies only to a JSON part", - id="exclude_none on a plain form field", - ), - ], -) -def test_a_dump_option_where_it_cant_apply_fails(annotation: Any, message: str) -> None: - with pytest.raises(DefinitionError, match=re.escape(message)): - - class API(ClientX): - @method.post("/items") - def create(self, p: annotation) -> None: ... # pyright: ignore[reportInvalidTypeForm] - - def test_a_json_value_pydantic_cant_serialize_raises_before_sending(mock_transport: MockTransport) -> None: class API(ClientX): @method.post("/items") @@ -538,6 +481,22 @@ def create(self, reading: annotation) -> None: ... # pyright: ignore[reportInva # Files: what a file can be +@pytest.mark.parametrize( + ("annotation", "helper"), + [ + pytest.param(Annotated[BinaryIO, File()], "File()", id="a binary file"), + pytest.param(Annotated[Iterator[bytes], Body()], "Body()", id="a stream"), + ], +) +def test_a_file_or_stream_without_skip_validation_fails(annotation: Any, helper: str) -> None: + message = f"is marked {helper} with a type that holds a binary file, a stream or Any, so it needs SkipValidation" + with pytest.raises(DefinitionError, match=re.escape(message)): + + class API(ClientX): + @method.post("/upload") + def upload(self, doc: annotation) -> None: ... # pyright: ignore[reportInvalidTypeForm] + + @pytest.mark.parametrize( "annotation", [ @@ -560,7 +519,7 @@ def upload(self, doc: Annotated[annotation, File()]) -> None: ... # pyright: ig @pytest.mark.parametrize( ("annotation", "value", "filename"), [ - pytest.param(io.BytesIO, io.BytesIO(b"%PDF"), "upload", id="BytesIO"), + pytest.param(Annotated[io.BytesIO, SkipValidation], io.BytesIO(b"%PDF"), "upload", id="BytesIO"), pytest.param( tuple[str, bytes, str, dict[str, str]], ("a.pdf", b"%PDF", "application/pdf", {"X-Checksum": "abc"}), @@ -572,6 +531,8 @@ def upload(self, doc: Annotated[annotation, File()]) -> None: ... # pyright: ig def test_file_values_that_fit_are_sent( annotation: Any, value: object, filename: str, mock_transport: MockTransport ) -> None: + # A file tuple of text and bytes, its headers dict included, needs no + # SkipValidation. class API(ClientX): @method.post("/upload") def upload(self, doc: Annotated[annotation, File()]) -> None: ... # pyright: ignore[reportInvalidTypeForm] @@ -583,6 +544,8 @@ def upload(self, doc: Annotated[annotation, File()]) -> None: ... # pyright: ig def test_a_list_of_files_repeats_the_field(mock_transport: MockTransport) -> None: # A None in the list is left out, and another File() can share the field. + # File tuples of text and bytes are validated, so they need no + # SkipValidation. class API(ClientX): @method.post("/upload") def upload( @@ -615,13 +578,13 @@ def test_a_raw_body_that_isnt_text_bytes_or_a_stream_fails(annotation: Any) -> N class API(ClientX): @method.put("/blobs") - def upload(self, data: Annotated[annotation, Body()]) -> None: ... # pyright: ignore[reportInvalidTypeForm] + def upload(self, data: Annotated[annotation, Body(), SkipValidation]) -> None: ... # pyright: ignore[reportInvalidTypeForm] def test_a_sync_client_streams_an_iterable_of_bytes(mock_transport: MockTransport) -> None: class API(ClientX): @method.put("/blobs") - def upload(self, data: Annotated[Iterator[bytes], Body()]) -> None: ... + def upload(self, data: Annotated[Iterator[bytes], Body(), SkipValidation]) -> None: ... sent: list[httpx2.Request] = [] API(BASE_URL, transport=mock_transport(sent)).upload(iter([b"a", b"b"])) @@ -633,7 +596,7 @@ def test_an_async_stream_on_a_sync_client_fails() -> None: class API(ClientX): @method.put("/blobs") - def upload(self, data: Annotated[AsyncIterator[bytes], Body()]) -> None: ... + def upload(self, data: Annotated[AsyncIterator[bytes], Body(), SkipValidation]) -> None: ... def test_a_sync_stream_on_an_async_client_fails() -> None: @@ -642,7 +605,7 @@ def test_a_sync_stream_on_an_async_client_fails() -> None: class API(AsyncClientX): @method.put("/blobs") - async def upload(self, data: Annotated[list[bytes], Body()]) -> None: ... + async def upload(self, data: Annotated[list[bytes], Body(), SkipValidation]) -> None: ... @pytest.mark.anyio @@ -653,7 +616,7 @@ async def chunks() -> AsyncIterator[bytes]: class API(AsyncClientX): @method.put("/blobs") - async def upload(self, data: Annotated[AsyncIterator[bytes], Body()]) -> None: ... + async def upload(self, data: Annotated[AsyncIterator[bytes], Body(), SkipValidation]) -> None: ... sent: list[httpx2.Request] = [] await API(BASE_URL, transport=mock_transport(sent)).upload(chunks()) @@ -665,15 +628,16 @@ class API(ClientX): @method.post("/messages") def create( self, - message: Annotated[NewUser, Form(alias="payload_json"), Send(json_part=True, exclude_none=True)], + message: Annotated[NewUser, Form(alias="payload_json"), Send(json_part=True)], doc: Annotated[bytes, File()], ) -> None: ... sent: list[httpx2.Request] = [] API(BASE_URL, transport=mock_transport(sent)).create(NewUser(name="Á", emailAddress="a@x"), b"%PDF") request = only_request(sent) - # As httpx2 encodes a JSON body: compact, with text as it is. exclude_none - # leaves out "joined". - part = 'name="payload_json"\r\nContent-Type: application/json\r\n\r\n{"name":"Á","emailAddress":"a@x"}' + # As httpx2 encodes a JSON body: compact, with text as it is. + part = ( + 'name="payload_json"\r\nContent-Type: application/json\r\n\r\n{"name":"Á","emailAddress":"a@x","joined":null}' + ) assert content_type(request) == "multipart/form-data" assert part in request.read().decode() diff --git a/test/test_docs.py b/test/test_docs.py index 48b3f49..9c03ade 100644 --- a/test/test_docs.py +++ b/test/test_docs.py @@ -26,7 +26,6 @@ import pytest from clientx import Send -from clientx._planner import _SPECS # pyright: ignore[reportPrivateUsage] ROOT = Path(__file__).parent.parent SAMPLES = sorted((ROOT / "docs_src").rglob("*.py")) @@ -69,17 +68,17 @@ async def astop(*_: object) -> NoReturn: runpy.run_path(str(sample), run_name="docs_sample") +# The helper each Send option applies to; it's ignored on any other. +SEND_OPTION_HELPERS = {"embed": {"Json()"}, "json_part": {"Form()"}} + + def test_the_send_table_lists_the_helpers_each_option_works_with() -> None: - # Each spec's send_options decide where an option works; the table must say - # the same, for every Send option. + # Every Send option is in the table, with the helper it applies to. page = (ROOT / "docs/requests.md").read_text() table = page[page.index("| Option | Works with | Effect |") :].split("\n\n", 1)[0] documented: dict[str, set[str]] = {} for row in table.splitlines()[2:]: option, works_with = row.split("|")[1:3] documented[option.strip().strip("`").split("=")[0]] = set(re.findall(r"`(\w+\(\))`", works_with)) - allowed = { - option.name: {spec.helper for spec in _SPECS.values() if option.name in spec.send_options} - for option in fields(Send) - } - assert documented == allowed + assert {option.name for option in fields(Send)} == SEND_OPTION_HELPERS.keys() + assert documented == SEND_OPTION_HELPERS diff --git a/test/test_endpoints.py b/test/test_endpoints.py index 9708b03..4408d43 100644 --- a/test/test_endpoints.py +++ b/test/test_endpoints.py @@ -8,8 +8,9 @@ import httpx2 import pytest +from pydantic import Secret, SecretStr -from clientx import AsyncClientX, ClientX, DefinitionError, Query, Timeout, method +from clientx import AsyncClientX, ClientX, DefinitionError, Header, Json, Query, Timeout, method type MockTransport = Callable[..., httpx2.MockTransport] @@ -143,3 +144,33 @@ def test_an_annotation_that_names_an_undefined_type_names_the_endpoint() -> None class API(ClientX): @method.get("/items") def items(self, filters: Annotated["Filters", Query()]) -> None: ... # noqa: F821 # pyright: ignore[reportUndefinedVariable] + + +@pytest.mark.parametrize( + "annotation", + [ + pytest.param(Annotated[SecretStr | None, Header()], id="SecretStr in a header"), + pytest.param(Annotated[list[Secret[int]], Json()], id="Secret inside JSON"), + ], +) +def test_a_pydantic_secret_parameter_fails(annotation: Any) -> None: + def call(self: ClientX, key: Any = None) -> None: ... + + call.__annotations__["key"] = annotation + with pytest.raises(DefinitionError, match=r"Parameter 'key' is a pydantic secret.*auth="): + type("API", (ClientX,), {"call": method.post("/items")(call)}) + + +@pytest.mark.parametrize( + ("name", "message"), + [ + pytest.param("_page", "pydantic leaves names starting with _, and model_config, out", id="leading _"), + pytest.param("model_config", "pydantic leaves names starting with _, and model_config, out", id="model_config"), + pytest.param("json", "has the name of a pydantic BaseModel attribute", id="BaseModel attribute"), + ], +) +def test_a_parameter_name_the_request_model_cant_hold_fails(name: str, message: str) -> None: + namespace: dict[str, object] = {"Annotated": Annotated, "Query": Query} + exec(f"def call(self, {name}: Annotated[int, Query()] = 1) -> None: ...", namespace) # noqa: S102 - the name is the case + with pytest.raises(DefinitionError, match=rf"Endpoint '.*call': Parameter '{name}' .*{re.escape(message)}"): + type("API", (ClientX,), {"call": method.get("/items")(namespace["call"])}) # pyright: ignore[reportCallIssue, reportArgumentType] diff --git a/test/test_paths.py b/test/test_paths.py index f1a7b91..43afff5 100644 --- a/test/test_paths.py +++ b/test/test_paths.py @@ -181,12 +181,21 @@ def fetch(self, item: int) -> None: ... assert "Endpoint 'test_a_malformed_template_fails_when_the_class_is_defined." in str(caught.value) -def test_a_placeholder_needs_a_parameter() -> None: - with pytest.raises(DefinitionError, match=re.escape("has the placeholder {user_id}, but no parameter is named")): +@pytest.mark.parametrize( + ("path", "message"), + [ + pytest.param("/users/{user_id}", "has the placeholder {user_id}, but no parameter is named", id="one"), + pytest.param( + "/{owner}/{path:path}", "has the placeholders {owner}, {path:path}, but no parameters", id="several" + ), + ], +) +def test_a_placeholder_needs_a_parameter(path: str, message: str) -> None: + with pytest.raises(DefinitionError, match=re.escape(message)): class API(ClientX): - @method.get("/users/{user_id}") - def fetch(self, item: int) -> None: ... + @method.get(path) + def fetch(self, item: Annotated[int, Query()]) -> None: ... def test_the_first_parameter_isnt_a_placeholders_parameter() -> None: @@ -256,9 +265,16 @@ class API(ClientX): def user(self, user_id: Annotated[int, Url(alias="userId")]) -> None: ... -@pytest.mark.parametrize("annotation", [list[int], Price], ids=["list", "your own class"]) -def test_a_placeholders_parameter_must_be_a_plain_value(annotation: Any) -> None: - message = "so it must be a plain value. A plain value is one of str, int, float, bool, Enum" +@pytest.mark.parametrize( + ("annotation", "message"), + [ + pytest.param( + list[int], "so it must be a plain value: one that dumps to a string, number or boolean", id="list" + ), + pytest.param(Price, "has a type ClientX can't tell the dumped form of", id="your own class"), + ], +) +def test_a_placeholders_parameter_must_be_a_plain_value(annotation: Any, message: str) -> None: with pytest.raises(DefinitionError, match=re.escape(message)): class API(ClientX): diff --git a/test/test_query_and_headers.py b/test/test_query_and_headers.py index 7368b6e..4427e54 100644 --- a/test/test_query_and_headers.py +++ b/test/test_query_and_headers.py @@ -2,7 +2,6 @@ import datetime import enum -import inspect import json import re from collections.abc import Callable, Collection, Sequence @@ -12,7 +11,7 @@ import pytest from pydantic import BaseModel, Field, PlainSerializer -from clientx import ArgumentError, ClientX, DefinitionError, Form, Header, Json, Query, Send, method +from clientx import ArgumentError, ClientX, DefinitionError, Form, Header, Json, Query, method type MockTransport = Callable[..., httpx2.MockTransport] @@ -50,6 +49,7 @@ def header_names(request: httpx2.Request) -> list[str]: [ pytest.param("page: int = 1", "page: Annotated[int, Query()]", id="plain value"), pytest.param("filters: Filters", "filters: Annotated[Filters, Json()]", id="model"), + pytest.param("page=1", "page: Annotated[str, Query()]", id="no annotation"), ], ) def test_a_parameter_without_a_helper_fails(parameter: str, example: str) -> None: @@ -246,20 +246,20 @@ def create(self, counts: Annotated[list[Annotated[int, Field(gt=0)]], Json()]) - assert json.loads(only_request(sent).content) == [1, 2] -@pytest.mark.parametrize( - ("path", "annotation"), - [ - ("/items", Annotated[int, Query(default=1)]), - ("/items", Annotated[str, Header(default_factory=str)]), - ], - ids=["Query(default=)", "Header(default_factory=)"], -) -def test_a_default_inside_a_helper_fails(path: str, annotation: Any) -> None: +def test_a_default_inside_a_helper_fails() -> None: with pytest.raises(DefinitionError, match=re.escape("has a default inside its helper")): class API(ClientX): - @method.get(path) - def search(self, p: annotation) -> None: ... # pyright: ignore[reportInvalidTypeForm] + @method.get("/items") + def search(self, p: Annotated[int, Query(default=1)]) -> None: ... + + +def test_a_default_factory_without_a_none_default_fails() -> None: + with pytest.raises(DefinitionError, match=re.escape("has a default_factory in its helper, so its default must be")): + + class API(ClientX): + @method.get("/items") + def search(self, p: Annotated[str, Header(default_factory=str)]) -> None: ... def test_query_with_ellipsis_isnt_a_default(mock_transport: MockTransport) -> None: @@ -287,17 +287,16 @@ def __str__(self) -> str: ("annotation", "message"), [ pytest.param( - Annotated[Price, Query()], - "goes to the query string, which takes a plain value or a collection of them. A plain value is one of " - "str, int, float, bool, Enum, date, datetime, time, UUID, Decimal, bytes, or Any", - id="your own class", + Annotated[Price, Query()], "has a type ClientX can't tell the dumped form of", id="your own class" ), pytest.param( - Annotated[list[str], Header()], "goes to the headers, which take a plain value.", id="list in a header" + Annotated[list[str], Header()], + "goes to the headers, which take a plain value: it must dump to a string, number or boolean,", + id="list in a header", ), pytest.param( Annotated[list[Price], Form()], - "goes to the form, which takes a plain value or a collection of them.", + "has a type ClientX can't tell the dumped form of", id="list of them in a form", ), ], @@ -396,7 +395,7 @@ def search(self, status: Annotated[str, Query()], s: Annotated[str, Header(alias [ pytest.param(str | list[str], "a", "tag=a", id="one value"), pytest.param(str | list[str], ["a", "b"], "tag=a&tag=b", id="a list of them"), - pytest.param(Sequence[str], "python", "tag=python", id="a str for a Sequence[str] is one value"), + pytest.param(str | Sequence[str], "python", "tag=python", id="a str for str | Sequence[str] is one value"), ], ) def test_a_value_or_a_list_of_them_is_decided_at_the_call( @@ -411,13 +410,16 @@ def search(self, tag: Annotated[annotation, Query()]) -> None: ... # pyright: i assert only_request(sent).url.query.decode() == query -def test_a_serializer_in_a_parameters_type_fails() -> None: +def test_a_serializer_in_a_parameters_type_runs(mock_transport: MockTransport) -> None: epoch = Annotated[datetime.datetime, PlainSerializer(lambda d: int(d.timestamp()), return_type=int)] - with pytest.raises(DefinitionError, match=re.escape("has a pydantic serializer in its type")): - class API(ClientX): - @method.get("/items") - def search(self, since: Annotated[epoch, Query()]) -> None: ... # pyright: ignore[reportInvalidTypeForm] + class API(ClientX): + @method.get("/items") + def search(self, since: Annotated[epoch, Query()]) -> None: ... # pyright: ignore[reportInvalidTypeForm] + + sent: list[httpx2.Request] = [] + API(BASE_URL, transport=mock_transport(sent)).search(datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC)) + assert only_request(sent).url.params["since"] == "1767225600" def test_a_value_that_cant_become_text_raises_before_sending(mock_transport: MockTransport) -> None: @@ -470,39 +472,3 @@ def test_a_header_name_that_isnt_ascii_fails() -> None: class API(ClientX): @method.get("/items") def search(self, note: Annotated[str, Header(alias="x-é")]) -> None: ... - - -DEFAULT_FILTERS = Filters(status="open") - - -def test_send_exclude_unset_leaves_out_a_parameter_not_passed(mock_transport: MockTransport) -> None: - # So the server applies its own default; passing the same value sends it. - class API(ClientX): - @method.get("/items") - def search( - self, - page: Annotated[int, Query(), Send(exclude_unset=True)] = 1, - filters: Annotated[Filters, Query(), Send(exclude_unset=True)] = DEFAULT_FILTERS, - ) -> None: ... - - sent: list[httpx2.Request] = [] - api = API(BASE_URL, transport=mock_transport(sent)) - api.search() - api.search(1, DEFAULT_FILTERS) - assert [request.url.query.decode() for request in sent] == ["", "page=1&status=open"] - - -@pytest.mark.parametrize( - ("default", "why"), - [ - pytest.param(inspect.Parameter.empty, "it has no default, so it's always passed", id="no default"), - pytest.param(None, "its default is None, which is left out anyway", id="None default"), - ], -) -def test_send_exclude_unset_with_nothing_to_leave_out_fails(default: object, why: str) -> None: - def search(self: ClientX, page: Annotated[int | None, Query(), Send(exclude_unset=True)]) -> None: ... - - if default is not inspect.Parameter.empty: - search.__defaults__ = (default,) - with pytest.raises(DefinitionError, match=re.escape(f"has Send(exclude_unset=...), but {why}")): - type("API", (ClientX,), {"search": method.get("/items")(search)}) diff --git a/test/test_spreading.py b/test/test_spreading.py index 0ac9256..54ebf96 100644 --- a/test/test_spreading.py +++ b/test/test_spreading.py @@ -9,10 +9,10 @@ import httpx2 import pytest -from pydantic import BaseModel, Field, computed_field, field_serializer, model_serializer +from pydantic import BaseModel, Field, SkipValidation, computed_field, field_serializer, model_serializer from pydantic.dataclasses import dataclass as pydantic_dataclass -from clientx import ClientX, DefinitionError, File, Form, Header, Json, Query, Send, method +from clientx import ArgumentError, ClientX, DefinitionError, File, Form, Header, Json, Query, method type MockTransport = Callable[..., httpx2.MockTransport] @@ -124,7 +124,9 @@ def traced( def test_a_models_fields_become_form_fields(mock_transport: MockTransport) -> None: class API(ClientX): @method.post("/signup") - def signup(self, form: Annotated[Signup, Form()], avatar: Annotated[Any, File()] = None) -> None: ... + def signup( + self, form: Annotated[Signup, Form()], avatar: Annotated[Any, File(), SkipValidation] = None + ) -> None: ... sent: list[httpx2.Request] = [] api = API(BASE_URL, transport=mock_transport(sent)) @@ -168,6 +170,15 @@ class WithList(BaseModel): tags: list[str] +class Opaque: + pass + + +@pydantic_dataclass(config={"arbitrary_types_allowed": True}) +class WithOpaque: + thing: Opaque + + @pytest.mark.parametrize( ("annotation", "message"), [ @@ -182,6 +193,16 @@ class WithList(BaseModel): "so each field of WithList goes to the headers, which take a plain value. Field 'tags' isn't one", id="header field that's a list", ), + pytest.param( + Annotated[dict[str, list[int]], Header()], + "so each item of the mapping goes to the headers, which take a plain value. Its value type isn't one", + id="mapping of lists in headers", + ), + pytest.param( + Annotated[WithOpaque, Query()], + "Field 'thing' of parameter 'p' has a type ClientX can't tell the dumped form of", + id="field of your own class", + ), ], ) def test_each_spread_field_must_fit_its_part(annotation: Any, message: str) -> None: @@ -242,30 +263,14 @@ class API(ClientX): def find(self, status: Annotated[str, Query()], search: Annotated[Search, Query()]) -> None: ... -@pytest.mark.parametrize( - ("send", "query"), - [ - pytest.param(Send(), "status=closed&limit=10", id="every field"), - pytest.param(Send(exclude_unset=True), "status=closed", id="exclude_unset"), - ], -) -def test_send_dump_options_on_a_spread_model(send: Send, query: str, mock_transport: MockTransport) -> None: +def test_a_spread_model_sends_every_field_defaults_included(mock_transport: MockTransport) -> None: class API(ClientX): @method.get("/items") - def find(self, search: Annotated[Search, Query(), send]) -> None: ... + def find(self, search: Annotated[Search, Query()]) -> None: ... sent: list[httpx2.Request] = [] API(BASE_URL, transport=mock_transport(sent)).find(Search(status="closed")) - assert only_request(sent).url.query.decode() == query - - -def test_exclude_none_doesnt_apply_to_a_spread_model() -> None: - message = "has Send(exclude_none=...), which applies only to a Form() or Json() parameter, but it's marked Query()" - with pytest.raises(DefinitionError, match=re.escape(message)): - - class API(ClientX): - @method.get("/items") - def find(self, search: Annotated[Search, Query(), Send(exclude_none=True)]) -> None: ... + assert only_request(sent).url.query.decode() == "status=closed&limit=10" # What a model dumps @@ -313,6 +318,25 @@ def find(self, p: Annotated[annotation, Query()]) -> None: ... # pyright: ignor assert only_request(sent).url.query.decode() == query +class Tags(BaseModel): + names: list[str] = ["a"] + + @model_serializer + def _as_list(self) -> list[str]: + return self.names + + +def test_a_spread_model_that_doesnt_dump_to_a_mapping_raises_before_sending(mock_transport: MockTransport) -> None: + class API(ClientX): + @method.get("/items") + def find(self, tags: Annotated[Tags, Query()]) -> None: ... + + sent: list[httpx2.Request] = [] + with pytest.raises(ArgumentError, match=re.escape("Can't spread 'tags': it dumps to list, not a mapping")): + API(BASE_URL, transport=mock_transport(sent)).find(Tags()) + assert sent == [] + + def test_a_list_in_a_spread_header_is_one_value(mock_transport: MockTransport) -> None: class API(ClientX): @method.get("/items") diff --git a/test/test_tools.py b/test/test_tools.py index 9a9248f..aa60b06 100644 --- a/test/test_tools.py +++ b/test/test_tools.py @@ -3,13 +3,14 @@ import json import re from collections.abc import Callable, Iterator +from enum import Enum from typing import Annotated, Any, BinaryIO import httpx2 import pytest -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, SkipValidation -from clientx import AsyncClientX, ClientX, DefinitionError, File, Header, Json, Query, Resource, Response, Send, method +from clientx import AsyncClientX, ClientX, DefinitionError, File, Header, Json, Query, Resource, Response, method from clientx.tools import Tool, ToolError, ToolOptions, list_tools, tool type MockTransport = Callable[..., httpx2.MockTransport] @@ -17,6 +18,10 @@ BASE_URL = "https://api.example.com" +class Color(Enum): + RED = "red" + + class NewUser(BaseModel): name: str email: str | None = None @@ -82,7 +87,7 @@ def status(self) -> Response: ... def backup(self) -> bytes: ... @method.post("/upload") - def upload(self, file: Annotated[BinaryIO, File()]) -> None: ... + def upload(self, file: Annotated[BinaryIO, File(), SkipValidation]) -> None: ... @method.get("/users") def users(self) -> list[User]: ... @@ -390,6 +395,10 @@ def no_self() -> None: """Do something.""" +def json_named(self: ClientX, json: str) -> None: + """Do something.""" + + def variadic(self: ClientX, *user_ids: int) -> None: """Do something.""" @@ -411,6 +420,9 @@ def _private(self: ClientX) -> None: pytest.param(tool(), binary, "Tool 'binary' can't return bytes", id="bytes"), pytest.param(tool(), no_self, "Tool 'no_self' needs a positional first parameter", id="no self"), pytest.param(tool(), variadic, "Tool 'variadic' can't take `*user_ids`", id="*args"), + pytest.param( + tool(), json_named, "Parameter 'json' has the name of a pydantic BaseModel attribute", id="BaseModel name" + ), pytest.param( tool(read_only=True, destructive=True), documented, @@ -435,6 +447,22 @@ async def fetch(self) -> None: """Fetch something.""" +def test_a_tool_method_gets_its_arguments_as_annotated() -> None: + received: list[Any] = [] + + class API(ClientX): + @tool() + def paint(self, color: Color) -> None: + """Paint something.""" + received.append(color) + + tool_ = {t.name: t for t in list_tools(API(BASE_URL))}["paint"] + tool_.call({"color": "red"}) + assert received == [Color.RED] + with pytest.raises(ToolError, match=re.escape("shade: Extra inputs are not permitted")): + tool_.call({"color": "red", "shade": 1}) + + def test_a_tool_method_with_no_json_form_raises_when_listed() -> None: class API(ClientX): @tool() @@ -454,15 +482,15 @@ def update( /, name: Annotated[str | None, Json()] = None, nickname: Annotated[str | None, Json()] = None, - page: Annotated[int, Query(), Send(exclude_unset=True)] = 1, + page: Annotated[int, Query()] = 1, ) -> User: ... sent: list[httpx2.Request] = [] api = API(BASE_URL, transport=mock_transport(sent, json={"id": 7, "name": "Ada"})) assert tools_of(api)["update"].call({"user_id": "7", "name": "Ada"}) == {"id": 7, "name": "Ada"} - # The positional-only user_id is passed, but nickname isn't sent as null, - # nor page as 1. - assert str(sent[0].url) == "https://api.example.com/users/7" + # The positional-only user_id is passed, and nickname isn't sent as null. + # page wasn't given, so its default is sent. + assert str(sent[0].url) == "https://api.example.com/users/7?page=1" assert json.loads(sent[0].content) == {"name": "Ada"} @@ -478,7 +506,7 @@ def search(self, name: Annotated[str, Query()], limit: Annotated[int, Query(le=1 assert str(caught.value) == ( "The arguments don't fit search: name: is required; " "limit: Input should be less than or equal to 100 (got 500); " - "userId: Unexpected keyword argument (got 1). Nothing was sent." + "userId: Extra inputs are not permitted (got 1). Nothing was sent." ) assert caught.value.tool == "search" assert sent == [] diff --git a/test/test_validation.py b/test/test_validation.py index d3fc8d0..e415772 100644 --- a/test/test_validation.py +++ b/test/test_validation.py @@ -1,12 +1,13 @@ -"""Argument validation: a client created with ``validate_arguments=True``.""" +"""Argument validation: every call is validated with the request model.""" import io +import re from collections.abc import Callable from typing import Annotated, Any, BinaryIO import httpx2 import pytest -from pydantic import BaseModel, ValidationError +from pydantic import BaseModel, SkipValidation, ValidationError from clientx import ArgumentError, AsyncClientX, ClientX, File, Form, Json, Query, method @@ -24,15 +25,9 @@ class API(ClientX): def users(self, page: Annotated[int, Query(ge=1)], size: Annotated[int, Query(le=100)] = 10) -> None: ... -def test_arguments_arent_checked_by_default(mock_transport: MockTransport) -> None: - sent: list[httpx2.Request] = [] - API(BASE_URL, transport=mock_transport(sent)).users(0) - assert sent[0].url.params["page"] == "0" - - def test_arguments_that_dont_fit_raise_before_sending(mock_transport: MockTransport) -> None: sent: list[httpx2.Request] = [] - api = API(BASE_URL, transport=mock_transport(sent), validate_arguments=True) + api = API(BASE_URL, transport=mock_transport(sent)) with pytest.raises(ArgumentError) as caught: api.users(0, size=500) assert caught.value.parameter == "page" @@ -42,10 +37,13 @@ def test_arguments_that_dont_fit_raise_before_sending(mock_transport: MockTransp assert sent == [] -def test_checking_is_strict(mock_transport: MockTransport) -> None: - api = API(BASE_URL, transport=mock_transport(), validate_arguments=True) - with pytest.raises(ArgumentError, match="page: Input should be a valid integer"): - api.users("7") # pyright: ignore[reportArgumentType] +def test_checking_is_lax(mock_transport: MockTransport) -> None: + # Pydantic converts what it can: "7" fits an int. + sent: list[httpx2.Request] = [] + API(BASE_URL, transport=mock_transport(sent)).users("7") # pyright: ignore[reportArgumentType] + assert sent[0].url.params["page"] == "7" + with pytest.raises(ArgumentError, match=re.escape("page: Input should be a valid integer")): + API(BASE_URL, transport=mock_transport()).users("seven") # pyright: ignore[reportArgumentType] def test_defaults_arent_checked(mock_transport: MockTransport) -> None: @@ -54,27 +52,30 @@ class Search(ClientX): def search(self, page: Annotated[int, Query()] = None) -> None: ... # pyright: ignore[reportArgumentType] sent: list[httpx2.Request] = [] - Search(BASE_URL, transport=mock_transport(sent), validate_arguments=True).search() + Search(BASE_URL, transport=mock_transport(sent)).search() assert "page" not in sent[0].url.params -def test_the_callers_values_are_sent_unchanged(mock_transport: MockTransport) -> None: +def test_the_validated_values_are_sent(mock_transport: MockTransport) -> None: + # Lax validation converts 3 to the float 3.0, and that's what's sent. class Users(ClientX): @method.post("/users") def create(self, user: Annotated[User, Json()], ratio: Annotated[float, Query()]) -> None: ... sent: list[httpx2.Request] = [] - Users(BASE_URL, transport=mock_transport(sent), validate_arguments=True).create(User(name="Ada"), 3) - assert (sent[0].url.params["ratio"], sent[0].content) == ("3", b'{"name":"Ada"}') + Users(BASE_URL, transport=mock_transport(sent)).create(User(name="Ada"), 3) + assert (sent[0].url.params["ratio"], sent[0].content) == ("3.0", b'{"name":"Ada"}') -def test_a_parameter_pydantic_cant_validate_isnt_checked(mock_transport: MockTransport) -> None: +def test_a_parameter_with_skip_validation_isnt_checked(mock_transport: MockTransport) -> None: class Files(ClientX): @method.post("/files") - def upload(self, doc: Annotated[BinaryIO, File()], copies: Annotated[int, Form(ge=1)]) -> None: ... + def upload( + self, doc: Annotated[BinaryIO, File(), SkipValidation], copies: Annotated[int, Form(ge=1)] + ) -> None: ... sent: list[httpx2.Request] = [] - api = Files(BASE_URL, transport=mock_transport(sent), validate_arguments=True) + api = Files(BASE_URL, transport=mock_transport(sent)) api.upload(io.BytesIO(b"%PDF"), 1) with pytest.raises(ArgumentError, match="copies"): api.upload(io.BytesIO(b"%PDF"), 0) @@ -87,6 +88,6 @@ class AsyncAPI(AsyncClientX): @method.get("/users") async def users(self, page: Annotated[int, Query(ge=1)]) -> Any: ... - api = AsyncAPI(BASE_URL, transport=mock_transport(), validate_arguments=True) + api = AsyncAPI(BASE_URL, transport=mock_transport()) with pytest.raises(ArgumentError, match="page"): await api.users(0)