From e036c9fa254a0544e1393a4c986b02eb1ca1d405 Mon Sep 17 00:00:00 2001 From: goduni <37146584+goduni@users.noreply.github.com> Date: Sat, 5 Sep 2026 11:30:40 +0000 Subject: [PATCH] docs: add Zensical documentation site and tested examples --- .github/workflows/docs.yml | 35 ++ .gitignore | 5 +- .readthedocs.yaml | 12 + README.md | 4 +- examples/__init__.py | 1 + examples/async_client.py | 51 +++ examples/backends/__init__.py | 1 + examples/backends/aiohttp_async.py | 51 +++ examples/backends/httpx2_async.py | 51 +++ examples/backends/httpx2_sync.py | 50 +++ examples/backends/httpx_async.py | 51 +++ examples/backends/httpx_sync.py | 50 +++ examples/backends/niquests_async.py | 51 +++ examples/backends/niquests_sync.py | 50 +++ examples/backends/requests_sync.py | 50 +++ examples/backends/urllib_sync.py | 50 +++ examples/backends/zapros_async.py | 51 +++ examples/backends/zapros_sync.py | 50 +++ examples/demo_api.py | 28 ++ examples/json_codec.py | 49 +++ examples/middleware_async.py | 71 ++++ examples/middleware_scope.py | 68 ++++ examples/middleware_sync.py | 68 ++++ examples/optional_fields.py | 39 ++ examples/quickstart.py | 53 +++ examples/recipes.py | 111 ++++++ examples/response_errors.py | 107 ++++++ examples/response_metadata.py | 113 ++++++ examples/response_retries.py | 45 +++ examples/response_streaming.py | 56 +++ examples/serialization/__init__.py | 1 + examples/serialization/adaptix.py | 27 ++ examples/serialization/customization.py | 63 ++++ examples/serialization/msgspec.py | 27 ++ examples/serialization/pydantic.py | 27 ++ pyproject.toml | 10 + ruff.toml | 6 + scripts/build_docs.py | 270 ++++++++++++++ scripts/docs_griffe.py | 48 +++ site/getting-started/async.md | 92 +++++ site/getting-started/installation.md | 467 ++++++++++++++++++++++++ site/getting-started/quickstart.md | 127 +++++++ site/guides/errors.md | 173 +++++++++ site/guides/index.md | 60 +++ site/guides/methods.md | 100 +++++ site/guides/middleware.md | 203 ++++++++++ site/guides/responses.md | 148 ++++++++ site/guides/serialization.md | 231 ++++++++++++ site/guides/streaming.md | 117 ++++++ site/index.md | 210 +++++++++++ site/integrations/backends.md | 48 +++ site/project/agent-skills.md | 35 ++ site/project/documentation.md | 144 ++++++++ site/project/releases.md | 44 +++ site/recipes/authentication.md | 30 ++ site/recipes/files.md | 52 +++ site/recipes/partial-updates.md | 106 ++++++ site/recipes/retries.md | 101 +++++ site/reference/clients.md | 36 ++ site/reference/http.md | 18 + site/reference/index.md | 23 ++ site/reference/markers.md | 14 + site/reference/methods.md | 16 + site/reference/middleware.md | 28 ++ site/reference/serializers.md | 24 ++ site/stylesheets/installation.css | 128 +++++++ site/stylesheets/overview.css | 257 +++++++++++++ tests/test_docs_build.py | 368 +++++++++++++++++++ tests/test_docs_examples.py | 437 ++++++++++++++++++++++ tests/test_docs_responses.py | 357 ++++++++++++++++++ tests/test_docs_serialization.py | 116 ++++++ zensical.toml | 105 ++++++ 72 files changed, 6363 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/docs.yml create mode 100644 .readthedocs.yaml create mode 100644 examples/__init__.py create mode 100644 examples/async_client.py create mode 100644 examples/backends/__init__.py create mode 100644 examples/backends/aiohttp_async.py create mode 100644 examples/backends/httpx2_async.py create mode 100644 examples/backends/httpx2_sync.py create mode 100644 examples/backends/httpx_async.py create mode 100644 examples/backends/httpx_sync.py create mode 100644 examples/backends/niquests_async.py create mode 100644 examples/backends/niquests_sync.py create mode 100644 examples/backends/requests_sync.py create mode 100644 examples/backends/urllib_sync.py create mode 100644 examples/backends/zapros_async.py create mode 100644 examples/backends/zapros_sync.py create mode 100644 examples/demo_api.py create mode 100644 examples/json_codec.py create mode 100644 examples/middleware_async.py create mode 100644 examples/middleware_scope.py create mode 100644 examples/middleware_sync.py create mode 100644 examples/optional_fields.py create mode 100644 examples/quickstart.py create mode 100644 examples/recipes.py create mode 100644 examples/response_errors.py create mode 100644 examples/response_metadata.py create mode 100644 examples/response_retries.py create mode 100644 examples/response_streaming.py create mode 100644 examples/serialization/__init__.py create mode 100644 examples/serialization/adaptix.py create mode 100644 examples/serialization/customization.py create mode 100644 examples/serialization/msgspec.py create mode 100644 examples/serialization/pydantic.py create mode 100644 scripts/build_docs.py create mode 100644 scripts/docs_griffe.py create mode 100644 site/getting-started/async.md create mode 100644 site/getting-started/installation.md create mode 100644 site/getting-started/quickstart.md create mode 100644 site/guides/errors.md create mode 100644 site/guides/index.md create mode 100644 site/guides/methods.md create mode 100644 site/guides/middleware.md create mode 100644 site/guides/responses.md create mode 100644 site/guides/serialization.md create mode 100644 site/guides/streaming.md create mode 100644 site/index.md create mode 100644 site/integrations/backends.md create mode 100644 site/project/agent-skills.md create mode 100644 site/project/documentation.md create mode 100644 site/project/releases.md create mode 100644 site/recipes/authentication.md create mode 100644 site/recipes/files.md create mode 100644 site/recipes/partial-updates.md create mode 100644 site/recipes/retries.md create mode 100644 site/reference/clients.md create mode 100644 site/reference/http.md create mode 100644 site/reference/index.md create mode 100644 site/reference/markers.md create mode 100644 site/reference/methods.md create mode 100644 site/reference/middleware.md create mode 100644 site/reference/serializers.md create mode 100644 site/stylesheets/installation.css create mode 100644 site/stylesheets/overview.css create mode 100644 tests/test_docs_build.py create mode 100644 tests/test_docs_examples.py create mode 100644 tests/test_docs_responses.py create mode 100644 tests/test_docs_serialization.py create mode 100644 zensical.toml diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..beab5a1 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,35 @@ +name: Documentation + +on: + push: + branches: [master] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: actions/setup-python@v6 + with: + python-version: "3.12" + - uses: astral-sh/setup-uv@v8.1.0 + with: + version: "0.10.8" + - run: uv sync --group docs --group tests + - run: >- + uv run --group docs --group tests pytest + tests/test_docs_examples.py tests/test_docs_serialization.py tests/test_docs_responses.py tests/test_docs_build.py -q + - run: uv run --group docs python scripts/build_docs.py + env: + DOCS_NOINDEX: ${{ github.event_name == 'pull_request' && '1' || '0' }} + - uses: actions/upload-artifact@v4 + with: + name: documentation + path: .build/docs diff --git a/.gitignore b/.gitignore index 967c13f..2fad8c5 100644 --- a/.gitignore +++ b/.gitignore @@ -143,8 +143,9 @@ venv.bak/ # Rope project settings .ropeproject -# mkdocs documentation -/site +# Generated documentation (sources live in /site) +/.build/ +/graphify-out/ # mypy .mypy_cache/ diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..a46f073 --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,12 @@ +version: 2 + +build: + os: ubuntu-24.04 + tools: + python: "3.12" + commands: + - pip install uv==0.10.8 + - uv sync --group docs + - uv run --group docs python scripts/build_docs.py + - mkdir -p "$READTHEDOCS_OUTPUT/html" + - cp -a .build/docs/. "$READTHEDOCS_OUTPUT/html/" diff --git a/README.md b/README.md index 0a5a6d4..cac0059 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,8 @@ **unihttp** is a modern library for creating declarative API clients. +[Documentation](https://unihttp.readthedocs.io/en/latest/) + ## Table of Contents - [Features](#features) @@ -556,4 +558,4 @@ cp -r /tmp/unihttp/.agents/skills/unihttp ~/.claude/skills/ cp -r /tmp/unihttp/.agents/skills/unihttp-client ~/.claude/skills/ ``` -Restart the agent (or reload its skills) and both skills become available. \ No newline at end of file +Restart the agent (or reload its skills) and both skills become available. diff --git a/examples/__init__.py b/examples/__init__.py new file mode 100644 index 0000000..dba2c84 --- /dev/null +++ b/examples/__init__.py @@ -0,0 +1 @@ +"""Runnable examples and reusable snippets for the unihttp documentation.""" diff --git a/examples/async_client.py b/examples/async_client.py new file mode 100644 index 0000000..1ed79cd --- /dev/null +++ b/examples/async_client.py @@ -0,0 +1,51 @@ +"""A standalone async version of the first-client example.""" + +import asyncio +from dataclasses import dataclass + +import httpx +from unihttp.bind_method import bind_method +from unihttp.clients.httpx import HTTPXAsyncClient +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + + +class UserClient(HTTPXAsyncClient): + get_user = bind_method(GetUser) + + +def mock_api(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, json={"id": int(request.url.path.rsplit("/", 1)[1]), "name": "Ada"} + ) + + +async def main() -> User: + async with UserClient( + base_url="https://api.example.com", + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + session=httpx.AsyncClient(transport=httpx.MockTransport(mock_api)), + ) as client: + user = await client.get_user(user_id=1) + print(user) # User(id=1, name='Ada') + return user + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/backends/__init__.py b/examples/backends/__init__.py new file mode 100644 index 0000000..83e398b --- /dev/null +++ b/examples/backends/__init__.py @@ -0,0 +1 @@ +"""Standalone clients used by the documentation's backend tabs.""" diff --git a/examples/backends/aiohttp_async.py b/examples/backends/aiohttp_async.py new file mode 100644 index 0000000..1ffe56b --- /dev/null +++ b/examples/backends/aiohttp_async.py @@ -0,0 +1,51 @@ +"""aiohttp async quickstart; start examples/demo_api.py first.""" + +import asyncio +from dataclasses import dataclass + +from unihttp.bind_method import bind_method + +# --8<-- [start:backend-import] +from unihttp.clients.aiohttp import AiohttpAsyncClient + +# --8<-- [end:backend-import] +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +# --8<-- [start:models] +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + # --8<-- [end:models] + + +# --8<-- [start:binding] +class UserClient(AiohttpAsyncClient): + get_user = bind_method(GetUser) + # --8<-- [end:binding] + + +async def main(base_url: str = "http://127.0.0.1:8000") -> User: + async with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + ) as client: + user = await client.get_user(user_id=1) + print(user) # User(id=1, name='Ada') + return user + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/backends/httpx2_async.py b/examples/backends/httpx2_async.py new file mode 100644 index 0000000..7e9435f --- /dev/null +++ b/examples/backends/httpx2_async.py @@ -0,0 +1,51 @@ +"""HTTPX2 async quickstart; start examples/demo_api.py first.""" + +import asyncio +from dataclasses import dataclass + +from unihttp.bind_method import bind_method + +# --8<-- [start:backend-import] +from unihttp.clients.httpx2 import HTTPX2AsyncClient + +# --8<-- [end:backend-import] +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +# --8<-- [start:models] +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + # --8<-- [end:models] + + +# --8<-- [start:binding] +class UserClient(HTTPX2AsyncClient): + get_user = bind_method(GetUser) + # --8<-- [end:binding] + + +async def main(base_url: str = "http://127.0.0.1:8000") -> User: + async with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + ) as client: + user = await client.get_user(user_id=1) + print(user) # User(id=1, name='Ada') + return user + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/backends/httpx2_sync.py b/examples/backends/httpx2_sync.py new file mode 100644 index 0000000..51b4ffc --- /dev/null +++ b/examples/backends/httpx2_sync.py @@ -0,0 +1,50 @@ +"""HTTPX2 sync quickstart; start examples/demo_api.py first.""" + +from dataclasses import dataclass + +from unihttp.bind_method import bind_method + +# --8<-- [start:backend-import] +from unihttp.clients.httpx2 import HTTPX2SyncClient + +# --8<-- [end:backend-import] +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +# --8<-- [start:models] +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + # --8<-- [end:models] + + +# --8<-- [start:binding] +class UserClient(HTTPX2SyncClient): + get_user = bind_method(GetUser) + # --8<-- [end:binding] + + +def main(base_url: str = "http://127.0.0.1:8000") -> User: + with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + ) as client: + user = client.get_user(user_id=1) + print(user) # User(id=1, name='Ada') + return user + + +if __name__ == "__main__": + main() diff --git a/examples/backends/httpx_async.py b/examples/backends/httpx_async.py new file mode 100644 index 0000000..03513e0 --- /dev/null +++ b/examples/backends/httpx_async.py @@ -0,0 +1,51 @@ +"""HTTPX async quickstart; start examples/demo_api.py first.""" + +import asyncio +from dataclasses import dataclass + +from unihttp.bind_method import bind_method + +# --8<-- [start:backend-import] +from unihttp.clients.httpx import HTTPXAsyncClient + +# --8<-- [end:backend-import] +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +# --8<-- [start:models] +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + # --8<-- [end:models] + + +# --8<-- [start:binding] +class UserClient(HTTPXAsyncClient): + get_user = bind_method(GetUser) + # --8<-- [end:binding] + + +async def main(base_url: str = "http://127.0.0.1:8000") -> User: + async with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + ) as client: + user = await client.get_user(user_id=1) + print(user) # User(id=1, name='Ada') + return user + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/backends/httpx_sync.py b/examples/backends/httpx_sync.py new file mode 100644 index 0000000..b2ff5d1 --- /dev/null +++ b/examples/backends/httpx_sync.py @@ -0,0 +1,50 @@ +"""HTTPX sync quickstart; start examples/demo_api.py first.""" + +from dataclasses import dataclass + +from unihttp.bind_method import bind_method + +# --8<-- [start:backend-import] +from unihttp.clients.httpx import HTTPXSyncClient + +# --8<-- [end:backend-import] +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +# --8<-- [start:models] +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + # --8<-- [end:models] + + +# --8<-- [start:binding] +class UserClient(HTTPXSyncClient): + get_user = bind_method(GetUser) + # --8<-- [end:binding] + + +def main(base_url: str = "http://127.0.0.1:8000") -> User: + with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + ) as client: + user = client.get_user(user_id=1) + print(user) # User(id=1, name='Ada') + return user + + +if __name__ == "__main__": + main() diff --git a/examples/backends/niquests_async.py b/examples/backends/niquests_async.py new file mode 100644 index 0000000..259b5c9 --- /dev/null +++ b/examples/backends/niquests_async.py @@ -0,0 +1,51 @@ +"""niquests async quickstart; start examples/demo_api.py first.""" + +import asyncio +from dataclasses import dataclass + +from unihttp.bind_method import bind_method + +# --8<-- [start:backend-import] +from unihttp.clients.niquests import NiquestsAsyncClient + +# --8<-- [end:backend-import] +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +# --8<-- [start:models] +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + # --8<-- [end:models] + + +# --8<-- [start:binding] +class UserClient(NiquestsAsyncClient): + get_user = bind_method(GetUser) + # --8<-- [end:binding] + + +async def main(base_url: str = "http://127.0.0.1:8000") -> User: + async with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + ) as client: + user = await client.get_user(user_id=1) + print(user) # User(id=1, name='Ada') + return user + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/backends/niquests_sync.py b/examples/backends/niquests_sync.py new file mode 100644 index 0000000..54464e8 --- /dev/null +++ b/examples/backends/niquests_sync.py @@ -0,0 +1,50 @@ +"""niquests sync quickstart; start examples/demo_api.py first.""" + +from dataclasses import dataclass + +from unihttp.bind_method import bind_method + +# --8<-- [start:backend-import] +from unihttp.clients.niquests import NiquestsSyncClient + +# --8<-- [end:backend-import] +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +# --8<-- [start:models] +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + # --8<-- [end:models] + + +# --8<-- [start:binding] +class UserClient(NiquestsSyncClient): + get_user = bind_method(GetUser) + # --8<-- [end:binding] + + +def main(base_url: str = "http://127.0.0.1:8000") -> User: + with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + ) as client: + user = client.get_user(user_id=1) + print(user) # User(id=1, name='Ada') + return user + + +if __name__ == "__main__": + main() diff --git a/examples/backends/requests_sync.py b/examples/backends/requests_sync.py new file mode 100644 index 0000000..724cf85 --- /dev/null +++ b/examples/backends/requests_sync.py @@ -0,0 +1,50 @@ +"""requests sync quickstart; start examples/demo_api.py first.""" + +from dataclasses import dataclass + +from unihttp.bind_method import bind_method + +# --8<-- [start:backend-import] +from unihttp.clients.requests import RequestsSyncClient + +# --8<-- [end:backend-import] +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +# --8<-- [start:models] +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + # --8<-- [end:models] + + +# --8<-- [start:binding] +class UserClient(RequestsSyncClient): + get_user = bind_method(GetUser) + # --8<-- [end:binding] + + +def main(base_url: str = "http://127.0.0.1:8000") -> User: + with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + ) as client: + user = client.get_user(user_id=1) + print(user) # User(id=1, name='Ada') + return user + + +if __name__ == "__main__": + main() diff --git a/examples/backends/urllib_sync.py b/examples/backends/urllib_sync.py new file mode 100644 index 0000000..5532bbc --- /dev/null +++ b/examples/backends/urllib_sync.py @@ -0,0 +1,50 @@ +"""urllib sync quickstart; start examples/demo_api.py first.""" + +from dataclasses import dataclass + +from unihttp.bind_method import bind_method + +# --8<-- [start:backend-import] +from unihttp.clients.urllib import UrllibSyncClient + +# --8<-- [end:backend-import] +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +# --8<-- [start:models] +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + # --8<-- [end:models] + + +# --8<-- [start:binding] +class UserClient(UrllibSyncClient): + get_user = bind_method(GetUser) + # --8<-- [end:binding] + + +def main(base_url: str = "http://127.0.0.1:8000") -> User: + with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + ) as client: + user = client.get_user(user_id=1) + print(user) # User(id=1, name='Ada') + return user + + +if __name__ == "__main__": + main() diff --git a/examples/backends/zapros_async.py b/examples/backends/zapros_async.py new file mode 100644 index 0000000..e464ebb --- /dev/null +++ b/examples/backends/zapros_async.py @@ -0,0 +1,51 @@ +"""zapros async quickstart; start examples/demo_api.py first.""" + +import asyncio +from dataclasses import dataclass + +from unihttp.bind_method import bind_method + +# --8<-- [start:backend-import] +from unihttp.clients.zapros import ZaprosAsyncClient + +# --8<-- [end:backend-import] +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +# --8<-- [start:models] +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + # --8<-- [end:models] + + +# --8<-- [start:binding] +class UserClient(ZaprosAsyncClient): + get_user = bind_method(GetUser) + # --8<-- [end:binding] + + +async def main(base_url: str = "http://127.0.0.1:8000") -> User: + async with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + ) as client: + user = await client.get_user(user_id=1) + print(user) # User(id=1, name='Ada') + return user + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/backends/zapros_sync.py b/examples/backends/zapros_sync.py new file mode 100644 index 0000000..9d761f1 --- /dev/null +++ b/examples/backends/zapros_sync.py @@ -0,0 +1,50 @@ +"""zapros sync quickstart; start examples/demo_api.py first.""" + +from dataclasses import dataclass + +from unihttp.bind_method import bind_method + +# --8<-- [start:backend-import] +from unihttp.clients.zapros import ZaprosSyncClient + +# --8<-- [end:backend-import] +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +# --8<-- [start:models] +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + # --8<-- [end:models] + + +# --8<-- [start:binding] +class UserClient(ZaprosSyncClient): + get_user = bind_method(GetUser) + # --8<-- [end:binding] + + +def main(base_url: str = "http://127.0.0.1:8000") -> User: + with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + ) as client: + user = client.get_user(user_id=1) + print(user) # User(id=1, name='Ada') + return user + + +if __name__ == "__main__": + main() diff --git a/examples/demo_api.py b/examples/demo_api.py new file mode 100644 index 0000000..47c6928 --- /dev/null +++ b/examples/demo_api.py @@ -0,0 +1,28 @@ +"""Local API for the backend quickstarts; run with python examples/demo_api.py.""" + +import json +from contextlib import suppress +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + +class DemoAPIHandler(BaseHTTPRequestHandler): + def do_GET(self) -> None: + found = self.path == "/users/1" + data = {"id": 1, "name": "Ada"} if found else {"error": "User not found"} + body = json.dumps(data).encode() + self.send_response(200 if found else 404) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +def main() -> None: + with ThreadingHTTPServer(("127.0.0.1", 8000), DemoAPIHandler) as server: + print("Demo API: http://127.0.0.1:8000/users/1 (Ctrl+C to stop)") + with suppress(KeyboardInterrupt): + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/examples/json_codec.py b/examples/json_codec.py new file mode 100644 index 0000000..1d205dc --- /dev/null +++ b/examples/json_codec.py @@ -0,0 +1,49 @@ +"""Use orjson for HTTP JSON encoding while Adaptix handles typed models.""" + +from dataclasses import dataclass + +import httpx +import orjson +from unihttp.clients.httpx import HTTPXSyncClient +from unihttp.markers import Body +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +@dataclass +class User: + id: int + name: str + + +@dataclass +class CreateUser(BaseMethod[User]): + __url__ = "/users" + __method__ = "POST" + + name: Body[str] + + +def mock_api(request: httpx.Request) -> httpx.Response: + body = orjson.loads(request.content) + return httpx.Response(201, json={"id": 1, "name": body["name"]}) + + +def main() -> User: + with HTTPXSyncClient( + base_url="https://api.example.com", + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + # --8<-- [start:codec] + json_dumps=lambda value: orjson.dumps(value).decode("utf-8"), + json_loads=orjson.loads, + # --8<-- [end:codec] + session=httpx.Client(transport=httpx.MockTransport(mock_api)), + ) as client: + user = client.call_method(CreateUser(name="Ada")) + print(user) + return user + + +if __name__ == "__main__": + main() diff --git a/examples/middleware_async.py b/examples/middleware_async.py new file mode 100644 index 0000000..4dcd1dd --- /dev/null +++ b/examples/middleware_async.py @@ -0,0 +1,71 @@ +"""Measure async request time; start examples/demo_api.py before running this file.""" + +import asyncio +import logging +from dataclasses import dataclass +from time import perf_counter + +from unihttp.bind_method import bind_method +from unihttp.clients.httpx import HTTPXAsyncClient +from unihttp.http.request import HTTPRequest +from unihttp.http.response import HTTPResponse +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.middlewares import AsyncHandler, AsyncMiddleware +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + +logger = logging.getLogger("unihttp.timing") + + +class AsyncTimingMiddleware(AsyncMiddleware): + async def handle( + self, request: HTTPRequest, next_handler: AsyncHandler + ) -> HTTPResponse: + started = perf_counter() + response = await next_handler(request) + elapsed_ms = (perf_counter() - started) * 1000 + logger.info( + "%s → %s in %.1f ms", + request.method, + response.status_code, + elapsed_ms, + ) + return response + + +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + + def on_error(self, response: HTTPResponse) -> None: + response.raise_for_status() + + +class UserClient(HTTPXAsyncClient): + get_user = bind_method(GetUser) + + +async def main(base_url: str = "http://127.0.0.1:8000") -> User: + async with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + middleware=[AsyncTimingMiddleware()], + ) as client: + user = await client.get_user(user_id=1) + print(user) + return user + + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO) + asyncio.run(main()) diff --git a/examples/middleware_scope.py b/examples/middleware_scope.py new file mode 100644 index 0000000..8b78de5 --- /dev/null +++ b/examples/middleware_scope.py @@ -0,0 +1,68 @@ +"""Scope request headers; start examples/demo_api.py before running this file.""" + +from dataclasses import dataclass +from uuid import uuid4 + +from unihttp.bind_method import bind_method +from unihttp.clients.httpx import HTTPXSyncClient +from unihttp.http.request import HTTPRequest +from unihttp.http.response import HTTPResponse +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.middlewares import Handler, Middleware +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +class RequestIDMiddleware(Middleware): + def handle(self, request: HTTPRequest, next_handler: Handler) -> HTTPResponse: + request.header["X-Request-ID"] = uuid4().hex + return next_handler(request) + + +class NoCacheMiddleware(Middleware): + def handle(self, request: HTTPRequest, next_handler: Handler) -> HTTPResponse: + request.header["Cache-Control"] = "no-cache" + return next_handler(request) + + +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + + def on_error(self, response: HTTPResponse) -> None: + response.raise_for_status() + + +class UserClient(HTTPXSyncClient): + get_user = bind_method(GetUser, middleware=[NoCacheMiddleware()]) + + +def main(base_url: str = "http://127.0.0.1:8000") -> None: + with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + middleware=[RequestIDMiddleware()], + ) as client: + # Both the client and bound-method middleware run. + print(client.get_user(user_id=1)) + + # Only the client middleware runs. + print(client.call_method(GetUser(user_id=1))) + + # Add Cache-Control to this explicit call too. + user = client.call_method(GetUser(user_id=1), middleware=[NoCacheMiddleware()]) + print(user) + + +if __name__ == "__main__": + main() diff --git a/examples/middleware_sync.py b/examples/middleware_sync.py new file mode 100644 index 0000000..25173d4 --- /dev/null +++ b/examples/middleware_sync.py @@ -0,0 +1,68 @@ +"""Measure request time; start examples/demo_api.py before running this file.""" + +import logging +from dataclasses import dataclass +from time import perf_counter + +from unihttp.bind_method import bind_method +from unihttp.clients.httpx import HTTPXSyncClient +from unihttp.http.request import HTTPRequest +from unihttp.http.response import HTTPResponse +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.middlewares import Handler, Middleware +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + +logger = logging.getLogger("unihttp.timing") + + +class TimingMiddleware(Middleware): + def handle(self, request: HTTPRequest, next_handler: Handler) -> HTTPResponse: + started = perf_counter() + response = next_handler(request) + elapsed_ms = (perf_counter() - started) * 1000 + logger.info( + "%s → %s in %.1f ms", + request.method, + response.status_code, + elapsed_ms, + ) + return response + + +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + + def on_error(self, response: HTTPResponse) -> None: + response.raise_for_status() + + +class UserClient(HTTPXSyncClient): + get_user = bind_method(GetUser) + + +def main(base_url: str = "http://127.0.0.1:8000") -> User: + with UserClient( + base_url=base_url, + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + middleware=[TimingMiddleware()], + ) as client: + user = client.get_user(user_id=1) + print(user) + return user + + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO) + main() diff --git a/examples/optional_fields.py b/examples/optional_fields.py new file mode 100644 index 0000000..317b969 --- /dev/null +++ b/examples/optional_fields.py @@ -0,0 +1,39 @@ +"""Backend-independent optional request fields for the documentation.""" + +# --8<-- [start:setup] +from dataclasses import dataclass + +from unihttp.markers import Body, Header, Query +from unihttp.method import BaseMethod +from unihttp.omitted import Omittable, Omitted + + +@dataclass +class User: + id: int + name: str + nickname: str | None = None + # --8<-- [end:setup] + + +# --8<-- [start:query] +@dataclass +class ListUsers(BaseMethod[list[User]]): + __url__ = "/users" + __method__ = "GET" + + name: Query[Omittable[str]] = Omitted() + limit: Query[Omittable[int]] = Omitted() + accept: Header[Omittable[str]] = Omitted() + # --8<-- [end:query] + + +# --8<-- [start:body] +@dataclass +class CreateUser(BaseMethod[User]): + __url__ = "/users" + __method__ = "POST" + + name: Body[str] + nickname: Body[Omittable[str | None]] = Omitted() + # --8<-- [end:body] diff --git a/examples/quickstart.py b/examples/quickstart.py new file mode 100644 index 0000000..b638b8a --- /dev/null +++ b/examples/quickstart.py @@ -0,0 +1,53 @@ +"""Run with: uv run --group docs python examples/quickstart.py.""" + +from dataclasses import dataclass + +import httpx +from unihttp.bind_method import bind_method +from unihttp.clients.httpx import HTTPXSyncClient +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +# --8<-- [start:overview] +@dataclass +class User: + id: int + name: str + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + + +class UserClient(HTTPXSyncClient): + get_user = bind_method(GetUser) + # --8<-- [end:overview] + + +def mock_api(request: httpx.Request) -> httpx.Response: + """An in-process API, so the example needs no server or credentials.""" + if request.method == "GET" and request.url.path == "/users/1": + return httpx.Response(200, json={"id": 1, "name": "Ada"}) + return httpx.Response(404, json={"error": "User not found"}) + + +def main() -> User: + with UserClient( + base_url="https://api.example.com", + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + session=httpx.Client(transport=httpx.MockTransport(mock_api)), + ) as client: + user = client.get_user(user_id=1) + print(user) # User(id=1, name='Ada') + return user + + +if __name__ == "__main__": + main() diff --git a/examples/recipes.py b/examples/recipes.py new file mode 100644 index 0000000..de945d3 --- /dev/null +++ b/examples/recipes.py @@ -0,0 +1,111 @@ +"""Reusable, tested examples for the documentation guides.""" + +from dataclasses import dataclass + +from unihttp.bind_method import bind_method +from unihttp.clients.httpx import HTTPXSyncClient +from unihttp.http import UploadFile +from unihttp.http.request import HTTPRequest +from unihttp.http.response import HTTPResponse +from unihttp.markers import Body, File, Form, Path, Raw +from unihttp.method import BaseMethod, StreamMethod +from unihttp.middlewares.base import Handler, Middleware +from unihttp.omitted import Omittable, Omitted + + +# --8<-- [start:models] +@dataclass +class User: + id: int + name: str + + +@dataclass +class CreateUser(BaseMethod[User]): + __url__ = "/users" + __method__ = "POST" + + name: Body[str] + # --8<-- [end:models] + + +# --8<-- [start:partial] +@dataclass +class UpdateUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "PATCH" + + user_id: Path[int] + name: Body[Omittable[str | None]] = Omitted() + # --8<-- [end:partial] + + +# --8<-- [start:auth] +class BearerAuth(Middleware): + def __init__(self, token: str) -> None: + self.token = token + + def handle(self, request: HTTPRequest, next_handler: Handler) -> HTTPResponse: + request.header["Authorization"] = f"Bearer {self.token}" + return next_handler(request) + + # --8<-- [end:auth] + + +# --8<-- [start:upload] +@dataclass +class UploadAvatar(BaseMethod[User]): + __url__ = "/users/{user_id}/avatar" + __method__ = "POST" + + user_id: Path[int] + caption: Form[str] + avatar: File[UploadFile] + # --8<-- [end:upload] + + +# --8<-- [start:stream] +@dataclass +class DownloadFile(StreamMethod): + __url__ = "/files/{file_id}" + __method__ = "GET" + + file_id: Path[int] + # --8<-- [end:stream] + + +# --8<-- [start:errors] +class UserNotFound(Exception): + pass + + +@dataclass +class GetUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + + def on_error(self, response: HTTPResponse) -> None: + if response.status_code == 404: + raise UserNotFound(self.user_id) + + # --8<-- [end:errors] + + +# --8<-- [start:raw] +@dataclass +class PutBytes(BaseMethod[dict[str, int]]): + __url__ = "/blob" + __method__ = "PUT" + + content: Raw[bytes] + # --8<-- [end:raw] + + +class UserClient(HTTPXSyncClient): + get_user = bind_method(GetUser) + create_user = bind_method(CreateUser) + update_user = bind_method(UpdateUser) + upload_avatar = bind_method(UploadAvatar) + download_file = bind_method(DownloadFile) diff --git a/examples/response_errors.py b/examples/response_errors.py new file mode 100644 index 0000000..478829e --- /dev/null +++ b/examples/response_errors.py @@ -0,0 +1,107 @@ +"""HTTP status mapping and application errors for the response guides.""" + +import logging +from dataclasses import dataclass + +from unihttp.bind_method import bind_method +from unihttp.clients.httpx import HTTPXAsyncClient, HTTPXSyncClient +from unihttp.exceptions import ( + ClientError, + HTTPStatusError, + NetworkError, + RequestTimeoutError, + ServerError, +) +from unihttp.http.response import HTTPResponse +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.middlewares import AsyncErrorMapperMiddleware, SyncErrorMapperMiddleware + +from examples.recipes import GetUser, User, UserNotFound + +logger = logging.getLogger(__name__) + + +# --8<-- [start:sync] +status_errors = SyncErrorMapperMiddleware({ + range(400, 500): ClientError, + range(500, 600): ServerError, +}) + + +class UserClient(HTTPXSyncClient): + get_user = bind_method(GetUser, middleware=[status_errors]) + # --8<-- [end:sync] + + +# --8<-- [start:async] +async_status_errors = AsyncErrorMapperMiddleware({ + range(400, 500): ClientError, + range(500, 600): ServerError, +}) + + +class AsyncUserClient(HTTPXAsyncClient): + get_user = bind_method(GetUser, middleware=[async_status_errors]) + # --8<-- [end:async] + + +# --8<-- [start:catch-sync] +def find_user(client: UserClient, user_id: int) -> User | None: + try: + return client.get_user(user_id=user_id) + except UserNotFound: + return None + except HTTPStatusError as exc: + logger.warning( + "API returned HTTP %s (request ID: %s)", + exc.status_code, + exc.response.headers.get("X-Request-ID"), + ) + raise + except (NetworkError, RequestTimeoutError): + logger.warning("The API request could not be completed") + raise + # --8<-- [end:catch-sync] + + +# --8<-- [start:catch-async] +async def find_user_async(client: AsyncUserClient, user_id: int) -> User | None: + try: + return await client.get_user(user_id=user_id) + except UserNotFound: + return None + except HTTPStatusError as exc: + logger.warning( + "API returned HTTP %s (request ID: %s)", + exc.status_code, + exc.response.headers.get("X-Request-ID"), + ) + raise + except (NetworkError, RequestTimeoutError): + logger.warning("The API request could not be completed") + raise + # --8<-- [end:catch-async] + + +# --8<-- [start:validation] +class APIError(Exception): + pass + + +@dataclass +class GetValidatedUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + + def validate_response(self, response: HTTPResponse) -> None: + if ( + response.ok + and isinstance(response.data, dict) + and response.data.get("ok") is False + ): + raise APIError(response.data.get("error", "Unknown API error")) + + # --8<-- [end:validation] diff --git a/examples/response_metadata.py b/examples/response_metadata.py new file mode 100644 index 0000000..9a6d0af --- /dev/null +++ b/examples/response_metadata.py @@ -0,0 +1,113 @@ +"""Return a loaded model together with HTTP status and a response header.""" + +from dataclasses import dataclass +from operator import itemgetter + +import httpx +from adaptix import Chain, loader +from unihttp.bind_method import bind_method +from unihttp.clients.httpx import HTTPXSyncClient +from unihttp.exceptions import ClientError, ServerError +from unihttp.http.response import HTTPResponse +from unihttp.markers import Path +from unihttp.method import BaseMethod +from unihttp.middlewares import SyncErrorMapperMiddleware +from unihttp.serialize import ResponseLoader +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +# --8<-- [start:model] +@dataclass +class User: + id: int + name: str + # --8<-- [end:model] + + +# --8<-- [start:metadata] +@dataclass +class UserResponse: + user: User + status_code: int + request_id: str | None + + +@dataclass +class GetUser(BaseMethod[UserResponse]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + + def make_response( + self, response: HTTPResponse, response_loader: ResponseLoader + ) -> UserResponse: + return UserResponse( + user=response_loader.load(response.data, User), + status_code=response.status_code, + request_id=response.headers.get("X-Request-ID"), + ) + + # --8<-- [end:metadata] + + +# --8<-- [start:list] +@dataclass +class ListUsers(BaseMethod[list[User]]): + __url__ = "/users" + __method__ = "GET" + # --8<-- [end:list] + + +# --8<-- [start:envelope] +@dataclass +class GetWrappedUser(BaseMethod[User]): + __url__ = "/users/{user_id}" + __method__ = "GET" + + user_id: Path[int] + # --8<-- [end:envelope] + + +# --8<-- [start:envelope-loader] +envelope_retort = DEFAULT_RETORT.extend( + recipe=[ + loader(User, itemgetter("data"), chain=Chain.FIRST), + ], +) +envelope_loader = AdaptixLoader(envelope_retort) +# --8<-- [end:envelope-loader] + + +class UserClient(HTTPXSyncClient): + get_user = bind_method( + GetUser, + middleware=[ + SyncErrorMapperMiddleware({ + range(400, 500): ClientError, + range(500, 600): ServerError, + }), + ], + ) + + +def mock_api(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, json={"id": 1, "name": "Ada"}, headers={"X-Request-ID": "request-123"} + ) + + +def main() -> UserResponse: + with UserClient( + base_url="https://api.example.com", + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + session=httpx.Client(transport=httpx.MockTransport(mock_api)), + ) as client: + result = client.get_user(user_id=1) + print(result.user.name, result.status_code, result.request_id) + return result + + +if __name__ == "__main__": + main() diff --git a/examples/response_retries.py b/examples/response_retries.py new file mode 100644 index 0000000..18952de --- /dev/null +++ b/examples/response_retries.py @@ -0,0 +1,45 @@ +"""Scope retries to a buffered GET and map statuses after the last attempt.""" + +from unihttp.bind_method import bind_method +from unihttp.clients.httpx import HTTPXAsyncClient, HTTPXSyncClient +from unihttp.exceptions import NetworkError, RequestTimeoutError +from unihttp.middlewares import AsyncRetryMiddleware, RetryMiddleware + +from examples.recipes import CreateUser, GetUser +from examples.response_errors import async_status_errors, status_errors + + +# --8<-- [start:sync] +class UserClient(HTTPXSyncClient): + get_user = bind_method( + GetUser, + middleware=[ + status_errors, + RetryMiddleware( + retries=2, + backoff=0.5, + exceptions=[NetworkError, RequestTimeoutError], + jitter=True, + ), + ], + ) + create_user = bind_method(CreateUser, middleware=[status_errors]) + # --8<-- [end:sync] + + +# --8<-- [start:async] +class AsyncUserClient(HTTPXAsyncClient): + get_user = bind_method( + GetUser, + middleware=[ + async_status_errors, + AsyncRetryMiddleware( + retries=2, + backoff=0.5, + exceptions=[NetworkError, RequestTimeoutError], + jitter=True, + ), + ], + ) + create_user = bind_method(CreateUser, middleware=[async_status_errors]) + # --8<-- [end:async] diff --git a/examples/response_streaming.py b/examples/response_streaming.py new file mode 100644 index 0000000..43e42e5 --- /dev/null +++ b/examples/response_streaming.py @@ -0,0 +1,56 @@ +"""Consume a download without buffering it and reject unsuccessful responses.""" + +from dataclasses import dataclass +from hashlib import sha256 + +from unihttp.bind_method import bind_method +from unihttp.clients.httpx import HTTPXAsyncClient, HTTPXSyncClient +from unihttp.exceptions import HTTPStatusError +from unihttp.http.response import HTTPResponse +from unihttp.markers import Path +from unihttp.method import StreamMethod + + +# --8<-- [start:method] +@dataclass +class DownloadFile(StreamMethod): + __url__ = "/files/{file_id}" + __method__ = "GET" + + file_id: Path[int] + + def on_error(self, response: HTTPResponse) -> None: + response.raise_for_status() + raise HTTPStatusError(f"Unexpected HTTP {response.status_code}", response) + + # --8<-- [end:method] + + +class FileClient(HTTPXSyncClient): + download_file = bind_method(DownloadFile) + + +class AsyncFileClient(HTTPXAsyncClient): + download_file = bind_method(DownloadFile) + + +# --8<-- [start:sync] +def download_checksum(client: FileClient, file_id: int) -> str: + response = client.download_file(file_id=file_id) + digest = sha256() + with response.data as stream: + for chunk in stream: + digest.update(chunk) + return digest.hexdigest() + # --8<-- [end:sync] + + +# --8<-- [start:async] +async def download_checksum_async(client: AsyncFileClient, file_id: int) -> str: + response = await client.download_file(file_id=file_id) + digest = sha256() + async with response.data as stream: + async for chunk in stream: + digest.update(chunk) + return digest.hexdigest() + # --8<-- [end:async] diff --git a/examples/serialization/__init__.py b/examples/serialization/__init__.py new file mode 100644 index 0000000..f76a756 --- /dev/null +++ b/examples/serialization/__init__.py @@ -0,0 +1 @@ +"""Tested model conversion and serializer configuration examples.""" diff --git a/examples/serialization/adaptix.py b/examples/serialization/adaptix.py new file mode 100644 index 0000000..946052e --- /dev/null +++ b/examples/serialization/adaptix.py @@ -0,0 +1,27 @@ +"""Adaptix setup for the shared serialization guide.""" + +# --8<-- [start:setup] +from dataclasses import dataclass + +from unihttp.markers import Body +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +@dataclass +class User: + id: int + user_name: str + + +@dataclass +class CreateUser(BaseMethod[User]): + __url__ = "/users" + __method__ = "POST" + + user_name: Body[str] + + +request_dumper = AdaptixDumper(DEFAULT_RETORT) +response_loader = AdaptixLoader(DEFAULT_RETORT) +# --8<-- [end:setup] diff --git a/examples/serialization/customization.py b/examples/serialization/customization.py new file mode 100644 index 0000000..e7c18f4 --- /dev/null +++ b/examples/serialization/customization.py @@ -0,0 +1,63 @@ +"""Customize Adaptix for API field names, normalized input, and Unix timestamps.""" + +from dataclasses import dataclass +from datetime import UTC, datetime + +from adaptix import P, dumper, loader, name_mapping +from unihttp.markers import Body +from unihttp.method import BaseMethod +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + +from examples.serialization.adaptix import CreateUser, User + +# --8<-- [start:global-mapping] +global_retort = DEFAULT_RETORT.extend( + recipe=[name_mapping(map={"user_name": "userName"})], +) +request_dumper = AdaptixDumper(global_retort) +response_loader = AdaptixLoader(global_retort) +# --8<-- [end:global-mapping] + +# --8<-- [start:scoped-mapping] +scoped_retort = DEFAULT_RETORT.extend( + recipe=[ + name_mapping(User, map={"user_name": "userName"}), + name_mapping(CreateUser, map={"user_name": "userName"}), + ], +) +# --8<-- [end:scoped-mapping] + +# --8<-- [start:normalize] +normalized_retort = global_retort.extend( + recipe=[dumper(P[CreateUser].user_name, str.strip)], +) +request_dumper = AdaptixDumper(normalized_retort) +# --8<-- [end:normalize] + + +# --8<-- [start:event-models] +@dataclass +class Event: + id: int + starts_at: datetime + + +@dataclass +class CreateEvent(BaseMethod[Event]): + __url__ = "/events" + __method__ = "POST" + + starts_at: Body[datetime] + # --8<-- [end:event-models] + + +# --8<-- [start:timestamps] +timestamp_retort = DEFAULT_RETORT.extend( + recipe=[ + loader(P[Event].starts_at, lambda value: datetime.fromtimestamp(value, tz=UTC)), + dumper(P[CreateEvent].starts_at, lambda value: value.timestamp()), + ], +) +request_dumper = AdaptixDumper(timestamp_retort) +response_loader = AdaptixLoader(timestamp_retort) +# --8<-- [end:timestamps] diff --git a/examples/serialization/msgspec.py b/examples/serialization/msgspec.py new file mode 100644 index 0000000..00e76fd --- /dev/null +++ b/examples/serialization/msgspec.py @@ -0,0 +1,27 @@ +"""Msgspec setup for the shared serialization guide.""" + +# --8<-- [start:setup] +from dataclasses import dataclass + +import msgspec +from unihttp.markers import Body +from unihttp.method import BaseMethod +from unihttp.serializers.msgspec import MsgspecDumper, MsgspecLoader + + +class User(msgspec.Struct): + id: int + user_name: str + + +@dataclass +class CreateUser(BaseMethod[User]): + __url__ = "/users" + __method__ = "POST" + + user_name: Body[str] + + +request_dumper = MsgspecDumper() +response_loader = MsgspecLoader() +# --8<-- [end:setup] diff --git a/examples/serialization/pydantic.py b/examples/serialization/pydantic.py new file mode 100644 index 0000000..ec213fb --- /dev/null +++ b/examples/serialization/pydantic.py @@ -0,0 +1,27 @@ +"""Pydantic setup for the shared serialization guide.""" + +# --8<-- [start:setup] +from dataclasses import dataclass + +from pydantic import BaseModel +from unihttp.markers import Body +from unihttp.method import BaseMethod +from unihttp.serializers.pydantic import PydanticDumper, PydanticLoader + + +class User(BaseModel): + id: int + user_name: str + + +@dataclass +class CreateUser(BaseMethod[User]): + __url__ = "/users" + __method__ = "POST" + + user_name: Body[str] + + +request_dumper = PydanticDumper() +response_loader = PydanticLoader() +# --8<-- [end:setup] diff --git a/pyproject.toml b/pyproject.toml index bc17156..fca7777 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,6 +37,7 @@ classifiers = [ [project.urls] Homepage = "https://github.com/goduni/unihttp" Repository = "https://github.com/goduni/unihttp" +Documentation = "https://unihttp.readthedocs.io/en/latest/" Issues = "https://github.com/goduni/unihttp/issues" [project.optional-dependencies] @@ -52,6 +53,15 @@ msgspec = ["msgspec>=0.18.0"] [dependency-groups] +docs = [ + "zensical==0.0.59", + "mkdocstrings-python==2.0.8", + "beautifulsoup4>=4.12,<5", + "markdownify>=1.2,<2", + "orjson>=3.10,<4", + "unihttp[httpx,adaptix,pydantic,msgspec]", +] + optionals = [ "unihttp[httpx]", "unihttp[httpx2]", diff --git a/ruff.toml b/ruff.toml index fb7e8d4..9ea908e 100644 --- a/ruff.toml +++ b/ruff.toml @@ -92,3 +92,9 @@ external = ["WPS"] [lint.pydocstyle] convention = "google" + +[lint.per-file-ignores] +# These files are embedded in the docs: keep lint directives out of examples. +# Omitted() is a singleton; UserNotFound is the documented exception name. +"examples/optional_fields.py" = ["RUF009"] +"examples/recipes.py" = ["RUF009", "N818"] diff --git a/scripts/build_docs.py b/scripts/build_docs.py new file mode 100644 index 0000000..4261889 --- /dev/null +++ b/scripts/build_docs.py @@ -0,0 +1,270 @@ +"""Build and verify the public site, including RTD metadata and agent exports.""" + +import gzip +import json +import os +import subprocess # noqa: S404 -- invokes the local documentation builder, without a shell +import sys +import tempfile +import tomllib +from pathlib import Path +from urllib.parse import unquote, urljoin, urlsplit +from xml.etree import ElementTree as ET # noqa: S405 -- parses our own generated sitemap + +from bs4 import BeautifulSoup +from markdownify import markdownify + +ROOT = Path(__file__).resolve().parents[1] +OUTPUT = ROOT / ".build/docs" + + +def page_url(path: Path, base_url: str) -> str: + relative = path.relative_to(OUTPUT).as_posix() + return urljoin(base_url, relative.removesuffix("index.html")) + + +def build(base_url: str) -> None: + source = (ROOT / "zensical.toml").read_text() + original_url = tomllib.loads(source)["project"]["site_url"] + source = source.replace( + f"site_url = {json.dumps(original_url)}", f"site_url = {json.dumps(base_url)}", 1 + ) + # Keep the configuration next to the original: relative source paths stay valid. + with tempfile.NamedTemporaryFile( + mode="w", encoding="utf-8", suffix=".toml", prefix=".zensical-", dir=ROOT + ) as config: + config.write(source) + config.flush() + subprocess.run( # noqa: S603 -- arguments are fixed and configuration is local + [ + sys.executable, + "-m", + "zensical", + "build", + "--clean", + "--strict", + "-f", + config.name, + ], + cwd=ROOT, + check=True, + ) + + +def finish_pages(base_url: str, version: str, noindex: bool) -> dict[Path, BeautifulSoup]: + pages = {} + index = [ + "# unihttp", + "", + "> Declarative, typed Python API clients. Choose an HTTP backend and serializer.", + "", + f"Documentation version: {version}. latest tracks development, not a release.", + "", + "## Documentation", + "", + ] + for path in sorted(OUTPUT.rglob("*.html")): + soup = BeautifulSoup(path.read_text(), "html.parser") + article = soup.select_one("article.md-content__inner") + if article is None or path.name == "404.html": + if noindex or path.name == "404.html": + tag = soup.new_tag("meta", attrs={"name": "robots", "content": "noindex"}) + soup.head.append(tag) + path.write_text(str(soup)) + pages[path] = soup + continue + title = article.find("h1") + description = soup.find("meta", attrs={"name": "description"}) + if title is None or description is None or not description.get("content"): + raise ValueError(f"Missing heading or description: {path}") + canonical = soup.find("link", rel="canonical") + expected_url = page_url(path, base_url) + if canonical is None or canonical.get("href") != expected_url: + raise ValueError(f"Incorrect canonical URL: {path}") + if noindex: + soup.head.append( + soup.new_tag("meta", attrs={"name": "robots", "content": "noindex"}) + ) + markdown_path = Path("markdown") / path.relative_to(OUTPUT).with_suffix(".md") + alternate = soup.new_tag( + "link", + attrs={ + "rel": "alternate", + "type": "text/markdown", + "href": urljoin(base_url, markdown_path.as_posix()), + }, + ) + soup.head.append(alternate) + # Convert the article, not navigation. This expands snippets and API directives. + content = BeautifulSoup(str(article), "html.parser") + for element in content.select(".headerlink, .md-content__button"): + element.decompose() + label_exported_tabs(content) + for link in content.find_all("a", href=True): + link["href"] = urljoin(expected_url, link["href"]) + text = markdownify(str(content), heading_style="ATX") + if "--8<--" in text or "::: unihttp" in text: + raise ValueError(f"Unexpanded documentation directive: {path}") + destination = OUTPUT / markdown_path + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(f"Source: {expected_url}\n\n{text.strip()}\n") + label = title.get_text(" ", strip=True).replace("¶", "").strip() + index.append(f"- [{label}]({alternate['href']}): {description['content']}") + path.write_text(str(soup)) + pages[path] = soup + (OUTPUT / "llms.txt").write_text("\n".join(index) + "\n") + return pages + + +def label_exported_tabs(content: BeautifulSoup) -> None: + """Keep each tab's label beside its content, including inactive and nested tabs.""" + for group in reversed(content.select(".tabbed-set")): + labels = group.select(":scope > .tabbed-labels > label") + panels = group.select(":scope > .tabbed-content > .tabbed-block") + if not labels or len(labels) != len(panels): + raise ValueError("Cannot associate exported tab labels with content") + for label, panel in zip(labels, panels, strict=True): + paragraph = content.new_tag("p") + name = content.new_tag("strong") + name.string = label.get_text(" ", strip=True) + paragraph.append(name) + panel.insert(0, paragraph) + for control in group.select(":scope > input, :scope > .tabbed-labels"): + control.decompose() + + +def verify_links(pages: dict[Path, BeautifulSoup], base_url: str) -> None: # noqa: C901 + base = urlsplit(base_url) + errors = [] + for path, soup in pages.items(): + # 404 URLs have no stable relative location when served for missing paths. + if path.name == "404.html": + continue + for element in soup.select("a[href], link[href], script[src], img[src]"): + href = element.get("href", element.get("src", "")) + target = urlsplit(urljoin(page_url(path, base_url), href)) + if target.netloc != base.netloc or target.scheme not in {"http", "https"}: + continue + if not target.path.startswith(base.path): + errors.append(f"{path}: link leaves this documentation version: {href}") + continue + relative = unquote(target.path[len(base.path) :]) + resolved = OUTPUT / relative + if target.path.endswith("/"): + resolved /= "index.html" + if not resolved.is_file(): + errors.append(f"{path}: missing target: {href}") + elif target.fragment and resolved in pages: + anchor = unquote(target.fragment) + if pages[resolved].find(id=anchor) is None: + errors.append(f"{path}: missing anchor: {href}") + if errors: + raise ValueError("\n".join(errors)) + + +def verify_api_reference(pages: dict[Path, BeautifulSoup]) -> None: + """Fail if the generator silently hides essential public signatures.""" + clients = pages[OUTPUT / "reference/clients/index.html"] + for identifier in ( + "unihttp.clients.httpx.HTTPXSyncClient", + "unihttp.clients.httpx.HTTPXAsyncClient", + ): + heading = clients.find(id=identifier) + signature = heading.parent.select_one(".doc-signature") if heading else None + if signature is None or not all( + parameter in signature.get_text() + for parameter in ("base_url", "request_dumper", "response_loader", "session") + ): + raise ValueError(f"Missing public constructor signature: {identifier}") + + serializers = pages[OUTPUT / "reference/serializers/index.html"] + symbols = [ + "unihttp.serialize.RequestDumper.dump", + "unihttp.serialize.ResponseLoader.load", + ] + for backend, prefix in ( + ("adaptix", "Adaptix"), + ("pydantic", "Pydantic"), + ("msgspec", "Msgspec"), + ): + symbols.extend(( + f"unihttp.serializers.{backend}.serialize.{prefix}Dumper.dump", + f"unihttp.serializers.{backend}.serialize.{prefix}Loader.load", + )) + for identifier in symbols: + if serializers.find(id=identifier) is None: + raise ValueError(f"Missing public serializer method: {identifier}") + + +def verify_redirects( + pages: dict[Path, BeautifulSoup], base_url: str, redirects: dict[str, str] +) -> None: + """Verify that moved documentation still resolves to its consolidated page.""" + + def html_path(source: str) -> Path: + path = Path(source) + if path.name == "index.md": + return OUTPUT / path.with_suffix(".html") + return OUTPUT / path.with_suffix("") / "index.html" + + for source, target in redirects.items(): + old_path = html_path(source) + target_path = html_path(target) + if old_path not in pages or target_path not in pages: + raise ValueError(f"Missing redirect or destination: {source} -> {target}") + soup = pages[old_path] + canonical = soup.find("link", rel="canonical") + refresh = soup.find("meta", attrs={"http-equiv": "refresh"}) + expected = page_url(target_path, base_url) + old_url = page_url(old_path, base_url) + if canonical is None or urljoin(old_url, canonical.get("href", "")) != expected: + raise ValueError(f"Incorrect redirect canonical: {source}") + destination = refresh.get("content", "").partition("url=")[2] if refresh else "" + if not destination or urljoin(old_url, destination) != expected: + raise ValueError(f"Incorrect redirect destination: {source}") + + +def verify_sitemap(base_url: str, noindex: bool) -> None: + path = OUTPUT / "sitemap.xml" + tree = ET.parse(path) # noqa: S314 -- local output from Zensical, not untrusted XML + root = tree.getroot() + for location in root.findall(".//{*}loc"): + if not location.text or not location.text.startswith(base_url): + raise ValueError("Sitemap contains a URL outside the canonical version") + if noindex: + for child in list(root): + root.remove(child) + tree.write(path, encoding="utf-8", xml_declaration=True) + # Zensical may emit a compressed copy; keep it consistent with the XML. + compressed = OUTPUT / "sitemap.xml.gz" + if compressed.exists(): + compressed.write_bytes(gzip.compress(path.read_bytes())) + + +def main() -> None: + config = tomllib.loads((ROOT / "zensical.toml").read_text())["project"] + base_url = ( + os.environ.get("READTHEDOCS_CANONICAL_URL", config["site_url"]).rstrip("/") + "/" + ) + if urlsplit(base_url).scheme not in {"http", "https"}: + raise ValueError("The documentation URL must be an absolute HTTP(S) URL") + version = os.environ.get("READTHEDOCS_VERSION", "latest") + version_type = os.environ.get("READTHEDOCS_VERSION_TYPE", "branch") + noindex = ( + os.environ.get("DOCS_NOINDEX") == "1" + or version_type == "external" + or (version_type == "branch" and version not in {"latest", "stable"}) + ) + build(base_url) + pages = finish_pages(base_url, version, noindex) + verify_links(pages, base_url) + verify_api_reference(pages) + verify_redirects(pages, base_url, config["plugins"]["redirects"]["redirect_maps"]) + verify_sitemap(base_url, noindex) + print( + f"Verified {len(pages)} HTML pages; generated Markdown and llms.txt in {OUTPUT}" + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/docs_griffe.py b/scripts/docs_griffe.py new file mode 100644 index 0000000..31785cb --- /dev/null +++ b/scripts/docs_griffe.py @@ -0,0 +1,48 @@ +"""Adapt API extraction to unihttp's source layout without changing the package.""" + +from pathlib import Path +from typing import Any + +from griffe import Extension, Function, GriffeLoader, Module, visit + + +class UnihttpDocsExtension(Extension): + def on_module(self, *, mod: Module, loader: GriffeLoader, **kwargs: Any) -> None: + if mod.path != "unihttp" or "serializers" in mod.members: + return + if not isinstance(mod.filepath, Path): + return + directory = mod.filepath.parent / "serializers" + namespace = Module("serializers", filepath=[directory], parent=mod) + mod.set_member("serializers", namespace) + for package in sorted(directory.iterdir()): + if not (package / "__init__.py").is_file(): + continue + self._visit_module(package / "__init__.py", package.name, namespace, loader) + child = namespace.members[package.name] + for source in sorted(package.glob("*.py")): + if source.name != "__init__.py": + self._visit_module(source, source.stem, child, loader) + + @staticmethod + def _visit_module( + source: Path, name: str, parent: Module, loader: GriffeLoader + ) -> None: + module = visit( + name, + source, + source.read_text(encoding="utf-8"), + parent=parent, + docstring_parser=loader.docstring_parser, + docstring_options=loader.docstring_options, + lines_collection=loader.lines_collection, + modules_collection=loader.modules_collection, + ) + parent.set_member(name, module) + + def on_function(self, *, func: Function, loader: GriffeLoader, **kwargs: Any) -> None: + if func.path == "unihttp.clients.base.BaseClient.handle_error" and func.docstring: + # Normalize only the extracted text of this legacy docstring. + func.docstring.value = func.docstring.value.replace( + "\n response:", "\n response:" + ).replace("\n method:", "\n method:") diff --git a/site/getting-started/async.md b/site/getting-started/async.md new file mode 100644 index 0000000..25d5883 --- /dev/null +++ b/site/getting-started/async.md @@ -0,0 +1,92 @@ +--- +title: Build an async API client +description: Run async unihttp clients with HTTPX, aiohttp, HTTPX2, niquests, or zapros, typed methods, and async context managers. +--- + +# Build an async API client + +Choose an async HTTP backend below. Every variant uses the same dataclasses and +Adaptix serializer, awaits the bound call, and constructs the client inside a +running event loop. + +First start the [local demo API](quickstart.md#demo-api) in a separate terminal. +Then install the dependencies from your tab, save the Python code as +`async_client.py`, and run `python async_client.py`. +Each variant prints `User(id=1, name='Ada')`. + +=== "HTTPX" + + ```bash + pip install "unihttp[httpx,adaptix]" + ``` + + ```python + --8<-- "examples/backends/httpx_async.py" + ``` + +=== "aiohttp" + + ```bash + pip install "unihttp[aiohttp,adaptix]" + ``` + + ```python + --8<-- "examples/backends/aiohttp_async.py" + ``` + +=== "HTTPX2" + + ```bash + pip install "unihttp[httpx2,adaptix]" + ``` + + ```python + --8<-- "examples/backends/httpx2_async.py" + ``` + +=== "niquests" + + ```bash + pip install "unihttp[niquests,adaptix]" + ``` + + ```python + --8<-- "examples/backends/niquests_async.py" + ``` + +=== "zapros" + + ```bash + pip install "unihttp[zapros,adaptix]" + ``` + + ```python + --8<-- "examples/backends/zapros_async.py" + ``` + +## Lifecycle and middleware + +Use `async with` to close the client. Reuse an open client for related requests +instead of constructing one per call. If you supply a session, check the selected +[backend's lifecycle](../integrations/backends.md#transport-configuration) before +sharing it with other code. + +An async client requires `AsyncMiddleware` implementations and async variants +of built-in middleware. See [middleware](../guides/middleware.md). + +In a notebook or an application with an existing event loop, use +`await main()` instead of nesting `asyncio.run()`. + +For multiple independent calls, schedule them with the concurrency primitives +of your application and keep the client open until all calls finish. Set +concurrency limits appropriate to the remote API. + +To use a real API, replace `base_url`, adapt the endpoint and response model, +and configure [error handling](../guides/errors.md). +requests and urllib are sync-only; see the [sync quickstart](quickstart.md). + +## Next steps + +Continue with [methods and request parameters](../guides/methods.md), or choose +your next task in the [user guide](../guides/index.md). +This tutorial is an alternative to the sync quickstart; you do not need both. diff --git a/site/getting-started/installation.md b/site/getting-started/installation.md new file mode 100644 index 0000000..9b8d1c4 --- /dev/null +++ b/site/getting-started/installation.md @@ -0,0 +1,467 @@ +--- +title: Install unihttp +description: Install unihttp on Python 3.12–3.14. Choose an HTTP backend and serializer, copy the pip or uv command, and verify your installation. +--- + +
+ +Getting started +{ .uh-eyebrow } + +# Install unihttp + +A small core. The dependencies you choose. +{ .uh-lead } + +Install an HTTP backend and a serializer, then start building your API client. +No need to install every integration. + +Python **3.12–3.14** · pip or uv +{ .uh-install-requirements } + +## 1. Install your stack {#choose-your-extras} + +Choose your HTTP library, then your model serializer. Run **one** of the two +commands shown. If you are following the quickstart, keep **Adaptix** selected. +Not sure which transport fits? [Compare the backends](../integrations/backends.md). + +
+Starting fresh? Set up an environment first. + +For pip, create an isolated environment with a supported Python interpreter. +Activate it before running the installation command. + +=== "macOS / Linux" + + ```bash + python3.12 -m venv .venv + source .venv/bin/activate + ``` + +=== "Windows (PowerShell)" + + ```powershell + py -3.12 -m venv .venv + .venv\Scripts\Activate.ps1 + ``` + +Python 3.13 or 3.14 also works; replace the interpreter version above. + +For a new uv project, run the following, then use `uv add` below. +uv manages the project's environment; you do not need to activate it. + +```bash +uv init --python 3.12 my-api-client +cd my-api-client +``` + +More about [pip environments](https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/) +and [uv projects](https://docs.astral.sh/uv/guides/projects/). + +
+ +
+ +HTTP library +{ .uh-install-label } + +=== "HTTPX" + + Sync and async. + { .uh-install-mode } + + Model serialization + { .uh-install-label } + + === "Adaptix" + + For dataclasses and TypedDicts. Used throughout the quickstarts. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[httpx,adaptix]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[httpx,adaptix]" + ``` + + === "Pydantic" + + For applications with Pydantic response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[httpx,pydantic]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[httpx,pydantic]" + ``` + + === "msgspec" + + For applications with msgspec.Struct response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[httpx,msgspec]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[httpx,msgspec]" + ``` + +=== "requests" + + Sync only. + { .uh-install-mode } + + Model serialization + { .uh-install-label } + + === "Adaptix" + + For dataclasses and TypedDicts. Used throughout the quickstarts. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[requests,adaptix]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[requests,adaptix]" + ``` + + === "Pydantic" + + For applications with Pydantic response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[requests,pydantic]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[requests,pydantic]" + ``` + + === "msgspec" + + For applications with msgspec.Struct response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[requests,msgspec]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[requests,msgspec]" + ``` + +=== "aiohttp" + + Async only. + { .uh-install-mode } + + Model serialization + { .uh-install-label } + + === "Adaptix" + + For dataclasses and TypedDicts. Used throughout the quickstarts. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[aiohttp,adaptix]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[aiohttp,adaptix]" + ``` + + === "Pydantic" + + For applications with Pydantic response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[aiohttp,pydantic]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[aiohttp,pydantic]" + ``` + + === "msgspec" + + For applications with msgspec.Struct response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[aiohttp,msgspec]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[aiohttp,msgspec]" + ``` + +=== "HTTPX2" + + Sync and async. + { .uh-install-mode } + + Model serialization + { .uh-install-label } + + === "Adaptix" + + For dataclasses and TypedDicts. Used throughout the quickstarts. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[httpx2,adaptix]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[httpx2,adaptix]" + ``` + + === "Pydantic" + + For applications with Pydantic response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[httpx2,pydantic]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[httpx2,pydantic]" + ``` + + === "msgspec" + + For applications with msgspec.Struct response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[httpx2,msgspec]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[httpx2,msgspec]" + ``` + +=== "niquests" + + Sync and async. + { .uh-install-mode } + + Model serialization + { .uh-install-label } + + === "Adaptix" + + For dataclasses and TypedDicts. Used throughout the quickstarts. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[niquests,adaptix]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[niquests,adaptix]" + ``` + + === "Pydantic" + + For applications with Pydantic response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[niquests,pydantic]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[niquests,pydantic]" + ``` + + === "msgspec" + + For applications with msgspec.Struct response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[niquests,msgspec]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[niquests,msgspec]" + ``` + +=== "zapros" + + Sync and async. + { .uh-install-mode } + + Model serialization + { .uh-install-label } + + === "Adaptix" + + For dataclasses and TypedDicts. Used throughout the quickstarts. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[zapros,adaptix]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[zapros,adaptix]" + ``` + + === "Pydantic" + + For applications with Pydantic response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[zapros,pydantic]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[zapros,pydantic]" + ``` + + === "msgspec" + + For applications with msgspec.Struct response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[zapros,msgspec]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[zapros,msgspec]" + ``` + +=== "urllib" + + Sync only · standard-library transport. + { .uh-install-mode } + + Model serialization + { .uh-install-label } + + === "Adaptix" + + For dataclasses and TypedDicts. Used throughout the quickstarts. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[adaptix]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[adaptix]" + ``` + + === "Pydantic" + + For applications with Pydantic response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[pydantic]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[pydantic]" + ``` + + === "msgspec" + + For applications with msgspec.Struct response models. + + ```bash title="pip · activated virtual environment" + python -m pip install "unihttp[msgspec]" + ``` + + ```bash title="uv · existing project" + uv add "unihttp[msgspec]" + ``` + +
+ +Installing extras makes integrations available; it does **not** select them in +your code. When you create a client, choose its backend class and pass +`request_dumper` and `response_loader` explicitly. +{ .uh-install-note } + +## 2. Check the installation + +Run this in the same environment where you installed unihttp. +It prints the installed package version without making a network request. + +=== "pip" + + ```bash + python -c "from importlib.metadata import version; print(version('unihttp'))" + ``` + +=== "uv" + + ```bash + uv run python -c "from importlib.metadata import version; print(version('unihttp'))" + ``` + +
+Package not found, or an import fails? + +- **`PackageNotFoundError` or `No module named unihttp`:** activate the environment + used for installation, or run your script with `uv run python`. Check that your + editor uses that same interpreter. +- **A backend or serializer module is missing:** rerun the command for the + combination you selected. The core package does not install optional integrations. +- **Python version is incompatible:** use Python 3.12, 3.13, or 3.14. Check the + interpreter with `python --version` (or `uv run python --version`). +- **`from unihttp import BaseMethod` fails:** public types live in submodules. + Use `from unihttp.method import BaseMethod`; see the + [method reference](../reference/methods.md). + +
+ +## 3. Make your first call + +The quickstarts use dataclasses and Adaptix with a local demo API. +Choose the execution model that fits your application. + +
+ +[**Build a sync client →** HTTPX, requests, HTTPX2, niquests, zapros, or urllib.](quickstart.md) + +[**Build an async client →** HTTPX, aiohttp, HTTPX2, niquests, or zapros.](async.md) + +
+ +Using existing models? The [serialization guide](../guides/serialization.md#connect-a-serializer) +shows Adaptix, Pydantic, and msgspec setup side by side. + +## Other installation options + +
+Core only, with custom serialization + +```bash +python -m pip install unihttp +``` + +This installs the core package, not optional HTTP or serializer dependencies. +Provide your own [request dumper and response loader](../reference/serializers.md). +The urllib backend needs no HTTP extra; third-party backends need their matching +extra or an already-installed dependency. + +
+ +
+Run the examples from this repository + +For a normal application, use a published package and keep your dependency +version pinned or locked. To work with the same source as this documentation: + +```bash +git clone https://github.com/goduni/unihttp.git +cd unihttp +uv sync --group docs +uv run --group docs python examples/quickstart.py +``` + +This particular example uses HTTPX's mock transport, so it needs no demo server. +See [versions and migration](../project/releases.md) for release details and +[contributing](../project/documentation.md) to work on the library or its documentation. + +
+ +
diff --git a/site/getting-started/quickstart.md b/site/getting-started/quickstart.md new file mode 100644 index 0000000..5eb6274 --- /dev/null +++ b/site/getting-started/quickstart.md @@ -0,0 +1,127 @@ +--- +title: Build a sync API client +description: Run a typed unihttp client with HTTPX, requests, HTTPX2, niquests, zapros, or urllib, using dataclasses and Adaptix. +--- + +# Build a sync API client + +Choose your HTTP library below. Each tab contains its installation command and a +complete script: the models and endpoint are the same, while the client class +and import match your backend. All variants use Adaptix for serialization. + +Need aiohttp or asynchronous calls? Use the [async quickstart](async.md). + +## Start a local demo API {#demo-api} + +All tabs call the same local API, so you need no API account or credentials. +Save the following as `demo_api.py` and run `python demo_api.py` in a separate +terminal. Keep it running while trying the clients; stop it with Ctrl+C. + +
+demo_api.py — standard-library demo server + +```python +--8<-- "examples/demo_api.py" +``` + +
+ +The server listens only on `127.0.0.1:8000` and returns +`{"id": 1, "name": "Ada"}` for `GET /users/1`. This is a local teaching server, +not a production API. + +## Choose your client + +In a second terminal, install the dependencies from your tab. Save its Python +code as `quickstart.py`, then run `python quickstart.py`. +Every variant prints `User(id=1, name='Ada')`. + +=== "HTTPX" + + ```bash + pip install "unihttp[httpx,adaptix]" + ``` + + ```python + --8<-- "examples/backends/httpx_sync.py" + ``` + +=== "requests" + + ```bash + pip install "unihttp[requests,adaptix]" + ``` + + ```python + --8<-- "examples/backends/requests_sync.py" + ``` + +=== "HTTPX2" + + ```bash + pip install "unihttp[httpx2,adaptix]" + ``` + + ```python + --8<-- "examples/backends/httpx2_sync.py" + ``` + +=== "niquests" + + ```bash + pip install "unihttp[niquests,adaptix]" + ``` + + ```python + --8<-- "examples/backends/niquests_sync.py" + ``` + +=== "zapros" + + ```bash + pip install "unihttp[zapros,adaptix]" + ``` + + ```python + --8<-- "examples/backends/zapros_sync.py" + ``` + +=== "urllib" + + ```bash + pip install "unihttp[adaptix]" + ``` + + ```python + --8<-- "examples/backends/urllib_sync.py" + ``` + +## What each part does + +- `User` is the response model. +- `GetUser(BaseMethod[User])` declares the endpoint and its result type. +- `user_id: Path[int]` fills `{user_id}` in the URL. +- `bind_method(GetUser)` exposes `get_user(user_id=...)` on the client. +- `AdaptixDumper` handles request parameters; `AdaptixLoader` builds the result. +- `with` closes the client when the block finishes. + +The bound method's argument types come from the method dataclass constructor. +Its result is `User`, not an `HTTPResponse`. Editor presentation of descriptors +can vary; the [binding reference](../reference/methods.md) explains the contract. + +## Connect to a real API + +Replace `base_url` with your API origin, adjust the endpoint and models to its +contract, and configure [error handling](../guides/errors.md). +The selected client creates its underlying HTTP session automatically. + +Session settings such as timeouts are backend-specific; see +[transport configuration](../integrations/backends.md#transport-configuration). +Do not pass an HTTPX session to a requests, niquests, or other backend. + +## Next steps + +Continue with [methods and request parameters](../guides/methods.md), or choose +your next task in the [user guide](../guides/index.md). +The [async quickstart](async.md) is an alternative to this tutorial, not a +required next step. diff --git a/site/guides/errors.md b/site/guides/errors.md new file mode 100644 index 0000000..28063a4 --- /dev/null +++ b/site/guides/errors.md @@ -0,0 +1,173 @@ +--- +title: Handle HTTP and response validation errors +description: Configure HTTP status exceptions, catch request failures, handle endpoint-specific errors, and validate error bodies in unihttp. +--- + +# Handle HTTP and response validation errors + +**unihttp does not raise HTTP status errors automatically.** Without explicit +handling, a `404` or `503` continues to response loading, which may fail because +the error body does not match your model. + +Use status mapping for general HTTP errors and method hooks for endpoint-specific +rules. Catch exceptions around the client call. + +## Handle an endpoint-specific error + +This method uses `User` from the [quickstart](../getting-started/quickstart.md). +It treats a missing user specially and leaves other statuses to the mapper below: + +```python +from dataclasses import dataclass + +from unihttp.http.response import HTTPResponse +from unihttp.markers import Path +from unihttp.method import BaseMethod + +--8<-- "examples/recipes.py:errors" +``` + +There is deliberately no catch-all `raise_for_status()` here. Letting `5xx` +responses reach middleware allows [status-based retries](../recipes/retries.md) +to run before an exception is raised. + +## Map statuses across endpoints + +Use `ClientError` for `4xx` and `ServerError` for `5xx`. Both inherit from +`HTTPStatusError` and expose `.status_code` and `.response` (the unihttp +`HTTPResponse`, not the backend's raw response). + +These HTTPX examples attach the mapper to the bound method. The same pattern +works with another [client backend](../integrations/backends.md). + +```python +from unihttp.bind_method import bind_method +from unihttp.exceptions import ClientError, ServerError +``` + +=== "Sync" + + ```python + from unihttp.clients.httpx import HTTPXSyncClient + from unihttp.middlewares import SyncErrorMapperMiddleware + + --8<-- "examples/response_errors.py:sync" + ``` + +=== "Async" + + ```python + from unihttp.clients.httpx import HTTPXAsyncClient + from unihttp.middlewares import AsyncErrorMapperMiddleware + + --8<-- "examples/response_errors.py:async" + ``` + +Construct the client with your base URL and serializers as in the quickstart. +To apply the policy to **all endpoints**, pass `middleware=[status_errors]` +(or `[async_status_errors]`) to the client constructor instead of repeating it +on each binding. Client-level middleware wraps method-level middleware. + +Mapping keys accept an integer, a range, or a tuple of integers. An exception +class receives `(message, response)`; use a factory for another constructor, +for example `404: lambda response: UserNotFound("User does not exist")`. +The first matching mapping wins. + +The mapper only sees responses that return from the inner handler. A validation +or error hook that has already raised bypasses status mapping. In this example, +`404` raises `UserNotFound` in the method; other `4xx` and `5xx` reach the mapper. +Unfollowed redirects are not covered by these `4xx`/`5xx` mappings. + +## Catch failures at the call site + +These helpers return `User | None`. They use an already configured client and +the following imports: + +```python +import logging + +from unihttp.exceptions import HTTPStatusError, NetworkError, RequestTimeoutError + +logger = logging.getLogger(__name__) +``` + +=== "Sync" + + ```python + --8<-- "examples/response_errors.py:catch-sync" + ``` + +=== "Async" + + ```python + --8<-- "examples/response_errors.py:catch-async" + ``` + +Only a missing user becomes `None`. Other failures propagate after logging. +The HTTP error log includes the request ID header, when present, to help trace +the failed call without logging its response body. + +The error types describe different stages: + +| Failure | What to handle | +| --- | --- | +| Network failure or timeout | `NetworkError` or `RequestTimeoutError`; do not assume an HTTP response exists. | +| Unsuccessful HTTP status | Exceptions configured by your mapper or error hooks. | +| API error inside a successful HTTP response | Your own exception from `validate_response`, as below. | +| Body does not match the declared result | The configured serializer's loading exception; this is not an HTTP status error. | + +Avoid treating all of these as “user not found” or retrying every exception. + +## Validate an error inside HTTP 200 + +Some APIs return `{"ok": false, "error": "Account disabled"}` with status `200`. +Use `validate_response` to reject that body before model loading: + +```python +--8<-- "examples/response_errors.py:validation" +``` + +This example checks successful statuses only, so a `503` error body can still +reach retry middleware. On success it expects the ordinary `User` payload. +If your API wraps successful data too, combine validation with +[envelope unwrapping](responses.md#unwrap-a-json-envelope). + +For a rule shared by all endpoints, override +`client.validate_response(response, method)` instead. The method hook only takes +`response`. Validation and error hooks remain synchronous `def` methods on +async clients too. + +## Return a fallback deliberately + +`on_error` is a raise-or-continue hook: its return value is ignored. Returning +`None` there does **not** make the client call return `None`. + +Catch a specific exception in application code, as above, or in a regular client +method when the fallback is part of your SDK's public API. A custom +`make_response` can also return a fallback, but only if earlier hooks and +middleware allow that response through. + +## Understand the pipeline + +For a buffered call: + +1. Enter middleware, outermost first: client middleware, then method/call middleware. +2. Send the request and construct `HTTPResponse`. +3. Run `client.validate_response(response, method)`, then `method.validate_response(response)`. +4. If `response.ok` is false, run `method.on_error(response)`, then `client.handle_error(response, method)`. +5. Return through middleware, innermost first. +6. Call `method.make_response(response, response_loader=...)` to produce the public result. + +An exception interrupts the sequence and propagates through the enclosing +middleware. The final `make_response` is outside that chain. + +`response.raise_for_status()` is useful inside a hook when you want immediate +`ClientError`/`ServerError` for `4xx`/`5xx`, but doing so prevents middleware from +retrying by status. Do not add it to the `GetUser` above when following the +[retry recipe](../recipes/retries.md). + +## Return a model with response metadata + +For successful results with headers or status, see +[Response data and metadata](responses.md#return-a-model-with-response-metadata). +[Streaming](streaming.md) has a different lifecycle and no buffered validation. diff --git a/site/guides/index.md b/site/guides/index.md new file mode 100644 index 0000000..5c7ea07 --- /dev/null +++ b/site/guides/index.md @@ -0,0 +1,60 @@ +--- +title: User guide +description: "Find unihttp guides by task: declare requests, configure clients, serialize models, and handle responses, errors, and streaming." +--- + +# User guide + +Start with the part of your client you are working on. Each guide explains the +behavior and links to a focused example or the corresponding API reference. +You do not need to read these pages in order. + +**New to unihttp?** [Install it](../getting-started/installation.md), then follow +either the [sync](../getting-started/quickstart.md) or +[async quickstart](../getting-started/async.md). Both build the same API client. + +## Requests + +Define what each endpoint sends. + +- [Methods and parameters](methods.md): URLs, HTTP verbs, path and query + parameters, headers, JSON bodies, and method binding. +- [Optional fields and Omitted](../recipes/partial-updates.md): distinguish a + missing field from an explicit null. +- [File uploads](../recipes/files.md): send multipart files and form fields. + +## Clients and middleware + +Choose how requests are sent and what runs around each call. + +- [HTTP backends](../integrations/backends.md): compare sync and async clients, + configure sessions, and switch transports. +- [Middleware](middleware.md): apply behavior per client or per method and + understand request/response ordering. +- [Authentication](../recipes/authentication.md): attach bearer tokens through + middleware. + +## Serialization + +Choose how method fields become request data and responses become Python models. + +- [Serialization](serialization.md): connect Adaptix, Pydantic, or msgspec; + customize field names and values; distinguish model conversion from JSON encoding. + +## Responses and errors + +Decide what your client returns and how it handles failures. + +- [Response data and metadata](responses.md): return typed results with status + codes and headers when needed. +- [Error handling](errors.md): validate responses and map HTTP statuses to + application exceptions. +- [Retries](../recipes/retries.md): configure bounded retries and correct + middleware ordering for calls that are safe to repeat. +- [Streaming downloads](streaming.md): consume response chunks and close streams. + +## Need an exact signature? + +The [API reference](../reference/index.md) lists public types, constructor +arguments, protocols, and hooks. Use it for symbol lookup; use these guides for +behavior and examples. diff --git a/site/guides/methods.md b/site/guides/methods.md new file mode 100644 index 0000000..d710ce1 --- /dev/null +++ b/site/guides/methods.md @@ -0,0 +1,100 @@ +--- +title: Define methods and request parameters +description: Map typed dataclass fields to HTTP paths, query strings, headers, JSON, forms, files, and raw request bodies. +--- + +# Define methods and request parameters + +Import from submodules, such as `unihttp.method` and `unihttp.markers`. +The top-level `unihttp` package does not re-export these names. + +A method is a dataclass subclass of `BaseMethod[Result]`. Set `__url__` and +`__method__`, then mark each parameter with its HTTP location. + +## JSON request bodies + +This excerpt defines a method returning a `User`. Import `dataclass` from +`dataclasses`, `Body` from `unihttp.markers`, and `BaseMethod` from +`unihttp.method`. + +```python +--8<-- "examples/recipes.py:models" +``` + +Binding it with `create_user = bind_method(CreateUser)` gives a method that +accepts `name="Ada"` and sends `{"name": "Ada"}`. + +A field `user: Body[User]` sends a **nested** object +`{"user": {"id": 1, "name": "Ada"}}`. Do not assume it flattens the model. + +## Marker reference + +| Marker | Location | Example | +| --- | --- | --- | +| `Path[T]` | URL placeholder | `user_id: Path[int]` | +| `Query[T]` | Query string | `page: Query[int] = 1` | +| `Header[T]` | Request header | `authorization: Header[str]` | +| `Body[T]` | JSON object field | `name: Body[str]` | +| `Form[T]` | Form field | `caption: Form[str]` | +| `File[T]` | Multipart file | `avatar: File[UploadFile]` | +| `Raw[T]` | Entire raw body | `content: Raw[bytes]` | + +Every URL placeholder needs a matching path field. Missing placeholders fail +when building the request. Header wire names and camelCase fields can be +configured with [Adaptix name mapping](serialization.md#rename-fields-without-changing-python-names). + +`Body` cannot be combined with `Form` or `File`. `Raw` cannot be combined +with any of those three. Use `Form` for the scalar fields of a multipart request. + +**Raw bodies currently require Adaptix or a custom dumper.** The Pydantic and +msgspec dumpers do not emit a raw body. See [serialization](serialization.md). + +For an entire byte payload, import `Raw` from `unihttp.markers` and define: + +```python +--8<-- "examples/recipes.py:raw" +``` + +This method sends bytes and expects a JSON acknowledgement such as +`{"size": 7}`. `Raw` controls the **request body only**; the response still passes +through the configured loader. Set an appropriate `Content-Type` header for the +remote endpoint; a raw body does not imply a JSON content type. + +For a binary response, use [streaming](streaming.md), which bypasses response +deserialization, or explicitly customize response processing. Declaring +`BaseMethod[bytes]` alone is not sufficient with the default Adaptix loader: +it expects a base64 string when loading bytes, not a raw HTTP byte payload. + +## Binding and custom methods + +Prefer `bind_method` for a direct endpoint. When you need preprocessing, +compose a normal client method that calls +`self.call_method(CreateUser(name=name.strip()))`. + +`call_method` accepts a method instance and returns the declared result. +It is awaitable on async clients. Streaming uses +[StreamMethod](streaming.md) and `call_method_stream`. + + + +## URL joining + +All built-in unihttp backends combine `base_url` with the method's URL using +`urllib.parse.urljoin` before passing the result to the HTTP library. This is +unihttp's URL handling, not the underlying library's `base_url` behavior. + +With `base_url="https://example.com/api/"`: + +- `/users` resolves to `https://example.com/users`, replacing the `/api/` prefix. +- `users` resolves to `https://example.com/api/users`, preserving the prefix. + +To preserve a path prefix, keep the trailing slash on `base_url` and omit the +leading slash from the method's URL. Without the trailing slash, +`https://example.com/api` combined with `users` resolves to +`https://example.com/users`. + +## Optional fields + +Use [Omitted](../recipes/partial-updates.md) to distinguish an absent parameter +from an explicit `None`. Query encoding of booleans and lists is +backend-dependent; verify it against the target API. diff --git a/site/guides/middleware.md b/site/guides/middleware.md new file mode 100644 index 0000000..b15601f --- /dev/null +++ b/site/guides/middleware.md @@ -0,0 +1,203 @@ +--- +title: Configure and write middleware +description: Write sync and async unihttp middleware, attach it to a client or an individual call, and understand execution order. +--- + +# Configure and write middleware + +Middleware adds behavior around a request without changing your endpoint +definitions. Use it to attach authentication, measure request time, retry a +failure, or inspect a response. + +## Write a middleware + +Let's measure how long a request takes and log its status code. +The middleware calls `next_handler(request)` to continue the request, then +works with the response before returning it to the client. + +=== "Sync" + + ```python + import logging + from time import perf_counter + + from unihttp.http.request import HTTPRequest + from unihttp.http.response import HTTPResponse + from unihttp.middlewares import Handler, Middleware + + logger = logging.getLogger("unihttp.timing") + + + --8<-- "examples/middleware_sync.py:19:30" + ``` + +=== "Async" + + ```python + import logging + from time import perf_counter + + from unihttp.http.request import HTTPRequest + from unihttp.http.response import HTTPResponse + from unihttp.middlewares import AsyncHandler, AsyncMiddleware + + logger = logging.getLogger("unihttp.timing") + + + --8<-- "examples/middleware_async.py:20:33" + ``` + +The code before `next_handler` runs on the way out; the code after it runs on +the way back. Return the response so the client can finish processing it. +For async clients, use `AsyncMiddleware` and await the handler. + +This example logs only requests for which the inner handler returns a response. +If the transport or a response hook raises, the exception passes through +unchanged. It does not log credentials, URLs, or response bodies. + +## Attach it to a client + +Continue with `UserClient` from the [sync quickstart](../getting-started/quickstart.md) +or [async quickstart](../getting-started/async.md), using the matching middleware +above. Import the serializers alongside your other imports: + +```python +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader +``` + +Pass your API's base URL to `main`; the default below points to the local demo API: + +=== "Sync" + + ```python + --8<-- "examples/middleware_sync.py:54:63" + ``` + +=== "Async" + + ```python + --8<-- "examples/middleware_async.py:57:66" + ``` + +Every call through this client now passes through the timing middleware. +It works with any backend that supports the selected sync or async mode. + +If your application has not configured logging, enable INFO messages once at +startup with `logging.basicConfig(level=logging.INFO)`. An example message is +`GET → 200 in 42.1 ms`; the measured time will vary. + +## Choose where it runs + +Use the client constructor for behavior shared by every endpoint. To apply +middleware to just one call, pass it to `call_method` instead: + +=== "Sync" + + ```python + user = client.call_method( + GetUser(user_id=1), + middleware=[TimingMiddleware()], + ) + ``` + +=== "Async" + + ```python + user = await client.call_method( + GetUser(user_id=1), + middleware=[AsyncTimingMiddleware()], + ) + ``` + +These snippets use the quickstart's `GetUser` and an open client. Per-call +middleware is **added to**, not substituted for, client-level middleware. +Do not register the timing middleware at both levels unless you want two +measurements. + +To run it whenever a particular bound method is called, add it to that binding: + +=== "Sync" + + ```python + get_user = bind_method(GetUser, middleware=[TimingMiddleware()]) + ``` + +=== "Async" + + ```python + get_user = bind_method(GetUser, middleware=[AsyncTimingMiddleware()]) + ``` + +Replace the `get_user` declaration inside your client class with this line. +A direct `client.call_method(GetUser(...))` does not use middleware attached to +the binding. The same per-call mechanism is available on `call_method_stream`. + +## Scope and ordering + +Middleware runs in list order on the request and in reverse order on the +response. Client-level middleware wraps per-call or bound-method middleware: + +```text +Request: client middleware → call/binding middleware → transport +Response: client middleware ← call/binding middleware ← transport +``` + +For a list `[A, B]`, A runs first and receives B's response. This matters when +combining [retries](../recipes/retries.md) with +[error mapping](errors.md#map-statuses-across-endpoints): an outer error mapper can act +on the final response after an inner retry middleware has finished. + +Response validation and error hooks run inside the chain. The final +`make_response` step, which loads the declared return type, runs after +middleware returns. For streaming calls, timing ends when the stream is +returned, not when the caller has consumed the download. + +## Built-in middleware + +You do not need to write your own middleware for these common tasks: + +| Purpose | Sync | Async | +| --- | --- | --- | +| Status mapping | `SyncErrorMapperMiddleware` | `AsyncErrorMapperMiddleware` | +| Retries | `RetryMiddleware` | `AsyncRetryMiddleware` | +| Logging | `LoggingMiddleware` | `AsyncLoggingMiddleware` | + +Import these from `unihttp.middlewares`. See [error handling](errors.md) and +[retries](../recipes/retries.md) for configuration, or +[authentication](../recipes/authentication.md) for a middleware that adds a token. + +When modifying headers, use `request.header` (singular) for the outgoing +request and `response.headers` (plural) for the response. Avoid logging +credentials or sensitive payloads. + +## Run the standalone examples + +The repository's middleware examples each contain their own model, method, +client, and entry point. They do not import another example. Install +`unihttp[httpx,adaptix]`, then start the demo API in a separate terminal: + +```bash +python examples/demo_api.py +``` + +Run either timing example: + +=== "Sync" + + ```bash + python examples/middleware_sync.py + ``` + +=== "Async" + + ```bash + python examples/middleware_async.py + ``` + +Each prints the user and logs the request's status and elapsed time. + +For a concrete scoping example, run `python examples/middleware_scope.py`. +It adds a fresh `X-Request-ID` to every request and sets `Cache-Control: no-cache` +only on the bound method and the explicit call that opts in. A direct call +without that middleware receives only the request ID. `no-cache` asks caches +to revalidate a stored response; it does not prohibit storing it. diff --git a/site/guides/responses.md b/site/guides/responses.md new file mode 100644 index 0000000..a649b60 --- /dev/null +++ b/site/guides/responses.md @@ -0,0 +1,148 @@ +--- +title: Work with response data and metadata +description: Return typed models and lists, unwrap JSON envelopes, and include HTTP status codes and headers in unihttp results. +--- + +# Work with response data and metadata + +A regular, buffered call returns your declared Python result. You work with a +`User` or `list[User]`, rather than an HTTP response object. + +This page builds on the [quickstart](../getting-started/quickstart.md). Configure +[HTTP error handling](errors.md#map-statuses-across-endpoints) before loading +responses: unihttp does not raise for unsuccessful statuses by default. + +## Return a typed model or list + +Given a response model: + +```python +from dataclasses import dataclass + +--8<-- "examples/response_metadata.py:model" +``` + +A `BaseMethod[User]` returns a `User`. For a JSON array such as +`[{"id": 1, "name": "Ada"}]`, declare `list[User]` instead: + +```python +from unihttp.method import BaseMethod + +--8<-- "examples/response_metadata.py:list" +``` + +Bind it with `list_users = bind_method(ListUsers)` on your client: + +=== "Sync" + + ```python + users = client.list_users() + for user in users: + print(user.name) + ``` + +=== "Async" + + ```python + users = await client.list_users() + for user in users: + print(user.name) + ``` + +The configured response loader converts the body into the declared type. +See [serialization](serialization.md) for model support and field conversions. +Changing the return type does not change what the remote API sends. + +## Unwrap a JSON envelope + +If the API returns `{"data": {"id": 1, "name": "Ada"}}`, but callers should +receive just `User`, configure the response serializer once. With Adaptix, add +a loader that extracts `data` before normal model loading: + +```python +from operator import itemgetter + +from adaptix import Chain, loader +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixLoader + +--8<-- "examples/response_metadata.py:envelope-loader" +``` + +Pass `response_loader=envelope_loader` when constructing the client. Keep your +request dumper unchanged. `Chain.FIRST` passes the extracted payload to Adaptix's +existing `User` loader, preserving its field conversion and validation. + +The method only declares the result type; it does not need `make_response`: + +```python +from unihttp.markers import Path + +--8<-- "examples/response_metadata.py:envelope" +``` + +Bind `GetWrappedUser` as usual. The same response loader works with sync and async +clients and any method returning this wrapped `User`. + +The rule targets **the type, not a particular endpoint**: every `User` loaded +by this Retort must have a `data` wrapper, including users nested in other models +or lists. It does not unwrap an envelope around an entire `list[User]`. If the +same API also returns plain users, use a separate response type for wrapped users +or a separate client/loader configuration. The plain array example above uses +the default loader, not `envelope_loader`. + +This loader changes loading only; it does not add a wrapper when dumping `User`. +For the underlying mechanism, see Adaptix's +[provider chaining](https://adaptix.readthedocs.io/en/latest/loading-and-dumping/tutorial.html#provider-chaining). +Handle API-specific error envelopes with +[`validate_response`](errors.md#validate-an-error-inside-http-200) before loading. + +## Return a model with response metadata + +When callers need the status or a header alongside the body, declare a wrapper +as the method's result. Unlike a JSON envelope, HTTP metadata is not part of the +body passed to the serializer, so this is a use case for `make_response`. +Here the API returns plain user JSON and the client uses the default response +loader from the quickstart, without the envelope recipe above: + +```python +from unihttp.http.response import HTTPResponse +from unihttp.serialize import ResponseLoader + +--8<-- "examples/response_metadata.py:metadata" +``` + +The hook loads the body into `User`, then adds the status and `X-Request-ID` +header. A missing header becomes `None`. After binding this `GetUser`: + +=== "Sync" + + ```python + result = client.get_user(user_id=1) + print(result.user.name, result.status_code, result.request_id) + ``` + +=== "Async" + + ```python + result = await client.get_user(user_id=1) + print(result.user.name, result.status_code, result.request_id) + ``` + +`HTTPResponse` also exposes `.cookies` and `.data`; see +[HTTP types](../reference/http.md) for all fields. + +## How custom response loading works + +`make_response` remains a regular `def`, even on async clients. Keep the parameter +name `response_loader`: the client passes it by keyword. + +This hook runs after validation, error handling, and the middleware chain. +Exceptions from the final conversion propagate to the caller; middleware does +not intercept or retry them. See [the response pipeline](errors.md#understand-the-pipeline) +for the complete order. + +## When the response is a stream + +Streaming calls return `HTTPResponse` directly, with a stream in `.data`. +They do not call `make_response` or the buffered response loader. See +[streaming downloads](streaming.md) for reading and closing them safely. diff --git a/site/guides/serialization.md b/site/guides/serialization.md new file mode 100644 index 0000000..98c52ff --- /dev/null +++ b/site/guides/serialization.md @@ -0,0 +1,231 @@ +--- +title: Serialization +description: Choose Adaptix, Pydantic, or msgspec for unihttp. Configure field names, custom value conversion, typed responses, and the HTTP JSON codec. +--- + +# Serialization + +**Adaptix is the recommended serializer for new unihttp clients.** It works +with plain dataclasses and TypedDicts, keeps conversion rules outside your +models, and supports field-name mapping and raw request bodies. + +If your application already uses Pydantic or msgspec models, reuse them with +the matching integration. Adaptix is a recommendation, not an automatic default: +you explicitly configure a `request_dumper` and a `response_loader`. + +| Integration | Choose it when | +| --- | --- | +| **Adaptix — recommended** | You want dataclasses or TypedDicts and configurable request/response conversion. | +| Pydantic | You already use `BaseModel` response models and their validation rules. | +| msgspec | You already use `msgspec.Struct` response models. | + +## Connect a serializer + +The **dumper** converts a method instance into request components such as +query parameters and body fields. The **loader** converts a parsed response +body into the method's declared result type. + +Choose the serializer extra alongside your HTTP backend in +[Installation](../getting-started/installation.md). The following alternatives +all describe the same endpoint: send a user name and receive a typed `User`. +Method declarations remain dataclasses in every variant. + +=== "Adaptix" + + ```python + --8<-- "examples/serialization/adaptix.py:setup" + ``` + +=== "Pydantic" + + ```python + --8<-- "examples/serialization/pydantic.py:setup" + ``` + +=== "msgspec" + + ```python + --8<-- "examples/serialization/msgspec.py:setup" + ``` + +Pass `request_dumper` and `response_loader` to your client constructor, as in +the [quickstart](../getting-started/quickstart.md). You can bind `CreateUser` +with `bind_method` or pass an instance to `call_method`. + +In all three variants: + +- `CreateUser(user_name="Ada")` produces the body fields `{"user_name": "Ada"}`. +- A response `{"id": 1, "user_name": "Ada"}` becomes a `User` instance. +- The serializer choice does not depend on the HTTP backend or sync/async mode. + + + +## Customize Adaptix + +A **retort** holds Adaptix's loading and dumping rules. Start from unihttp's +`DEFAULT_RETORT`: it includes support for request markers, omitted fields, +uploads, and raw request bodies. By default it also ignores extra response +fields, so your DTO can model only the data your application needs. + +Use `DEFAULT_RETORT.extend(recipe=[...])` to add rules while retaining these +integrations. It returns a new retort without modifying the original. +Create it once during client setup and reuse it for subsequent calls. + +The examples below use `User` and `CreateUser` from the **Adaptix** tab above. + +### Rename fields without changing Python names + +Suppose the API uses `userName`, but your Python fields use `user_name`. +Import `name_mapping` from `adaptix` and configure both directions: + +```python +--8<-- "examples/serialization/customization.py:global-mapping" +``` + +Now `CreateUser(user_name="Ada")` produces `{"userName": "Ada"}`, and +`{"id": 1, "userName": "Ada"}` loads as `User(id=1, user_name="Ada")`. + +This rule applies to every model and method field named `user_name` handled +by that retort. If only these two types use the API's spelling, scope the rule: + +```python +--8<-- "examples/serialization/customization.py:scoped-mapping" +``` + +Use `AdaptixDumper(scoped_retort)` and `AdaptixLoader(scoped_retort)` with this +variant. Mapping the response model alone does not rename fields declared on +the request method: both classes need a rule. + +### Transform a value before sending it + +You can also change a field's value without changing the method definition. +For example, trim surrounding whitespace from a user name before sending it. +Import `P` and `dumper` from `adaptix`: + +```python +--8<-- "examples/serialization/customization.py:normalize" +``` + +`P[CreateUser].user_name` selects that field on that method only. +The new retort extends the name-mapping example, so +`CreateUser(user_name=" Ada ")` produces `{"userName": "Ada"}`. + +The method instance is not mutated. This is a dumping rule: it does not trim +names when loading a response. Use a `loader` rule for input conversion. + +### Read and write a custom wire format + +Suppose an events API sends Unix timestamps, while your Python code uses +timezone-aware `datetime` values. Add these imports: + +```python +from datetime import UTC, datetime + +from adaptix import P, dumper, loader +``` + +Define the response model and request method using the Python type: + +```python +--8<-- "examples/serialization/customization.py:event-models" +``` + +Then configure the response field's loader and the request field's dumper: + +```python +--8<-- "examples/serialization/customization.py:timestamps" +``` + +| Direction | Input | Converted value | +| --- | --- | --- | +| Response → model | `{"id": 1, "starts_at": 1704067200}` | `Event(id=1, starts_at=datetime(2024, 1, 1, tzinfo=UTC))` | +| Method → body | `CreateEvent(starts_at=datetime(2024, 1, 1, tzinfo=UTC))` | `{"starts_at": 1704067200.0}` | + +Use aware datetimes so the timestamp does not depend on the machine's local +timezone. Custom conversion functions are responsible for accepting and +validating the API's wire format; these rules do not change unrelated fields. + +For more recipes and selection rules, see the official +[Adaptix loading and dumping tutorial](https://adaptix.readthedocs.io/en/latest/loading-and-dumping/tutorial.html) +and [name-mapping reference](https://adaptix.readthedocs.io/en/latest/loading-and-dumping/extended-usage.html#name-mapping). + +## What is shared, and what differs + +### Optional and nested fields + +All three integrations support ordinary marked request fields. With the +documented `Omittable[T] = Omitted()` pattern, they omit the field instead of +sending the sentinel. See [Optional fields and Omitted](../recipes/partial-updates.md) +for query, header, and body examples; omission is not specific to PATCH. + +A field such as `user: Body[User]` produces a nested `user` object. +It does not flatten the model into the outer request body. + +### Validation errors + +Response model validation or conversion errors propagate from the chosen +serialization library. A successful HTTP status does not guarantee that the +response matches your model. See [error handling](errors.md) for where +validation and response loading occur in the request pipeline. + + + +### Pydantic specifics + +The loader uses Pydantic's `TypeAdapter` to validate the declared response +type, including your `BaseModel` configuration. The request dumper uses +the method dataclass's field names as request keys. An alias on a response +model does not rename a separate method field. + +See [Pydantic's documentation](https://docs.pydantic.dev/latest/) for model +validation and aliases. + + + +### msgspec specifics + +The request dumper converts field values with `msgspec.to_builtins`; the loader +uses `msgspec.convert` to construct your declared response type. +Selecting these classes does not switch the HTTP client's JSON codec to +`msgspec.json`. + +See [msgspec's documentation](https://jcristharif.com/msgspec/) for model +configuration and conversion behavior. + +### Raw request bodies + +Adaptix supports `Raw` fields. The Pydantic and msgspec dumpers currently +populate path, query, header, body, file, and form data, but not `raw`. +For raw payloads, use Adaptix or implement your own +[request dumper](../reference/serializers.md). + +## Unwrap a response envelope + +If an API wraps its payload in `data`, configure an Adaptix loader with +`Chain.FIRST` to extract it before model loading. This keeps the transformation +in the Retort instead of repeating it in each method's `make_response`. +See [Unwrap a JSON envelope](responses.md#unwrap-a-json-envelope) for the recipe, +client configuration, and type-scoping considerations. + +## JSON codec versus model serialization + +`json_dumps` and `json_loads` control the HTTP transport's JSON encoding and +decoding. They do not replace the dumper that extracts request fields or the +loader that constructs your response model. + +For example, install `orjson`, import it, and add these arguments to your +existing client constructor: + +```python +--8<-- "examples/json_codec.py:codec" +``` + +Keep the same `request_dumper` and `response_loader`. The dump callable must +return a string, which is why the example decodes the bytes returned by +`orjson.dumps`. + +An empty response may be represented as `None`, and non-JSON response handling +depends on the backend. Make your method's response handling match the API; +choosing a JSON codec does not turn arbitrary response bytes into a typed model. +For binary downloads, use [streaming](streaming.md). For response headers and +status alongside a model, see [Response data and metadata](responses.md). diff --git a/site/guides/streaming.md b/site/guides/streaming.md new file mode 100644 index 0000000..4369131 --- /dev/null +++ b/site/guides/streaming.md @@ -0,0 +1,117 @@ +--- +title: Stream HTTP response bodies +description: Consume unihttp downloads incrementally, reject failed responses, and close sync or async streams even when reading fails. +--- + +# Stream HTTP response bodies + +Use `StreamMethod` to consume a response without loading the whole body into +memory. The call returns an `HTTPResponse` with status and headers available; +`.data` is a `ChunkStream` or `AsyncChunkStream` of bytes. + +## Define a download method + +Handle unsuccessful statuses in the method so a failed download cannot silently +look like an empty successful response: + +```python +from dataclasses import dataclass + +from unihttp.exceptions import HTTPStatusError +from unihttp.http.response import HTTPResponse +from unihttp.markers import Path +from unihttp.method import StreamMethod + +--8<-- "examples/response_streaming.py:method" +``` + +`on_error` runs only for non-2xx responses. `raise_for_status()` raises +`ClientError` for `4xx` and `ServerError` for `5xx`; the final raise also rejects +other unsuccessful statuses, including an unfollowed redirect. + +Bind the method with `download_file = bind_method(DownloadFile)` on your sync +`FileClient` or async `AsyncFileClient`. Import `bind_method` from +`unihttp.bind_method`; it chooses the streaming path automatically. Configure +the client as in the [quickstart](../getting-started/quickstart.md) and keep it +open until reading finishes. + +## Read and close a stream + +For example, calculate a download's SHA-256 checksum one chunk at a time. +These functions take an already configured, open client: + +```python +from hashlib import sha256 +``` + +=== "Sync" + + ```python + --8<-- "examples/response_streaming.py:sync" + ``` + +=== "Async" + + ```python + --8<-- "examples/response_streaming.py:async" + ``` + +The stream context manager closes the underlying response when reading finishes, +raises, or exits early. Use it even if you only need the first few chunks. +The functions return a checksum only after the whole stream has been read; +request and read failures propagate to the caller. + +Keep the separate `response` variable when you also need `.headers` or +`.status_code`. For file downloads, your consumer can write each chunk to a file; +only publish the completed file after the entire read succeeds. Async consumers +should avoid blocking file I/O on the event loop. + +## Choose the chunk size + +Pass `__chunk_size__=8192` when calling the bound method or constructing +`DownloadFile(file_id=1, __chunk_size__=8192)`. The default is 65536 bytes. + +For an explicit unbound call, use +`client.call_method_stream(DownloadFile(file_id=1))`, awaiting it on an async +client. Do not use the buffered `call_method` for a `StreamMethod`. + +## Errors and parsing + +There are two places a download can fail: opening the response and consuming +its body. A `try/except` must cover both, not just `client.download_file(...)`. +For the helpers above, catch around the entire `download_checksum(...)` call +(or its awaited async equivalent): + +- `HTTPStatusError` covers rejected statuses, including the `ClientError` and + `ServerError` subclasses raised by this method. +- `NetworkError` and `RequestTimeoutError` can occur while opening or reading. +- Exceptions from your own consumer also propagate; the stream context still + closes the response. + +Import these exceptions from `unihttp.exceptions`. See +[Error handling](errors.md#catch-failures-at-the-call-site) for catch patterns. + +### Error bodies are not buffered + +Streaming skips `validate_response`, `make_response`, and the response loader. +For any non-2xx status, the client closes the stream **before** calling +`method.on_error` and `client.handle_error`. Those hooks can inspect status and +headers, but cannot read the error body from the closed stream. + +The default hooks do not raise: without the explicit handling above, a `404` +can return a stream yielding no chunks. If you need to parse an API's error +body, use a buffered method instead. + +### Chunks are not messages + +Chunks contain bytes, not complete JSON documents, lines, or SSE events. A chunk +boundary can even split a multi-byte character. Incremental decoding and message +framing belong in your consumer. + +### Retries do not resume a download + +The [buffered retry recipe](../recipes/retries.md) cannot resume an interrupted +download and should not be attached to this method. A retry strategy needs to +close the previous response and decide whether to restart or resume using a +mechanism supported by the server. Discard partial output unless your consumer +explicitly supports resuming it. diff --git a/site/index.md b/site/index.md new file mode 100644 index 0000000..7ff6e86 --- /dev/null +++ b/site/index.md @@ -0,0 +1,210 @@ +--- +title: unihttp – modern library for creating declarative API clients +description: Build declarative Python API clients with unihttp, typed methods, sync and async HTTP backends, and your preferred serializer. +hide: + - toc + - path +--- + +
+ +
+ +Python API clients, thoughtfully structured. +{ .uh-eyebrow } + +# unihttp – modern library for creating declarative API clients + +Describe an endpoint once. Call it as a typed Python method. +Keep your HTTP transport and response models separate. +{ .uh-lead } + +
+ +[Build your first client](getting-started/quickstart.md){ .md-button .md-button--primary } +[Installation & extras →](getting-started/installation.md){ .uh-secondary } + +
+ +Sync & async clients · Explicit request parameters · Pluggable serializers +{ .uh-summary } + +
+ +
+ +
+ +## An endpoint you can read. + +The URL, parameters, and result type live together in a small dataclass. +`bind_method` exposes it on your client with a typed call signature. + +1. **Declare the result.** `User` describes the response your code receives. +2. **Describe the request.** `Path[int]` places `user_id` in the URL. +3. **Bind the method.** `get_user(user_id=1)` returns a `User` with the configured response loader; await the call with async clients. + +Choose an HTTP library in the tabs. The models stay the same; the client changes. +These excerpts omit shared imports and configuration. See the complete +[sync](getting-started/quickstart.md) or [async](getting-started/async.md) example +to run against a local demo API. aiohttp is async-only. +{ .uh-caption } + +
+ +
+ +Endpoint & client · Python +{ .uh-code-label } + +=== "HTTPX" + + ```python + --8<-- "examples/backends/httpx_sync.py:backend-import" + + --8<-- "examples/backends/httpx_sync.py:models" + + + --8<-- "examples/backends/httpx_sync.py:binding" + ``` + +=== "requests" + + ```python + --8<-- "examples/backends/requests_sync.py:backend-import" + + --8<-- "examples/backends/requests_sync.py:models" + + + --8<-- "examples/backends/requests_sync.py:binding" + ``` + +=== "aiohttp" + + ```python + --8<-- "examples/backends/aiohttp_async.py:backend-import" + + --8<-- "examples/backends/aiohttp_async.py:models" + + + --8<-- "examples/backends/aiohttp_async.py:binding" + ``` + +=== "HTTPX2" + + ```python + --8<-- "examples/backends/httpx2_sync.py:backend-import" + + --8<-- "examples/backends/httpx2_sync.py:models" + + + --8<-- "examples/backends/httpx2_sync.py:binding" + ``` + +=== "niquests" + + ```python + --8<-- "examples/backends/niquests_sync.py:backend-import" + + --8<-- "examples/backends/niquests_sync.py:models" + + + --8<-- "examples/backends/niquests_sync.py:binding" + ``` + +=== "zapros" + + ```python + --8<-- "examples/backends/zapros_sync.py:backend-import" + + --8<-- "examples/backends/zapros_sync.py:models" + + + --8<-- "examples/backends/zapros_sync.py:binding" + ``` + +=== "urllib" + + ```python + --8<-- "examples/backends/urllib_sync.py:backend-import" + + --8<-- "examples/backends/urllib_sync.py:models" + + + --8<-- "examples/backends/urllib_sync.py:binding" + ``` + + +
+ +
+ +
+ +## Your API contract. Your stack. + +Method definitions describe the API, not the transport. Choose an HTTP client +for your application and a serializer for your models. + +
+ +
+ +### HTTP transport + +HTTPX, aiohttp, requests, niquests, zapros, or the standard-library urllib. +Use a sync or async client where supported by the backend. + +[Compare HTTP backends →](integrations/backends.md) + +
+ +
+ +### Model serialization + +Use dataclasses with Adaptix, or integrate your Pydantic and msgspec models. +Configure request dumping and response loading explicitly. + +[Choose a serializer →](guides/serialization.md) + +
+ +
+ +
+ +
+ +## Build beyond the first request. + +
+ +[**Define your API** Map query parameters, JSON bodies, headers, and files. ](guides/methods.md) + +[**Go asynchronous** Use async clients, context managers, and middleware. ](getting-started/async.md) + +[**Handle failures** Choose how HTTP errors become application exceptions. ](guides/errors.md) + +[**Add authentication** Apply a bearer token through request middleware. ](recipes/authentication.md) + +[**Stream a response** Read downloads incrementally and close streams safely. ](guides/streaming.md) + +[**Look up the API** Find exact signatures, types, and extension points. ](reference/index.md) + +
+ +[Browse the user guide →](guides/index.md) + +
+ +
+ +**When unihttp fits** + +Use it for a reusable API client or SDK with explicit endpoint contracts. +For a one-off request, calling your HTTP library directly may be sufficient. + +
+ +
diff --git a/site/integrations/backends.md b/site/integrations/backends.md new file mode 100644 index 0000000..bf02014 --- /dev/null +++ b/site/integrations/backends.md @@ -0,0 +1,48 @@ +--- +title: Choose an HTTP backend +description: Compare unihttp sync and async client classes and installation extras for HTTPX, aiohttp, requests, niquests, zapros, and urllib. +--- + +# Choose an HTTP backend + +The endpoint dataclasses are independent of the HTTP client. Select a backend +that fits your application and install its extra alongside your serializer. + +| Backend module | Sync class | Async class | HTTP extra | +| --- | --- | --- | --- | +| `unihttp.clients.httpx` | `HTTPXSyncClient` | `HTTPXAsyncClient` | `httpx` | +| `unihttp.clients.httpx2` | `HTTPX2SyncClient` | `HTTPX2AsyncClient` | `httpx2` | +| `unihttp.clients.aiohttp` | — | `AiohttpAsyncClient` | `aiohttp` | +| `unihttp.clients.requests` | `RequestsSyncClient` | — | `requests` | +| `unihttp.clients.niquests` | `NiquestsSyncClient` | `NiquestsAsyncClient` | `niquests` | +| `unihttp.clients.zapros` | `ZaprosSyncClient` | `ZaprosAsyncClient` | `zapros` | +| `unihttp.clients.urllib` | `UrllibSyncClient` | — | None | + +HTTPX is used in the tutorials because it supports both sync and async clients +and an in-process mock transport. Use aiohttp in an existing aiohttp application, +or retain requests when integrating with a synchronous requests-based codebase. + +The urllib transport uses the standard library. That removes an HTTP dependency, +but model serialization may still require a serializer dependency. + +## Transport configuration + +Backend-specific constructor arguments are listed in the +[client reference](../reference/clients.md). Where a session argument is +available, use it for backend configuration such as connection limits and +timeouts. Do not assume every backend accepts identical session parameters or +supports identical HTTP protocol versions. + +HTTPX clients close supplied sessions as well as internally created sessions. +Check the selected client's lifecycle before sharing a session with other code. + +## Switching backends + +Keep method definitions, then change the client base class, installed extra, +and any backend-specific session setup. When moving between sync and async, +also change context managers, awaits, and middleware variants. + +The shared API does not make all wire behavior identical. In particular, +verify query encoding, multipart uploads, exception translation, and streaming +against your API. The repository's integration tests cover common behavior; +they are not a guarantee for every transport option. diff --git a/site/project/agent-skills.md b/site/project/agent-skills.md new file mode 100644 index 0000000..9a6c319 --- /dev/null +++ b/site/project/agent-skills.md @@ -0,0 +1,35 @@ +--- +title: unihttp agent skills +description: Find the repository's unihttp guidance and SDK-generation skills for coding agents, with version-aware API documentation. +--- + +# unihttp agent skills + +The repository includes two skills: + +- [unihttp](https://github.com/goduni/unihttp/tree/master/.agents/skills/unihttp): + conventions for imports, method declarations, serializers, middleware, and + client lifecycle. +- [unihttp-client](https://github.com/goduni/unihttp/tree/master/.agents/skills/unihttp-client): + instructions for generating a typed client package from an OpenAPI description + or an API description. + +Each skill is a directory containing a `SKILL.md` and supporting references. +Install it using your agent's supported skill mechanism. For a project-local +installation, copy the selected directories from `.agents/skills/` into the +skill directory used by your agent. + +A skill is guidance for a coding agent; it is not an automatic runtime feature +of unihttp. Review generated clients against the API contract and run their +tests. + +## Version-aware context + +Use skills and documentation from the same revision as your library whenever +possible. Development guidance can refer to features absent from an older +release. + +The published site also provides `llms.txt` and a Markdown representation of +each page under `markdown/`. These are generated from the rendered +documentation, including expanded code snippets and API reference text. +They are convenient inputs for agents, not a promise of search visibility. diff --git a/site/project/documentation.md b/site/project/documentation.md new file mode 100644 index 0000000..d42d856 --- /dev/null +++ b/site/project/documentation.md @@ -0,0 +1,144 @@ +--- +title: Contributing to unihttp +description: Set up unihttp for development, add regression tests, run code checks, and submit a pull request to the library. +--- + +# Contributing to unihttp + +Help improve unihttp with a bug fix, a clearer type signature, a backend or +serializer improvement, or a better example. Small, focused contributions are +welcome; documentation changes follow the same pull-request workflow as code. + +## Before you start + +Check [existing issues](https://github.com/goduni/unihttp/issues) and +[pull requests](https://github.com/goduni/unihttp/pulls) for related work. +For a new feature or a change to the public API, open an issue first to discuss +the use case, proposed interface, and alternatives. + +For a bug report, include: + +- A minimal example that reproduces the problem. +- Expected and actual behavior, including a relevant traceback. +- Python and unihttp versions, plus the HTTP backend and serializer in use. + +Remove credentials and private response data from reports. For a suspected +vulnerability, follow the [security policy](https://github.com/goduni/unihttp/blob/master/.github/SECURITY.md) +instead of opening a public issue. Follow the project's +[code of conduct](https://github.com/goduni/unihttp/blob/master/.github/CODE_OF_CONDUCT.md) +in discussions and reviews. + +## Set up your environment + +You need Git, uv, and Python 3.12–3.14. Fork the repository on GitHub, then +replace `YOUR-USERNAME` with your account name: + +```bash +git clone https://github.com/YOUR-USERNAME/unihttp.git +cd unihttp +git switch -c fix/describe-your-change +uv sync --group dev --group docs +``` + +The `dev` group installs the supported optional integrations, test tools, Ruff, +and mypy. The `docs` group adds the documentation builder and its checks. +Run the commands below from the repository root. + +## Find the right place + +- `src/unihttp/` — method definitions, binding, markers, and shared HTTP types. +- `src/unihttp/clients/` — sync and async HTTP backend adapters. +- `src/unihttp/serializers/` — Adaptix, Pydantic, and msgspec integrations. +- `src/unihttp/middlewares/` — middleware interfaces and implementations. +- `tests/test_core/`, `tests/test_clients/`, and `tests/test_features/` — focused + tests for the corresponding parts of the library. +- `tests/test_integration/` — tests that exercise components together. +- `examples/` and `site/` — runnable examples and public documentation. + +Start with nearby implementations and tests. Keep changes scoped to the issue; +avoid unrelated refactoring or formatting in the same pull request. + +## Add tests for the change + +For a bug fix, add a regression test that fails before the fix. For new behavior, +cover the expected result and relevant failure cases. If a change affects a +shared contract, check the applicable sync/async clients or serializers, not +just the integration used in your first example. + +Run a focused test while iterating, for example: + +```bash +uv run --group docs pytest tests/test_core/test_method.py -q +``` + +Use mocks or a local test server where practical. Tests should not depend on +private credentials or a third-party API being available. + +## Run the checks + +Before opening a pull request, run the checks used by the library's CI: + +```bash +uv run --group docs ruff check +uv run --group docs ruff format --check +uv run --group docs mypy +uv run --group docs pytest --cov src --cov-fail-under=80 +``` + +CI runs the library checks on Python 3.12, 3.13, and 3.14 and requires at least +80% test coverage. Including `--group docs` locally also enables the documentation +tests instead of skipping them when their dependencies are absent. + +For local library tests across all three Python versions, use the Nox sessions +configured in `noxfile.py`: + +```bash +uv run --group docs nox +``` + +Nox creates separate test environments. The Python interpreters need to be +available; run the checks on your current interpreter first for faster feedback. + +## Documentation + +Update the relevant guide, API docstring, or example when changing public +behavior. Public pages live in `site/`, runnable examples in `examples/`, and +navigation in `zensical.toml`. Internal notes under `docs/` are not published. + +Preview the site locally: + +```bash +uv run --group docs zensical serve +``` + +Open `http://localhost:8000`. To validate the complete site and its examples: + +```bash +uv run --group docs pytest tests/test_docs_examples.py tests/test_docs_serialization.py tests/test_docs_responses.py tests/test_docs_build.py -q +uv run --group docs python scripts/build_docs.py +``` + +The full build checks links, anchors, and API reference output, then generates +Markdown exports and `llms.txt`. Output goes to `.build/docs/`; do not edit +generated files or use `site/` as the output directory. + +Give each page a title, description, and one top-level heading. Keep existing +URLs where possible. Include tested examples from `examples/` instead of +copying code into Markdown. Use the existing backend tabs for client-specific +alternatives, with consistent library labels across pages. + +## Open a pull request + +Push your branch to your fork and open a pull request against `master` in +[goduni/unihttp](https://github.com/goduni/unihttp). In the description: + +1. Explain the problem and the change; link the relevant issue. +2. Include a small usage example if the public interface changes. +3. Describe the tests you added and the checks you ran. +4. Call out breaking changes and any migration steps explicitly. + +Review your diff and complete the repository's pull-request checklist. If you +change dependencies in `pyproject.toml`, run `uv sync --group dev --group docs` +and re-run the relevant checks. The generated `uv.lock` stays local and is not +committed. Watch CI and respond to review feedback; keep follow-up changes +focused on the same task. diff --git a/site/project/releases.md b/site/project/releases.md new file mode 100644 index 0000000..8dfa99a --- /dev/null +++ b/site/project/releases.md @@ -0,0 +1,44 @@ +--- +title: Versions and migration +description: Understand unihttp development documentation, release documentation, and how to check API changes before upgrading. +--- + +# Versions and migration + +The `latest` Read the Docs version tracks `master`. It may document changes +that have not been published to PyPI. The package version in the source metadata +alone does not establish that every change is already released. + +Use [GitHub releases](https://github.com/goduni/unihttp/releases) and +[PyPI](https://pypi.org/project/unihttp/) to identify published versions. +Compare the installed version with `python -m pip show unihttp`. + +## Match documentation to your installation + +Use documentation for your installed release when that version is available. +`stable`, when available, describes the current published release; `latest` +describes the development branch. Older releases may not have a documentation +site, so consult the README and source at their Git tag. + +The current source supports Python 3.12–3.14. For another release, check that +release's package metadata rather than assuming the same Python requirements. +HTTP backends and serializers are optional dependencies with their own version +requirements. + +## Upgrade checklist + +Before upgrading, read the release notes and check the client backend, +serialization behavior, and any overridden response hooks. Run your API contract +tests, including errors and streaming cleanup. + +When checking your client code, pay particular attention to these contracts: + +- Pass `AdaptixDumper(DEFAULT_RETORT)` and `AdaptixLoader(DEFAULT_RETORT)` + explicitly, not the retort itself. +- `call_method` returns the declared model, not an HTTP response wrapper. +- Returning a value from `on_error` does not replace the method's result. +- Extend Adaptix using `DEFAULT_RETORT.extend(recipe=[...])`. + +These describe current behavior, not a list of changes introduced in a specific +release. Version-specific changes belong to the linked release notes. See +[errors](../guides/errors.md) and [serialization](../guides/serialization.md) for examples. diff --git a/site/recipes/authentication.md b/site/recipes/authentication.md new file mode 100644 index 0000000..ef3fec4 --- /dev/null +++ b/site/recipes/authentication.md @@ -0,0 +1,30 @@ +--- +title: Add bearer authentication +description: Attach bearer tokens to unihttp requests with a typed middleware and keep credentials out of method declarations. +--- + +# Add bearer authentication + +Use middleware to attach a token to every request. This excerpt needs +`HTTPRequest` from `unihttp.http.request`, `HTTPResponse` from +`unihttp.http.response`, and `Handler, Middleware` from +`unihttp.middlewares.base`. + +```python +--8<-- "examples/recipes.py:auth" +``` + +Pass `middleware=[BearerAuth(token)]` to your client constructor, where +`token` comes from your application's configuration or credential provider. +For a reusable SDK, accept the token in its client constructor and attach the +middleware there. + +For async clients, subclass `AsyncMiddleware`, use `AsyncHandler`, make +`handle` async, and return `await next_handler(request)`. + +For authentication on a single endpoint, bind that method with its own +middleware. See [scope and ordering](../guides/middleware.md). + +This recipe attaches a token; it does not implement OAuth token refresh. +If refresh is needed, design expiry, synchronization, and replay behavior +around the remote API's authentication contract. diff --git a/site/recipes/files.md b/site/recipes/files.md new file mode 100644 index 0000000..252bfc6 --- /dev/null +++ b/site/recipes/files.md @@ -0,0 +1,52 @@ +--- +title: Upload files with multipart forms +description: Send a file and form fields with unihttp File, Form, and UploadFile, including filenames and content types. +--- + +# Upload files with multipart forms + +Use `File` for the binary payload and `Form` for associated scalar fields. +With `User` as the response model, define: + +```python +--8<-- "examples/recipes.py:upload" +``` + +The declaration above needs these imports, plus the `User` response model from +the [quickstart](../getting-started/quickstart.md): + +```python +from dataclasses import dataclass + +from unihttp.bind_method import bind_method +from unihttp.http import UploadFile +from unihttp.markers import File, Form, Path +from unihttp.method import BaseMethod +``` + +Bind it as +`upload_avatar = bind_method(UploadAvatar)`. + +With a configured client: + +```python +from unihttp.http import UploadFile + +user = client.upload_avatar( + user_id=1, + caption="portrait", + avatar=UploadFile( + b"image bytes", + filename="ada.png", + content_type="image/png", + ), +) +``` + +For real files, open the input in binary mode and keep it open until the +request completes. Use a valid payload matching your declared content type. + +Do not combine `Body` with `File`: use `Form` for multipart metadata. +Allow the transport to set the multipart boundary instead of hard-coding a +`Content-Type` header. Confirm file representations supported by your +[backend](../integrations/backends.md). diff --git a/site/recipes/partial-updates.md b/site/recipes/partial-updates.md new file mode 100644 index 0000000..4292330 --- /dev/null +++ b/site/recipes/partial-updates.md @@ -0,0 +1,106 @@ +--- +title: Optional fields and Omitted +description: Omit optional query parameters, headers, and body fields with unihttp Omittable and Omitted, independently of the HTTP method. +--- + + + +# Optional fields and Omitted + +Use `Omitted()` when a request field should not be sent. It is independent of +the HTTP method: an optional GET filter, a POST body field, and a PATCH update +all use the same mechanism. The field's marker determines its location; +`Omitted()` determines whether it is included. + +## Omitted is not None + +`Omittable[T]` is an alias for `T | Omitted`. It allows the sentinel as a value; +the default `= Omitted()` also lets callers leave the argument out. + +- `Omittable[str]` accepts a string or omission; it does not include `None`. +- `Omittable[str | None]` additionally allows an explicit `None`. +- `str | None` alone allows null, but does not express omission. + +For a JSON body field, `None` becomes JSON `null`, while `Omitted()` leaves the +key out. An empty string or zero is still a supplied value, not omission. +Whether the server applies a default, clears a value, or rejects an absent or +null field is part of the endpoint's contract, not determined by unihttp. + +## Optional query parameters and headers + +These examples share the following imports and response model: + +```python +--8<-- "examples/optional_fields.py:setup" +``` + +For a GET endpoint, make filters and per-request headers omittable: + +```python +--8<-- "examples/optional_fields.py:query" +``` + +`ListUsers()` adds no query parameters or method-level headers. +`ListUsers(name="Ada", limit=10, accept="application/json")` includes both +filters and the `Accept` header. Middleware or the HTTP session may still add +headers of their own. + +Use `Omitted()`, not `None`, to leave out query parameters and headers. These +locations have no JSON null representation: the HTTP backend may encode or +reject `None` differently. Required URL placeholders still need concrete +`Path` values; omission does not make a path segment optional. + +## Optional JSON body fields + +The same pattern works for a POST endpoint. Here `name` is required, while +`nickname` can be omitted, set to a string, or explicitly set to null: + +```python +--8<-- "examples/optional_fields.py:body" +``` + +| Method instance | Serialized body fields | +| --- | --- | +| `CreateUser(name="Ada")` | `{"name": "Ada"}` | +| `CreateUser(name="Ada", nickname=None)` | `{"name": "Ada", "nickname": null}` | +| `CreateUser(name="Ada", nickname="Countess")` | `{"name": "Ada", "nickname": "Countess"}` | + +These method definitions are backend-independent and work with sync or async +clients. Bind them with `bind_method` or pass an instance to `call_method`, as +described in [methods and parameters](../guides/methods.md#binding-and-custom-methods). + +## Example: partial updates with PATCH + +PATCH is one application of omission, not a requirement for it. For an API +that treats missing fields as unchanged and null as clearing a value, an +update method can look like this. Import `Path` from `unihttp.markers` and use +the imports and `User` model above: + +```python +--8<-- "examples/recipes.py:partial" +``` + +| Call arguments | Serialized body fields | +| --- | --- | +| `user_id=1, name="Ada"` | `{"name": "Ada"}` | +| `user_id=1, name=None` | `{"name": null}` | +| `user_id=1` | No body fields | + +The `User` response model above has a non-nullable `name`; make it nullable +if this endpoint returns null after clearing the name. + +An entirely empty body dictionary may become no request body at the transport +layer, rather than a literal JSON `{}`. Check what your API accepts. + +## Serializer setup + +The examples work with `AdaptixDumper(DEFAULT_RETORT)`, `PydanticDumper()`, and +`MsgspecDumper()`. Omission is handled during request serialization, before the +HTTP backend sends the request. A custom dumper must implement omission itself. + +Use the direct `= Omitted()` default for consistency across integrations; +do not substitute `field(default_factory=Omitted)`, which Adaptix's omission +provider does not treat as the same default. When customizing Adaptix, extend +`DEFAULT_RETORT` to retain its omission support. + +See [serialization](../guides/serialization.md) for serializer configuration. diff --git a/site/recipes/retries.md b/site/recipes/retries.md new file mode 100644 index 0000000..5ce4b40 --- /dev/null +++ b/site/recipes/retries.md @@ -0,0 +1,101 @@ +--- +title: Retry transient failures +description: Safely scope unihttp retries to a buffered GET, combine them with HTTP error handling, and configure backoff for sync and async clients. +--- + +# Retry transient failures + +Retry a call only when the remote operation is safe to repeat. The built-in +middleware does **not** filter by HTTP method: attaching it to an entire client +also retries POSTs and other operations that may create duplicate resources. + +## Add retries to one GET method + +This example reuses `GetUser`, `status_errors`, and `async_status_errors` from +[Error handling](../guides/errors.md). `GetUser.on_error` only raises for `404`; +it leaves server errors for middleware. `CreateUser` is the POST method from +[methods and parameters](../guides/methods.md). + +The mapper is outermost and retry is inside it. Only `get_user` gets retries; +`create_user` still gets status handling, but is sent once. + +```python +from unihttp.bind_method import bind_method +from unihttp.exceptions import NetworkError, RequestTimeoutError +``` + +=== "Sync" + + ```python + from unihttp.clients.httpx import HTTPXSyncClient + from unihttp.middlewares import RetryMiddleware + + --8<-- "examples/response_retries.py:sync" + ``` + +=== "Async" + + ```python + from unihttp.clients.httpx import HTTPXAsyncClient + from unihttp.middlewares import AsyncRetryMiddleware + + --8<-- "examples/response_retries.py:async" + ``` + +Construct the client with your base URL and serializers as usual. Calls keep +their normal signatures: `client.get_user(user_id=1)`, or await that call on +an async client. You can also scope middleware to +[one explicit call](../guides/middleware.md). + +With this configuration: + +- `503 → 503 → 200` returns the loaded user after three attempts. +- Three `503` responses raise `ServerError` after the last attempt. +- `404` immediately raises `UserNotFound`; it is not retried. +- A configured network failure or timeout is retried up to the same limit. +- A failed `create_user` is not repeated. + +## Keep error handling outside retries + +Middleware lists are outermost-first. `[status_errors, RetryMiddleware(...)]` +lets retry inspect each response before the mapper turns the final status into +an exception. Reversing that order raises too early for status-based retries. + +Method and client hooks run inside the request handler. If they call +`raise_for_status()` on a `503`, retry receives a `ServerError`, not a response. +Prefer the mapper arrangement above for HTTP errors. If an existing hook must +raise, configure the specific exception types you intend to retry instead; +do not indiscriminately retry `ClientError`, `HTTPStatusError`, or `Exception`. + +Validation exceptions can also interrupt an attempt. The final model conversion +runs outside middleware and is not retried. See +[the response pipeline](../guides/errors.md#understand-the-pipeline). + +## Configure attempts and delays + +`retries=2` means **up to three attempts**, including the original request. +The default is three retries, or four attempts total. + +By default, status retries cover `500`, `502`, `503`, and `504`. Pass a non-empty +`status_codes` list to choose another set. Exceptions are not retried unless +included in `exceptions`; the example opts into `NetworkError` and +`RequestTimeoutError`. + +The delay before retry number `attempt + 1` is `backoff * 2**attempt`, starting +at `attempt = 0`. Here the base delays are 0.5 and 1 second. With `jitter=True`, +each delay gets an additional random value between 0 and 1 second. + +`429` is not retried by default, and the middleware does not interpret +`Retry-After`. If you need server-directed delays, this configuration alone +does not implement them. + +## Retry only calls you can safely repeat + +A timeout does not prove the server did nothing. Before enabling retries for a +write, check the API's idempotency guarantees and use its idempotency mechanism +where available. The request body must also be replayable: retry middleware +does not rewind file objects or consumed request streams for you. + +Do not attach this buffered-call recipe to streaming downloads. It cannot +resume a partially consumed response, and opening another response can require +additional cleanup. See [streaming](../guides/streaming.md#errors-and-parsing). diff --git a/site/reference/clients.md b/site/reference/clients.md new file mode 100644 index 0000000..0f847ac --- /dev/null +++ b/site/reference/clients.md @@ -0,0 +1,36 @@ +--- +title: Clients +description: Public sync and async client constructors and request lifecycle hooks. +--- + +# Clients + +Install the appropriate backend extra before importing its module. The base classes describe the shared lifecycle; concrete constructors list backend-specific settings. HTTPX clients close supplied sessions. See [HTTP backends](../integrations/backends.md) before switching transports. + +::: unihttp.clients.base.BaseClient + +::: unihttp.clients.base.BaseSyncClient + +::: unihttp.clients.base.BaseAsyncClient + +::: unihttp.clients.httpx.HTTPXSyncClient + +::: unihttp.clients.httpx.HTTPXAsyncClient + +::: unihttp.clients.httpx2.HTTPX2SyncClient + +::: unihttp.clients.httpx2.HTTPX2AsyncClient + +::: unihttp.clients.aiohttp.AiohttpAsyncClient + +::: unihttp.clients.requests.RequestsSyncClient + +::: unihttp.clients.niquests.NiquestsSyncClient + +::: unihttp.clients.niquests.NiquestsAsyncClient + +::: unihttp.clients.zapros.ZaprosSyncClient + +::: unihttp.clients.zapros.ZaprosAsyncClient + +::: unihttp.clients.urllib.UrllibSyncClient diff --git a/site/reference/http.md b/site/reference/http.md new file mode 100644 index 0000000..1405451 --- /dev/null +++ b/site/reference/http.md @@ -0,0 +1,18 @@ +--- +title: HTTP types +description: Request, response, upload, and stream types used by unihttp hooks and middleware. +--- + +# HTTP types + +`HTTPRequest.header` is singular; `HTTPResponse.headers` is plural. Buffered `call_method` returns the loaded body, whereas streaming calls expose `HTTPResponse` directly. These types are available to middleware and response hooks. See [response metadata](../guides/responses.md) for a wrapper example and [streaming](../guides/streaming.md) for cleanup requirements. + +::: unihttp.http.request.HTTPRequest + +::: unihttp.http.response.HTTPResponse + +::: unihttp.http.files.UploadFile + +::: unihttp.http.stream.ChunkStream + +::: unihttp.http.stream.AsyncChunkStream diff --git a/site/reference/index.md b/site/reference/index.md new file mode 100644 index 0000000..f534912 --- /dev/null +++ b/site/reference/index.md @@ -0,0 +1,23 @@ +--- +title: API reference +description: Find unihttp public client classes, method binding, parameter markers, HTTP types, serializer protocols, middleware, and exceptions. +--- + +# API reference + +Public signatures and types, generated from the library source. +For explanations and worked examples, use the [user guide](../guides/index.md). +For your first request, start with a [quickstart](../getting-started/quickstart.md). + +| Looking for | Reference | Usage guide | +| --- | --- | --- | +| `BaseMethod`, `StreamMethod`, `bind_method` | [Methods and binding](methods.md) | [Declare requests](../guides/methods.md) | +| Client constructors and lifecycle hooks | [Clients](clients.md) | [Choose an HTTP backend](../integrations/backends.md) | +| `Path`, `Query`, `Body`, `Omitted` | [Markers and omitted values](markers.md) | [Optional fields](../recipes/partial-updates.md) | +| `HTTPRequest`, `HTTPResponse`, uploads and streams | [HTTP types](http.md) | [Response metadata](../guides/responses.md), [streaming](../guides/streaming.md) | +| `RequestDumper`, `ResponseLoader`, integrations | [Serializers](serializers.md) | [Serialization](../guides/serialization.md) | +| Handlers, retries, logging and exceptions | [Middleware and exceptions](middleware.md) | [Middleware](../guides/middleware.md), [errors](../guides/errors.md) | + +Import symbols from their documented submodules, not from the top-level +`unihttp` package. Install the matching optional dependency before importing a +backend or serializer integration. diff --git a/site/reference/markers.md b/site/reference/markers.md new file mode 100644 index 0000000..b1879b8 --- /dev/null +++ b/site/reference/markers.md @@ -0,0 +1,14 @@ +--- +title: Markers and omitted values +description: Typed aliases for request locations and the sentinel used to omit fields. +--- + +# Markers and omitted values + +Import aliases from `unihttp.markers`: `Path`, `Query`, `Header`, `Body`, `Form`, `File`, and `Raw`. Each is an `Annotated[T, Marker]` alias, so its Python value remains of type `T`. See the [wire-location table](../guides/methods.md#marker-reference). `Raw` currently requires Adaptix or a custom dumper. + +Import `Omittable` and `Omitted` from `unihttp.omitted`. `Omittable[T]` means `T | Omitted`; use `Omitted()` as the default. [Optional fields and Omitted](../recipes/partial-updates.md) explains omission versus null, independently of the HTTP method. + +::: unihttp.markers.Marker + +::: unihttp.omitted.Omitted diff --git a/site/reference/methods.md b/site/reference/methods.md new file mode 100644 index 0000000..c10554c --- /dev/null +++ b/site/reference/methods.md @@ -0,0 +1,16 @@ +--- +title: Methods and binding +description: Public method definitions, response hooks, and typed client binding. +--- + +# Methods and binding + +Bind a method dataclass with `bind_method` to expose its constructor arguments on a client. Buffered calls return the declared model; streaming calls return an HTTP response containing a stream. Runtime-bound signatures depend on the supplied dataclass, so the generic signatures below describe the binding machinery rather than every generated endpoint. + +::: unihttp.method.RequestMethod + +::: unihttp.method.BaseMethod + +::: unihttp.method.StreamMethod + +::: unihttp.bind_method.bind_method diff --git a/site/reference/middleware.md b/site/reference/middleware.md new file mode 100644 index 0000000..314c26d --- /dev/null +++ b/site/reference/middleware.md @@ -0,0 +1,28 @@ +--- +title: Middleware and exceptions +description: Middleware handlers, retry and status-mapping configuration, logging, and the unihttp exception hierarchy. +--- + +# Middleware and exceptions + +Sync `Handler` and async `AsyncHandler` are callable aliases exported by `unihttp.middlewares`. Match the middleware variant to the client. See [middleware ordering](../guides/middleware.md) and [retry behavior](../recipes/retries.md). + +`HTTPStatusError` exposes `response` and `status_code`. Status errors require explicit handling; default response hooks do not raise automatically. Network exception normalization depends on the transport. + +::: unihttp.middlewares.base.Middleware + +::: unihttp.middlewares.base.AsyncMiddleware + +::: unihttp.middlewares.error_mapper.SyncErrorMapperMiddleware + +::: unihttp.middlewares.error_mapper.AsyncErrorMapperMiddleware + +::: unihttp.middlewares.retry.RetryMiddleware + +::: unihttp.middlewares.retry.AsyncRetryMiddleware + +::: unihttp.middlewares.logging.LoggingMiddleware + +::: unihttp.middlewares.logging.AsyncLoggingMiddleware + +::: unihttp.exceptions diff --git a/site/reference/serializers.md b/site/reference/serializers.md new file mode 100644 index 0000000..3e02a18 --- /dev/null +++ b/site/reference/serializers.md @@ -0,0 +1,24 @@ +--- +title: Serializers +description: RequestDumper and ResponseLoader protocols and built-in Adaptix, Pydantic, and msgspec implementations. +--- + +# Serializers + +A request dumper produces request parts; a response loader converts parsed data into the declared type. Both are explicitly supplied to the client. See [serialization](../guides/serialization.md) for compatibility limits. `DEFAULT_RETORT` is exported from `unihttp.serializers.adaptix` and should be extended with a keyword `recipe` to preserve unihttp providers. + +::: unihttp.serialize.RequestDumper + +::: unihttp.serialize.ResponseLoader + +::: unihttp.serializers.adaptix.serialize.AdaptixDumper + +::: unihttp.serializers.adaptix.serialize.AdaptixLoader + +::: unihttp.serializers.pydantic.serialize.PydanticDumper + +::: unihttp.serializers.pydantic.serialize.PydanticLoader + +::: unihttp.serializers.msgspec.serialize.MsgspecDumper + +::: unihttp.serializers.msgspec.serialize.MsgspecLoader diff --git a/site/stylesheets/installation.css b/site/stylesheets/installation.css new file mode 100644 index 0000000..8d1afae --- /dev/null +++ b/site/stylesheets/installation.css @@ -0,0 +1,128 @@ +/* Installation keeps the documentation TOC and native, linked content tabs. */ +.md-typeset .uh-install h1 { + margin: .5rem 0 .8rem; + color: var(--md-default-fg-color); + font-size: clamp(1.8rem, 1.5rem + 1.5cqi, 2.2rem); + font-weight: 650; + letter-spacing: -.035em; + line-height: 1.15; +} + +.md-typeset .uh-install h2 { + margin: 2rem 0 .8rem; + padding-top: 1.2rem; + border-top: 1px solid var(--uh-line); + font-size: 1.2rem; + font-weight: 600; + letter-spacing: -.02em; +} + +.md-typeset .uh-install .uh-lead { + margin-bottom: .6rem; +} + +.uh-install-requirements { + color: var(--uh-muted); + font-size: .75rem; +} + +.md-typeset .uh-install-help { + margin-block: 1rem; + padding: 0; + border: 1px solid var(--uh-line); + border-radius: .25rem; + background: transparent; + box-shadow: none; + font-size: .8rem; +} + +.md-typeset .uh-install-help > summary { + display: list-item; + margin: 0; + padding: .7rem .8rem; + min-height: 2.2rem; + border: 0; + background: transparent; + font-weight: 500; + cursor: pointer; + list-style-position: inside; +} + +.md-typeset .uh-install-help > summary::before, +.md-typeset .uh-install-help > summary::after { + display: none; +} + +.uh-install-help[open] > :not(summary) { + margin-inline: .8rem; +} + +.uh-install summary:focus-visible, +.uh-install a:focus-visible { + outline: 2px solid var(--uh-accent); + outline-offset: 2px; +} + +.uh-install-picker { + margin-top: 1.5rem; +} + +.md-typeset .uh-install-label { + margin: 1rem 0 .25rem; + color: var(--uh-muted); + font-size: .7rem; + font-weight: 600; +} + +.md-typeset .uh-install-mode { + margin: .75rem 0 1rem; + color: var(--uh-accent); + font-size: .75rem; +} + +.uh-install-picker .tabbed-set { + min-width: 0; +} + +.md-typeset .uh-install-note { + margin-top: 1.2rem; + color: var(--uh-muted); + font-size: .75rem; + line-height: 1.7; +} + +.uh-install-next { + display: grid; + gap: .8rem; + margin-block: 1.2rem; +} + +.md-typeset .uh-install-next p { + margin: 0; +} + +.md-typeset .uh-install-next a { + display: block; + padding-block: .5rem; + color: var(--uh-accent); + text-decoration: none; +} + +.uh-install-next a:hover strong { + text-decoration: underline; + text-underline-offset: .2em; +} + +.uh-install-next span { + display: block; + margin-top: .35rem; + color: var(--uh-muted); + font-size: .75rem; +} + +@container (min-width: 28rem) { + .uh-install-next { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1.5rem; + } +} diff --git a/site/stylesheets/overview.css b/site/stylesheets/overview.css new file mode 100644 index 0000000..3946664 --- /dev/null +++ b/site/stylesheets/overview.css @@ -0,0 +1,257 @@ +/* Shared page tokens; all layout rules remain scoped to their page components. */ +.uh-overview, +.uh-install { + --uh-accent: #855019; + --uh-on-accent: #fffaf3; + --uh-muted: #595d65; + --uh-line: color-mix(in srgb, var(--md-default-fg-color) 16%, var(--md-default-bg-color)); + container-type: inline-size; +} + +[data-md-color-scheme="slate"] .uh-overview, +[data-md-color-scheme="slate"] .uh-install { + --uh-accent: #e4b879; + --uh-on-accent: #27221b; + --uh-muted: #b1b5be; +} + +.md-typeset .uh-overview h1, +.md-typeset .uh-overview h2, +.md-typeset .uh-overview h3 { + color: var(--md-default-fg-color); + font-weight: 650; + text-wrap: balance; +} + +.md-typeset .uh-overview h1 { + max-width: 28ch; + margin: .6rem 0 1.2rem; + font-size: clamp(1.65rem, 1.2rem + 2.1cqi, 2.5rem); + line-height: 1.13; + letter-spacing: -.035em; +} + +.md-typeset .uh-overview h2 { + margin: 0 0 .8rem; + font-size: 1.3rem; + line-height: 1.25; + letter-spacing: -.02em; +} + +.md-typeset .uh-overview h3 { + margin: 0 0 .6rem; + font-size: .9rem; +} + +.uh-hero { + padding: .4rem 0 2.4rem; +} + +.md-typeset .uh-eyebrow { + margin: 0; + color: var(--uh-accent); + font-size: .7rem; + font-weight: 600; + letter-spacing: .025em; +} + +.md-typeset .uh-lead { + max-width: 56ch; + margin: 0 0 1.4rem; + font-size: 1rem; + line-height: 1.65; +} + +.uh-actions > p { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: .5rem 1.2rem; +} + +.md-typeset .uh-actions .md-button--primary { + border-color: var(--uh-accent); + background: var(--uh-accent); + color: var(--uh-on-accent); + padding: .6em 1.15em; +} + +.md-typeset .uh-actions .md-button--primary:hover { + background: var(--uh-on-accent); + color: var(--uh-accent); +} + +.md-typeset .uh-overview a:not(.md-button):not(.headerlink) { + color: var(--uh-accent); +} + +.md-typeset .uh-secondary { + display: inline-flex; + align-items: center; + min-height: 2.2rem; +} + +.md-typeset .uh-overview a:focus-visible { + outline: 2px solid var(--uh-accent); + outline-offset: 4px; +} + +.md-typeset .uh-summary, +.md-typeset .uh-caption { + color: var(--uh-muted); + font-size: .7rem; + line-height: 1.7; +} + +.md-typeset .uh-summary { + margin: 1rem 0 0; +} + +.uh-example, +.uh-stack, +.uh-next { + border-top: 1px solid var(--uh-line); + padding-block: 2rem; +} + +.uh-example, +.uh-stack-options { + display: grid; + gap: 1.2rem; +} + +.uh-example > *, +.uh-stack-options > * { + min-width: 0; +} + +.md-typeset .uh-example ol { + margin: 1.2rem 0 1.2rem 1rem; +} + +.md-typeset .uh-example li { + margin: 0 0 .8rem; + padding-left: .2rem; +} + +.uh-example li::marker { + color: var(--uh-accent); + font-weight: 600; +} + +.uh-code { + align-self: start; + overflow: hidden; + border: 1px solid var(--uh-line); + border-radius: .3rem; + background: var(--md-code-bg-color); +} + +.md-typeset .uh-code-label { + margin: 0; + padding: .65rem .8rem; + border-bottom: 1px solid var(--uh-line); + color: var(--uh-muted); + font-size: .65rem; + font-weight: 600; +} + +.md-typeset .uh-code .highlight, +.md-typeset .uh-code pre { + margin: 0; +} + +.md-typeset .uh-code .tabbed-set { + margin: 0; +} + +.md-typeset .uh-overview .uh-code .tabbed-labels a { + color: inherit; +} + +.md-typeset .uh-code pre > code { + padding: .9rem; + font-size: .7rem; + line-height: 1.65; +} + +.uh-stack > p { + max-width: 64ch; +} + +.uh-stack-options { + margin-top: 1.4rem; +} + +.uh-stack-options a { + display: inline-flex; + align-items: center; + min-height: 2.2rem; +} + +.md-typeset .uh-routes > p { + margin: 0; + border-bottom: 1px solid var(--uh-line); +} + +.md-typeset .uh-routes a { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: .2rem .8rem; + padding: .9rem .2rem; + text-decoration: none; +} + +.uh-routes a > span:first-of-type { + grid-column: 1; + color: var(--uh-muted); + font-size: .75rem; +} + +.uh-routes a > span[aria-hidden] { + grid-column: 2; + grid-row: 1 / 3; + align-self: center; +} + +.uh-routes a:hover strong { + text-decoration: underline; + text-underline-offset: .2em; +} + +.md-typeset .uh-fit { + max-width: 66ch; + padding-bottom: 1rem; + color: var(--uh-muted); + font-size: .75rem; +} + +.md-typeset .uh-fit p { + margin: 0 0 .4rem; +} + +@container (min-width: 36rem) { + .uh-example { + grid-template-columns: minmax(0, 1fr) minmax(0, 1.2fr); + gap: 2rem; + } + + .uh-stack-options { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 2rem; + } + + .md-typeset .uh-routes a { + grid-template-columns: 10rem minmax(0, 1fr) auto; + align-items: baseline; + } + + .uh-routes a > span:first-of-type { + grid-column: 2; + } + + .uh-routes a > span[aria-hidden] { + grid-column: 3; + grid-row: 1; + } +} diff --git a/tests/test_docs_build.py b/tests/test_docs_build.py new file mode 100644 index 0000000..17fc148 --- /dev/null +++ b/tests/test_docs_build.py @@ -0,0 +1,368 @@ +"""Verify deployment metadata and that exported docs contain usable content.""" + +import pytest + +pytest.importorskip("markdownify") +BeautifulSoup = pytest.importorskip("bs4").BeautifulSoup + +from scripts import build_docs + + +@pytest.fixture +def rendered_site(tmp_path, monkeypatch): + monkeypatch.setattr(build_docs, "OUTPUT", tmp_path) + return tmp_path + + +def write_page(root, relative="index.html", content="

Documentation

"): + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + url = "https://docs.example.com/en/v1/" + relative.removesuffix("index.html") + path.write_text(f'''Test + + + +

Example

{content}
+''') + return path + + +def test_preview_exports_and_metadata(rendered_site): + path = write_page( + rendered_site, + content='

API

class User: pass
', + ) + pages = build_docs.finish_pages("https://docs.example.com/en/v1/", "123", True) + build_docs.verify_links(pages, "https://docs.example.com/en/v1/") + soup = BeautifulSoup(path.read_text(), "html.parser") + assert soup.find("meta", attrs={"name": "robots"})["content"] == "noindex" + exported = (rendered_site / "markdown/index.md").read_text() + assert "class User: pass" in exported + assert "Not part of the article" not in exported + assert "Development documentation" not in exported + assert ( + "https://docs.example.com/en/v1/markdown/index.md" + in (rendered_site / "llms.txt").read_text() + ) + + +def test_release_is_indexable(rendered_site): + write_page(rendered_site) + pages = build_docs.finish_pages("https://docs.example.com/en/v1/", "v1", False) + soup = pages[rendered_site / "index.html"] + assert soup.find("meta", attrs={"name": "robots"}) is None + assert "Documentation version:" not in soup.get_text() + assert "Documentation version: v1." in (rendered_site / "llms.txt").read_text() + + +def test_latest_has_no_development_banner(rendered_site): + write_page(rendered_site) + pages = build_docs.finish_pages("https://docs.example.com/en/v1/", "latest", False) + soup = pages[rendered_site / "index.html"] + assert "Development documentation" not in soup.get_text() + assert "may include unreleased changes" not in soup.get_text() + assert ( + "Development documentation" + not in (rendered_site / "markdown/index.md").read_text() + ) + assert "Documentation version: latest." in (rendered_site / "llms.txt").read_text() + + +@pytest.mark.parametrize("href", ["missing/", "#missing", "/en/latest/"]) +def test_broken_links_fail(rendered_site, href): + write_page(rendered_site, content=f'Broken') + pages = build_docs.finish_pages("https://docs.example.com/en/v1/", "v1", False) + with pytest.raises(ValueError): + build_docs.verify_links(pages, "https://docs.example.com/en/v1/") + + +def test_preview_sitemap_has_no_indexable_urls(rendered_site): + path = rendered_site / "sitemap.xml" + path.write_text( + 'https://docs.example.com/en/v1/' + ) + build_docs.verify_sitemap("https://docs.example.com/en/v1/", True) + assert "" not in path.read_text() + + +def test_wrong_canonical_fails(rendered_site): + write_page(rendered_site) + with pytest.raises(ValueError, match="canonical"): + build_docs.finish_pages("https://wrong.example.com/", "v1", False) + + +@pytest.mark.parametrize( + "prefix", ["https://docs.example.com/en/latest/", "https://custom.example/v1/"] +) +def test_redirects_keep_canonical_and_skip_article_exports(rendered_site, prefix): + write_page(rendered_site) + old = rendered_site / "old" / "index.html" + old.parent.mkdir() + old.write_text( + 'Moved' + ) + pages = build_docs.finish_pages("https://docs.example.com/en/v1/", "v1", False) + build_docs.verify_redirects(pages, prefix, {"old.md": "index.md"}) + assert not (rendered_site / "markdown/old/index.md").exists() + assert "old/index.md" not in (rendered_site / "llms.txt").read_text() + pages[old].find("meta")["content"] = "0; url=missing/" + with pytest.raises(ValueError, match="redirect destination"): + build_docs.verify_redirects(pages, prefix, {"old.md": "index.md"}) + + +def test_tab_exports_keep_labels_and_inactive_code(rendered_site): + import markdown + + content = markdown.markdown( + '=== "HTTPX"\n\n ```python\n from unihttp.clients.httpx import HTTPXSyncClient\n ```\n\n' + '=== "aiohttp"\n\n ```python\n from unihttp.clients.aiohttp import AiohttpAsyncClient\n ```', + extensions=["pymdownx.superfences", "pymdownx.tabbed"], + extension_configs={"pymdownx.tabbed": {"alternate_style": True}}, + ) + path = write_page(rendered_site, content=content) + build_docs.finish_pages("https://docs.example.com/en/v1/", "v1", False) + exported = (rendered_site / "markdown/index.md").read_text() + assert exported.index("**HTTPX**") < exported.index("HTTPXSyncClient") + assert exported.index("HTTPXSyncClient") < exported.index("**aiohttp**") + assert exported.index("**aiohttp**") < exported.index("AiohttpAsyncClient") + html = BeautifulSoup(path.read_text(), "html.parser") + assert len(html.select(".tabbed-set > input")) == 2 + assert len(html.select(".tabbed-labels > label")) == 2 + + +@pytest.fixture +def installation_html(): + import markdown + + source = (build_docs.ROOT / "site/getting-started/installation.md").read_text() + return markdown.markdown( + source.split("---", 2)[2], + extensions=["attr_list", "md_in_html", "pymdownx.superfences", "pymdownx.tabbed"], + extension_configs={"pymdownx.tabbed": {"alternate_style": True}}, + ) + + +def test_installation_covers_all_backend_serializer_combinations(installation_html): + import shlex + import tomllib + + project = tomllib.loads((build_docs.ROOT / "pyproject.toml").read_text())["project"] + extras = project["optional-dependencies"] + soup = BeautifulSoup(installation_html, "html.parser") + picker = soup.select_one(".uh-install-picker > .tabbed-set") + labels = picker.select(":scope > .tabbed-labels > label") + panels = picker.select(":scope > .tabbed-content > .tabbed-block") + assert {label.get_text().lower() for label in labels} == { + "httpx", + "requests", + "aiohttp", + "httpx2", + "niquests", + "zapros", + "urllib", + } + for label, panel in zip(labels, panels, strict=True): + backend = label.get_text().lower() + serializers = panel.select_one(".tabbed-set") + names = serializers.select(":scope > .tabbed-labels > label") + commands = serializers.select(":scope > .tabbed-content > .tabbed-block") + assert {name.get_text().lower() for name in names} == { + "adaptix", + "pydantic", + "msgspec", + } + for name, command in zip(names, commands, strict=True): + selected = ([backend] if backend != "urllib" else []) + [ + name.get_text().lower() + ] + assert set(selected) <= extras.keys() + package = "unihttp[" + ",".join(selected) + "]" + blocks = command.select("pre > code") + assert len(blocks) == 2 + assert shlex.split(blocks[0].get_text()) == [ + "python", + "-m", + "pip", + "install", + package, + ] + assert shlex.split(blocks[1].get_text()) == ["uv", "add", package] + + +def test_installation_exports_nested_tabs(rendered_site, installation_html): + write_page(rendered_site, content=installation_html) + build_docs.finish_pages("https://docs.example.com/en/v1/", "v1", False) + exported = (rendered_site / "markdown/index.md").read_text() + first_backend = exported.split("**HTTPX**", 1)[1].split("**requests**", 1)[0] + for name, extra in [ + ("Adaptix", "adaptix"), + ("Pydantic", "pydantic"), + ("msgspec", "msgspec"), + ]: + assert first_backend.index(f"**{name}**") < first_backend.index( + f"unihttp[httpx,{extra}]" + ) + assert "unihttp[pydantic]" in exported # Inactive urllib + Pydantic tab. + + +def navigation_paths(items): + for item in items: + if isinstance(item, str): + yield item + else: + for value in item.values(): + if isinstance(value, list): + yield from navigation_paths(value) + else: + yield value + + +@pytest.mark.parametrize( + "page", + sorted((build_docs.ROOT / "site").rglob("*.md")), + ids=lambda page: page.relative_to(build_docs.ROOT / "site").as_posix(), +) +def test_rendered_examples_are_clean(page): + import re + import markdown + + html = markdown.markdown( + page.read_text().split("---", 2)[2], + extensions=[ + "attr_list", + "md_in_html", + "pymdownx.superfences", + "pymdownx.tabbed", + "pymdownx.snippets", + ], + extension_configs={ + "pymdownx.tabbed": {"alternate_style": True}, + "pymdownx.snippets": { + "base_path": [str(build_docs.ROOT)], + "check_paths": True, + "dedent_subsections": True, + }, + }, + ) + soup = BeautifulSoup(html, "html.parser") + for code in soup.select(".highlight pre > code"): + text = code.get_text() + assert not re.search(r"\n(?:[ \t]*\n){3,}", text), page + assert not re.search(r"#\s*(?:noqa\b|type:\s*ignore\b|pyright:|ruff:)", text), ( + page + ) + if page == build_docs.ROOT / "site/index.md": + assert "user_id: Path[int]\n\n\nclass UserClient" in text + if page.relative_to(build_docs.ROOT / "site").as_posix() in { + "guides/middleware.md", + "guides/responses.md", + "guides/errors.md", + "guides/streaming.md", + "recipes/retries.md", + }: + assert not text.startswith(" "), ( + "Guide snippets must not inherit function indentation" + ) + assert "MockTransport" not in text + assert "events.append" not in text + + +def test_middleware_snippet_ranges_match_complete_definitions(): + import ast + import re + + root = build_docs.ROOT + page = (root / "site/guides/middleware.md").read_text() + snippets = re.findall(r'--8<-- "(examples/middleware_\w+\.py):(\d+):(\d+)"', page) + assert len(snippets) == 4 + for name, start, end in snippets: + source = (root / name).read_text() + tree = ast.parse(source) + definition = next(node for node in tree.body if node.lineno == int(start)) + assert isinstance(definition, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)) + assert definition.end_lineno == int(end), "Update the snippet range with the example" + snippet = "\n".join(source.splitlines()[int(start) - 1:int(end)]) + assert ast.dump(ast.parse(snippet).body[0]) == ast.dump(definition) + + +def test_navigation_covers_each_listed_page_once(): + import tomllib + from collections import Counter + + config = tomllib.loads((build_docs.ROOT / "zensical.toml").read_text())["project"] + assert [next(iter(section)) for section in config["nav"]] == [ + "Getting started", + "User guide", + "API reference", + "Coding agent skills", + "Contributing", + ] + paths = list(navigation_paths(config["nav"])) + assert all(count == 1 for count in Counter(paths).values()) + root = build_docs.ROOT / config["docs_dir"] + # Keep the old release URL available without a navigation entry. + unlisted = {"project/releases.md"} + assert set(paths).isdisjoint(unlisted) + assert set(paths) | unlisted == { + path.relative_to(root).as_posix() for path in root.rglob("*.md") + } + assert config["nav"][-2:] == [ + {"Coding agent skills": "project/agent-skills.md"}, + {"Contributing": "project/documentation.md"}, + ] + assert "navigation.indexes" in config["theme"]["features"] + assert "navigation.expand" not in config["theme"]["features"] + guide = next(item["User guide"] for item in config["nav"] if "User guide" in item) + assert {"Serialization": "guides/serialization.md"} in guide + redirects = config["plugins"]["redirects"]["redirect_maps"] + assert redirects == { + f"integrations/{backend}.md": "guides/serialization.md" + for backend in ("adaptix", "pydantic", "msgspec") + } + assert all(not (root / source).exists() for source in redirects) + + +def test_api_extraction_supports_original_namespace_package(caplog): + from griffe import GriffeLoader, load_extensions + + root = build_docs.ROOT + assert not (root / "src/unihttp/serializers/__init__.py").exists() + source = root / "src/unihttp/clients/base.py" + original = source.read_bytes() + loader = GriffeLoader( + search_paths=[root / "src"], + extensions=load_extensions(str(root / "scripts/docs_griffe.py") + ":UnihttpDocsExtension"), + docstring_parser="google", + ) + package = loader.load("unihttp") + loader.resolve_aliases() + for backend, prefix in [("adaptix", "Adaptix"), ("pydantic", "Pydantic"), ("msgspec", "Msgspec")]: + for suffix, method in [("Dumper", "dump"), ("Loader", "load")]: + obj = package[f"serializers.{backend}.serialize.{prefix}{suffix}"] + assert method in obj.members + hook = package["clients.base.BaseClient.handle_error"] + assert hook.docstring.parsed + assert "Confusing indentation" not in caplog.text + assert source.read_bytes() == original + assert not (root / "src/unihttp/serializers/__init__.py").exists() + + +@pytest.mark.parametrize( + "section,index", + [("User guide", "guides/index.md"), ("API reference", "reference/index.md")], +) +def test_section_indexes_link_to_every_child(section, index): + import re + import tomllib + + config = tomllib.loads((build_docs.ROOT / "zensical.toml").read_text())["project"] + children = next(item[section] for item in config["nav"] if section in item) + root = build_docs.ROOT / config["docs_dir"] + page = root / index + targets = { + (page.parent / link.split("#")[0]).resolve() + for link in re.findall(r"\]\(([^)]+)\)", page.read_text()) + } + assert { + (root / path).resolve() for path in navigation_paths(children) if path != index + } <= targets diff --git a/tests/test_docs_examples.py b/tests/test_docs_examples.py new file mode 100644 index 0000000..a0b74e7 --- /dev/null +++ b/tests/test_docs_examples.py @@ -0,0 +1,437 @@ +"""Contract checks for the exact Python files embedded in the public docs.""" + +import json +import importlib +import re +import sys +from pathlib import Path +from http.server import ThreadingHTTPServer +from threading import Thread + +import httpx +import pytest + +from examples import ( + async_client, + demo_api, + middleware_async, + middleware_scope, + middleware_sync, + optional_fields, + quickstart, + recipes, + response_metadata, +) +from unihttp.http import UploadFile +from unihttp.middlewares import RetryMiddleware, SyncErrorMapperMiddleware +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader +from unihttp.serializers.msgspec import MsgspecDumper, MsgspecLoader +from unihttp.serializers.pydantic import PydanticDumper, PydanticLoader + + +def test_quickstart(): + assert quickstart.main() == quickstart.User(id=1, name="Ada") + + +@pytest.fixture +def docs_demo_api(): + with ThreadingHTTPServer(("127.0.0.1", 0), demo_api.DemoAPIHandler) as server: + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_port}" + finally: + server.shutdown() + thread.join(timeout=5) + + +@pytest.mark.parametrize( + "backend", ["httpx", "requests", "httpx2", "niquests", "zapros", "urllib"] +) +def test_sync_backend_tab(backend, docs_demo_api, monkeypatch): + module = importlib.import_module(f"examples.backends.{backend}_sync") + original_close = module.UserClient.close + closed = [] + + def close(client): + original_close(client) + closed.append(True) + + monkeypatch.setattr(module.UserClient, "close", close) + assert module.main(docs_demo_api) == module.User(id=1, name="Ada") + assert closed == [True] + + +@pytest.mark.parametrize("backend", ["httpx", "aiohttp", "httpx2", "niquests", "zapros"]) +async def test_async_backend_tab(backend, docs_demo_api, monkeypatch): + module = importlib.import_module(f"examples.backends.{backend}_async") + original_close = module.UserClient.close + closed = [] + + async def close(client): + await original_close(client) + closed.append(True) + + monkeypatch.setattr(module.UserClient, "close", close) + assert await module.main(docs_demo_api) == module.User(id=1, name="Ada") + assert closed == [True] + + +async def test_async_quickstart(): + assert await async_client.main() == async_client.User(id=1, name="Ada") + + +def client_for(handler, **kwargs): + return recipes.UserClient( + base_url="https://api.example.com", + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=AdaptixLoader(DEFAULT_RETORT), + session=httpx.Client(transport=httpx.MockTransport(handler)), + **kwargs, + ) + + +def test_create_auth_and_partial_update(): + seen = [] + + def handler(request): + seen.append(request) + return httpx.Response(200, json={"id": 1, "name": "Ada"}) + + with client_for(handler, middleware=[recipes.BearerAuth("test-token")]) as client: + assert client.create_user(name="Ada").name == "Ada" + client.update_user(user_id=1, name=None) + client.update_user(user_id=1) + assert json.loads(seen[0].content) == {"name": "Ada"} + assert seen[0].headers["Authorization"] == "Bearer test-token" + assert json.loads(seen[1].content) == {"name": None} + assert seen[1].method == "PATCH" + assert seen[1].url.path == "/users/1" + assert seen[2].content == b"" # Empty body is not encoded as {} by this backend. + + +def test_method_error_and_status_mapper(): + def handler(request): + return httpx.Response(404, json={"error": "missing"}) + + with client_for(handler) as client: + with pytest.raises(recipes.UserNotFound): + client.get_user(user_id=999) + with client_for( + handler, middleware=[SyncErrorMapperMiddleware({404: ValueError})] + ) as client: + with pytest.raises(ValueError, match="HTTP 404"): + client.create_user(name="Ada") + + +def test_upload_and_stream(): + seen = [] + + def handler(request): + seen.append(request) + if request.url.path.startswith("/files/"): + return httpx.Response(200, content=b"downloaded content") + return httpx.Response(200, json={"id": 1, "name": "Ada"}) + + with client_for(handler) as client: + client.upload_avatar( + user_id=1, + caption="portrait", + avatar=UploadFile(b"image", filename="ada.png", content_type="image/png"), + ) + response = client.download_file(file_id=1) + with response.data as stream: + assert b"".join(stream) == b"downloaded content" + assert "multipart/form-data" in seen[0].headers["Content-Type"] + assert b'filename="ada.png"' in seen[0].content + assert b"portrait" in seen[0].content + + +def test_retry_before_error_mapping(): + attempts = [] + + def handler(request): + attempts.append(request) + return httpx.Response( + 503 if len(attempts) == 1 else 200, json={"id": 1, "name": "Ada"} + ) + + with client_for( + handler, + middleware=[ + SyncErrorMapperMiddleware({range(500, 600): RuntimeError}), + RetryMiddleware(retries=1, backoff=0, jitter=False), + ], + ) as client: + assert client.create_user(name="Ada").id == 1 + assert len(attempts) == 2 + + +@pytest.mark.parametrize( + "dumper,loader", + [ + (AdaptixDumper(DEFAULT_RETORT), AdaptixLoader(DEFAULT_RETORT)), + (PydanticDumper(), PydanticLoader()), + (MsgspecDumper(), MsgspecLoader()), + ], +) +def test_serializer_contract(dumper, loader): + assert dumper.dump(recipes.CreateUser(name="Ada"))["body"] == {"name": "Ada"} + assert dumper.dump(recipes.UpdateUser(user_id=1))["body"] == {} + assert loader.load({"id": 1, "name": "Ada"}, recipes.User) == recipes.User(1, "Ada") + + +@pytest.mark.parametrize( + "dumper", + [AdaptixDumper(DEFAULT_RETORT), PydanticDumper(), MsgspecDumper()], + ids=["adaptix", "pydantic", "msgspec"], +) +def test_optional_fields_across_methods_and_serializers(dumper): + from unihttp.omitted import Omitted + + request = optional_fields.ListUsers().build_http_request(dumper) + assert request.method == "GET" + assert request.query == {} + assert request.header == {} + + request = optional_fields.ListUsers( + name="Ada", limit=10, accept="application/json" + ).build_http_request(dumper) + assert request.query == {"name": "Ada", "limit": 10} + assert request.header == {"accept": "application/json"} + assert dumper.dump(optional_fields.ListUsers(name="", limit=0))["query"] == { + "name": "", + "limit": 0, + } + assert dumper.dump(optional_fields.ListUsers(name=Omitted()))["query"] == {} + + for nickname, expected in [ + (Omitted(), {"name": "Ada"}), + (None, {"name": "Ada", "nickname": None}), + ("Countess", {"name": "Ada", "nickname": "Countess"}), + ("", {"name": "Ada", "nickname": ""}), + ]: + request = optional_fields.CreateUser( + name="Ada", nickname=nickname + ).build_http_request(dumper) + assert request.method == "POST" + assert request.body == expected + assert dumper.dump(optional_fields.CreateUser(name="Ada"))["body"] == {"name": "Ada"} + + assert dumper.dump(recipes.UpdateUser(user_id=1))["body"] == {} + assert dumper.dump(recipes.UpdateUser(user_id=1, name=None))["body"] == {"name": None} + assert dumper.dump(recipes.UpdateUser(user_id=1, name="Ada"))["body"] == { + "name": "Ada" + } + + +def test_raw_body_adaptix(): + request = recipes.PutBytes(content=b"payload").build_http_request( + AdaptixDumper(DEFAULT_RETORT) + ) + assert request.raw == b"payload" + + +def test_raw_upload_json_acknowledgement(): + def handler(request): + assert request.method == "PUT" + assert request.content == b"payload" + return httpx.Response(200, json={"size": len(request.content)}) + + with client_for(handler) as client: + assert client.call_method(recipes.PutBytes(content=b"payload")) == {"size": 7} + + +def test_response_metadata(): + result = response_metadata.main() + assert result.user == response_metadata.User(id=1, name="Ada") + assert result.status_code == 200 + assert result.request_id == "request-123" + + +def test_middleware_scope(docs_demo_api, monkeypatch, capsys): + from uuid import UUID + + seen = [] + make_request = middleware_scope.UserClient.make_request + + def record(client, request): + seen.append(dict(request.header)) + return make_request(client, request) + + monkeypatch.setattr(middleware_scope.UserClient, "make_request", record) + middleware_scope.main(docs_demo_api) + assert capsys.readouterr().out.count("User(id=1, name='Ada')") == 3 + assert [headers.get("Cache-Control") for headers in seen] == [ + "no-cache", + None, + "no-cache", + ] + ids = [headers["X-Request-ID"] for headers in seen] + assert len(set(ids)) == 3 + assert all(UUID(value).version == 4 for value in ids) + + +@pytest.mark.parametrize("module", [middleware_sync, middleware_async, middleware_scope]) +def test_middleware_examples_are_standalone(module, tmp_path, docs_demo_api): + import ast + import shutil + import subprocess + + source = Path(module.__file__).read_text() + tree = ast.parse(source) + assert "--8<--" not in source + assert "MockTransport" not in source + for node in ast.walk(tree): + if isinstance(node, (ast.Import, ast.ImportFrom)): + assert node in tree.body, "Keep imports at module level" + modules = ( + [node.module or ""] + if isinstance(node, ast.ImportFrom) + else [alias.name for alias in node.names] + ) + assert all(not name.startswith("examples") for name in modules) + if isinstance(node, ast.ClassDef): + assert node in tree.body, "Keep classes at module level" + script = tmp_path / Path(module.__file__).name + shutil.copyfile(module.__file__, script) + runner = ( + "import asyncio, inspect, runpy, sys; " + "main = runpy.run_path(sys.argv[1])['main']; " + "asyncio.run(main(sys.argv[2])) if inspect.iscoroutinefunction(main) else main(sys.argv[2])" + ) + result = subprocess.run( + [sys.executable, "-c", runner, str(script), docs_demo_api], + cwd=tmp_path, + capture_output=True, + text=True, + check=True, + timeout=15, + ) + assert "User(id=1, name='Ada')" in result.stdout + + +def test_sync_timing_middleware_connection(docs_demo_api, caplog): + with caplog.at_level("INFO", logger="unihttp.timing"): + middleware_sync.main(docs_demo_api) + messages = [ + record.getMessage() + for record in caplog.records + if record.name == "unihttp.timing" + ] + assert len(messages) == 1 + assert re.fullmatch(r"GET → 200 in \d+\.\d ms", messages[0]) + + +async def test_async_timing_middleware_connection(docs_demo_api, caplog): + with caplog.at_level("INFO", logger="unihttp.timing"): + await middleware_async.main(docs_demo_api) + messages = [ + record.getMessage() + for record in caplog.records + if record.name == "unihttp.timing" + ] + assert len(messages) == 1 + assert re.fullmatch(r"GET → 200 in \d+\.\d ms", messages[0]) + + +@pytest.mark.parametrize("is_async", [False, True], ids=["sync", "async"]) +async def test_timing_middleware_preserves_response_and_errors( + is_async, monkeypatch, caplog +): + from unihttp.http.request import HTTPRequest + from unihttp.http.response import HTTPResponse + + module = middleware_async if is_async else middleware_sync + middleware = module.AsyncTimingMiddleware() if is_async else module.TimingMiddleware() + ticks = iter([1.0, 1.125, 2.0]) + monkeypatch.setattr(module, "perf_counter", lambda: next(ticks)) + request = HTTPRequest( + method="GET", + url="/private?token=secret", + header={"Authorization": "secret"}, + path={}, + query={}, + body={}, + file={}, + form={}, + ) + response = HTTPResponse( + status_code=200, + data={"secret": "payload"}, + headers={}, + cookies={}, + raw_response=None, + ) + seen = [] + + def send(received): + seen.append(received) + return response + + async def async_send(received): + return send(received) + + with caplog.at_level("INFO", logger="unihttp.timing"): + result = ( + await middleware.handle(request, async_send) + if is_async + else middleware.handle(request, send) + ) + assert result is response + assert seen == [request] + assert [record.getMessage() for record in caplog.records] == ["GET → 200 in 125.0 ms"] + + error = RuntimeError("transport failed") + + def fail(received): + raise error + + async def async_fail(received): + raise error + + caplog.clear() + with ( + caplog.at_level("INFO", logger="unihttp.timing"), + pytest.raises(RuntimeError) as raised, + ): + if is_async: + await middleware.handle(request, async_fail) + else: + middleware.handle(request, fail) + assert raised.value is error + assert not caplog.records + + +def test_custom_json_codec(): + pytest.importorskip("orjson") + from examples import json_codec + + assert json_codec.main() == json_codec.User(id=1, name="Ada") + + +@pytest.mark.parametrize("status", [302, 404, 500]) +def test_stream_error_closes_before_hook(status): + observed = [] + + class Download(recipes.DownloadFile): + def on_error(self, response): + observed.append((response.status_code, list(response.data))) + + def handler(request): + return httpx.Response(status, content=b"error details") + + with client_for(handler) as client: + response = client.call_method_stream(Download(file_id=1)) + assert response.status_code == status + assert list(response.data) == [] + assert observed == [(status, [])] + + +def test_readme_links_to_documentation(): + import tomllib + + root = Path(__file__).resolve().parents[1] + config = tomllib.loads((root / "zensical.toml").read_text()) + url = config["project"]["site_url"] + assert f"[Documentation]({url})" in (root / "README.md").read_text() diff --git a/tests/test_docs_responses.py b/tests/test_docs_responses.py new file mode 100644 index 0000000..95d5a32 --- /dev/null +++ b/tests/test_docs_responses.py @@ -0,0 +1,357 @@ +"""Run the response guides' exact examples together, in sync and async modes.""" + +import inspect +from contextlib import asynccontextmanager +from hashlib import sha256 + +import httpx +import pytest + +from examples import ( + recipes, + response_errors, + response_metadata, + response_retries, + response_streaming, +) +from unihttp.exceptions import ( + ClientError, + HTTPStatusError, + NetworkError, + RequestTimeoutError, + ServerError, +) +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +async def resolve(result): + return await result if inspect.isawaitable(result) else result + + +@pytest.fixture(params=[False, True], ids=["sync", "async"]) +def async_mode(request): + return request.param + + +@asynccontextmanager +async def client_for( + module, handler, async_mode, *, streaming=False, response_loader=None +): + if streaming: + cls = module.AsyncFileClient if async_mode else module.FileClient + else: + cls = module.AsyncUserClient if async_mode else module.UserClient + session_cls = httpx.AsyncClient if async_mode else httpx.Client + client = cls( + base_url="https://api.example.com", + request_dumper=AdaptixDumper(DEFAULT_RETORT), + response_loader=response_loader + if response_loader is not None + else AdaptixLoader(DEFAULT_RETORT), + session=session_cls(transport=httpx.MockTransport(handler)), + ) + try: + yield client + finally: + await resolve(client.close()) + + +@pytest.fixture(autouse=True) +def no_retry_delays(monkeypatch): + from unihttp.middlewares import AsyncRetryMiddleware, RetryMiddleware + + async def no_sleep(self, attempt): + pass + + monkeypatch.setattr(RetryMiddleware, "_sleep", lambda self, attempt: None) + monkeypatch.setattr(AsyncRetryMiddleware, "_sleep", no_sleep) + + +@pytest.mark.parametrize( + "statuses,exception,attempts", + [ + ([503, 503, 200], None, 3), + ([503, 503, 503], ServerError, 3), + ([404], recipes.UserNotFound, 1), + ([401], ClientError, 1), + ], +) +async def test_error_hook_mapper_and_retry_work_together( + async_mode, statuses, exception, attempts +): + seen = [] + + def handler(request): + status = statuses[len(seen)] + seen.append(request) + return httpx.Response(status, json={"id": 1, "name": "Ada"}) + + async with client_for(response_retries, handler, async_mode) as client: + if exception: + with pytest.raises(exception): + await resolve(client.get_user(user_id=1)) + else: + assert await resolve(client.get_user(user_id=1)) == recipes.User(1, "Ada") + assert len(seen) == attempts + + +async def test_post_has_status_handling_but_no_retry(async_mode): + seen = [] + + def handler(request): + seen.append(request) + return httpx.Response(503, json={"error": "unavailable"}) + + async with client_for(response_retries, handler, async_mode) as client: + with pytest.raises(ServerError): + await resolve(client.create_user(name="Ada")) + assert [request.method for request in seen] == ["POST"] + + +@pytest.mark.parametrize("failure", [httpx.ConnectError, httpx.ReadTimeout]) +async def test_configured_transport_failures_retry(async_mode, failure): + seen = [] + + def handler(request): + seen.append(request) + if len(seen) < 3: + raise failure("temporary failure", request=request) + return httpx.Response(200, json={"id": 1, "name": "Ada"}) + + async with client_for(response_retries, handler, async_mode) as client: + assert (await resolve(client.get_user(user_id=1))).name == "Ada" + assert len(seen) == 3 + + +@pytest.mark.parametrize("status", [200, 404, 503]) +async def test_call_site_fallback_and_status_metadata(async_mode, status, caplog): + def handler(request): + return httpx.Response( + status, json={"id": 1, "name": "Ada"}, headers={"X-Request-ID": "request-123"} + ) + + find = response_errors.find_user_async if async_mode else response_errors.find_user + async with client_for(response_errors, handler, async_mode) as client: + if status == 503: + with pytest.raises(ServerError) as caught: + await resolve(find(client, 1)) + assert caught.value.status_code == 503 + assert caught.value.response.headers["X-Request-ID"] == "request-123" + assert "request-123" in caplog.text + else: + result = await resolve(find(client, 1)) + assert result == (recipes.User(1, "Ada") if status == 200 else None) + + +@pytest.mark.parametrize( + "failure,exception", + [(httpx.ConnectError, NetworkError), (httpx.ReadTimeout, RequestTimeoutError)], +) +async def test_call_site_does_not_hide_transport_errors(async_mode, failure, exception): + def handler(request): + raise failure("unavailable", request=request) + + find = response_errors.find_user_async if async_mode else response_errors.find_user + async with client_for(response_errors, handler, async_mode) as client: + with pytest.raises(exception): + await resolve(find(client, 1)) + + +@pytest.mark.parametrize("status", [200, 503]) +async def test_validation_handles_business_errors_without_intercepting_503( + async_mode, status +): + def handler(request): + return httpx.Response(status, json={"ok": False, "error": "Account disabled"}) + + mapper = ( + response_errors.async_status_errors + if async_mode + else response_errors.status_errors + ) + async with client_for(response_errors, handler, async_mode) as client: + with pytest.raises(response_errors.APIError if status == 200 else ServerError): + await resolve( + client.call_method( + response_errors.GetValidatedUser(1), middleware=[mapper] + ) + ) + + +@pytest.mark.parametrize("case", ["list", "envelope", "metadata", "missing-header"]) +async def test_response_shapes(async_mode, case): + user = {"id": 1, "name": "Ada"} + payload = [user] if case == "list" else {"data": user} if case == "envelope" else user + headers = {} if case == "missing-header" else {"X-Request-ID": "request-123"} + + def handler(request): + return httpx.Response(200, json=payload, headers=headers) + + methods = { + "list": response_metadata.ListUsers(), + "envelope": response_metadata.GetWrappedUser(1), + } + method = methods.get(case, response_metadata.GetUser(1)) + loader = response_metadata.envelope_loader if case == "envelope" else None + async with client_for( + response_errors, handler, async_mode, response_loader=loader + ) as client: + result = await resolve(client.call_method(method)) + expected = response_metadata.User(1, "Ada") + if case == "list": + assert result == [expected] + elif case == "envelope": + assert result == expected + else: + assert result == response_metadata.UserResponse( + expected, 200, headers.get("X-Request-ID") + ) + + +def test_envelope_method_uses_default_response_hook(): + from unihttp.method import BaseMethod + + assert response_metadata.GetWrappedUser.make_response is BaseMethod.make_response + + +def test_envelope_retort_keeps_model_validation(): + from adaptix.load_error import AggregateLoadError + + with pytest.raises(AggregateLoadError): + response_metadata.envelope_loader.load( + {"data": {"id": "invalid", "name": "Ada"}}, response_metadata.User + ) + + +def test_envelope_recipe_only_changes_loading(): + user = response_metadata.User(1, "Ada") + payload = {"data": {"id": 1, "name": "Ada"}} + assert response_metadata.envelope_loader.load(payload, response_metadata.User) == user + assert payload == {"data": {"id": 1, "name": "Ada"}} + assert response_metadata.envelope_retort.dump(user) == {"id": 1, "name": "Ada"} + assert ( + AdaptixLoader(DEFAULT_RETORT).load(payload["data"], response_metadata.User) + == user + ) + + +def test_envelope_recipe_applies_to_nested_users_too(): + user = response_metadata.User(1, "Ada") + assert response_metadata.envelope_loader.load( + [{"data": {"id": 1, "name": "Ada"}}], list[response_metadata.User] + ) == [user] + with pytest.raises(KeyError, match="data"): + response_metadata.envelope_loader.load( + {"id": 1, "name": "Ada"}, response_metadata.User + ) + + +async def test_model_loading_failure_is_not_retried(async_mode): + seen = [] + + def handler(request): + seen.append(request) + return httpx.Response(200, json={"unexpected": "not a User"}) + + async with client_for(response_retries, handler, async_mode) as client: + with pytest.raises(Exception) as caught: + await resolve(client.get_user(user_id=1)) + assert not isinstance(caught.value, HTTPStatusError) + assert len(seen) == 1 + + +class DownloadBody(httpx.SyncByteStream, httpx.AsyncByteStream): + def __init__(self, failure=None): + self.failure = failure + self.closed = False + + def __iter__(self): + yield b"a" * 65536 + if self.failure: + raise self.failure("read failed") + yield b"b" + + async def __aiter__(self): + for chunk in self: + yield chunk + + def close(self): + self.closed = True + + async def aclose(self): + self.closed = True + + +@pytest.mark.parametrize("status", [200, 302, 404, 500]) +async def test_stream_rejects_errors_and_closes(async_mode, status): + body = DownloadBody() + + def handler(request): + return httpx.Response(status, stream=body) + + checksum = ( + response_streaming.download_checksum_async + if async_mode + else response_streaming.download_checksum + ) + async with client_for( + response_streaming, handler, async_mode, streaming=True + ) as client: + if status == 200: + assert ( + await resolve(checksum(client, 1)) + == sha256(b"a" * 65536 + b"b").hexdigest() + ) + else: + with pytest.raises(HTTPStatusError) as caught: + await resolve(checksum(client, 1)) + assert caught.value.status_code == status + assert body.closed # Before closing the client itself. + + +@pytest.mark.parametrize( + "failure,exception", + [(httpx.ReadError, NetworkError), (httpx.ReadTimeout, RequestTimeoutError)], +) +async def test_stream_read_failure_propagates_and_closes(async_mode, failure, exception): + body = DownloadBody(failure) + + def handler(request): + return httpx.Response(200, stream=body) + + checksum = ( + response_streaming.download_checksum_async + if async_mode + else response_streaming.download_checksum + ) + async with client_for( + response_streaming, handler, async_mode, streaming=True + ) as client: + with pytest.raises(exception): + await resolve(checksum(client, 1)) + assert body.closed + + +async def test_stream_consumer_failure_closes_response(async_mode, monkeypatch): + body = DownloadBody() + + class BrokenConsumer: + def update(self, chunk): + raise ValueError("consumer failed") + + monkeypatch.setattr(response_streaming, "sha256", BrokenConsumer) + + def handler(request): + return httpx.Response(200, stream=body) + + checksum = ( + response_streaming.download_checksum_async + if async_mode + else response_streaming.download_checksum + ) + async with client_for( + response_streaming, handler, async_mode, streaming=True + ) as client: + with pytest.raises(ValueError, match="consumer failed"): + await resolve(checksum(client, 1)) + assert body.closed diff --git a/tests/test_docs_serialization.py b/tests/test_docs_serialization.py new file mode 100644 index 0000000..8cbc94a --- /dev/null +++ b/tests/test_docs_serialization.py @@ -0,0 +1,116 @@ +"""Contract tests for the snippets in the consolidated serialization guide.""" + +import importlib +from dataclasses import dataclass +from datetime import UTC, datetime + +import httpx +import pytest + +from examples import optional_fields, recipes +from examples.serialization import customization +from unihttp.clients.httpx import HTTPXSyncClient +from unihttp.http import UploadFile +from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader + + +@pytest.mark.parametrize("backend", ["adaptix", "pydantic", "msgspec"]) +def test_serializer_setup_tab(backend): + module = importlib.import_module(f"examples.serialization.{backend}") + method = module.CreateUser(user_name="Ada") + assert module.request_dumper.dump(method)["body"] == {"user_name": "Ada"} + response_data = {"id": 1, "user_name": "Ada"} + user = module.response_loader.load(response_data, module.User) + assert user == module.User(id=1, user_name="Ada") + + def handler(request): + assert request.method == "POST" + assert request.content == b'{"user_name": "Ada"}' + return httpx.Response(201, json=response_data) + + with HTTPXSyncClient( + base_url="https://api.example.com", + request_dumper=module.request_dumper, + response_loader=module.response_loader, + session=httpx.Client(transport=httpx.MockTransport(handler)), + ) as client: + assert client.call_method(method) == user + + +@pytest.mark.parametrize( + "retort", [customization.global_retort, customization.scoped_retort] +) +def test_adaptix_name_mapping_both_directions(retort): + dumper = AdaptixDumper(retort) + loader = AdaptixLoader(retort) + assert dumper.dump(customization.CreateUser(user_name="Ada"))["body"] == { + "userName": "Ada" + } + assert loader.load( + {"id": 1, "userName": "Ada"}, customization.User + ) == customization.User(1, "Ada") + + +def test_adaptix_scoped_mapping_does_not_rename_other_models(): + @dataclass + class OtherUser: + user_name: str + + assert customization.scoped_retort.dump(OtherUser("Ada")) == {"user_name": "Ada"} + assert customization.global_retort.dump(OtherUser("Ada")) == {"userName": "Ada"} + assert DEFAULT_RETORT.dump(customization.User(1, "Ada")) == { + "id": 1, + "user_name": "Ada", + } + + +def test_adaptix_normalization_only_changes_the_outgoing_value(): + method = customization.CreateUser(user_name=" Ada ") + dumper = AdaptixDumper(customization.normalized_retort) + loader = AdaptixLoader(customization.normalized_retort) + assert dumper.dump(method)["body"] == {"userName": "Ada"} + assert method.user_name == " Ada " + assert ( + loader.load({"id": 1, "userName": " Ada "}, customization.User).user_name + == " Ada " + ) + + +def test_adaptix_custom_timestamp_format(): + instant = datetime(2024, 1, 1, tzinfo=UTC) + dumper = AdaptixDumper(customization.timestamp_retort) + loader = AdaptixLoader(customization.timestamp_retort) + assert dumper.dump(customization.CreateEvent(starts_at=instant))["body"] == { + "starts_at": 1704067200.0 + } + assert loader.load( + {"id": 1, "starts_at": 1704067200}, customization.Event + ) == customization.Event(1, instant) + with pytest.raises(Exception): + loader.load({"id": 1, "starts_at": "not a timestamp"}, customization.Event) + + +@pytest.mark.parametrize( + "retort", + [ + customization.global_retort, + customization.scoped_retort, + customization.normalized_retort, + customization.timestamp_retort, + ], +) +def test_adaptix_recipes_keep_unihttp_providers(retort): + dumper = AdaptixDumper(retort) + assert dumper.dump(optional_fields.CreateUser(name="Ada"))["body"] == {"name": "Ada"} + assert ( + recipes.PutBytes(content=b"payload").build_http_request(dumper).raw == b"payload" + ) + request = recipes.UploadAvatar( + user_id=1, caption="Portrait", avatar=UploadFile(b"image", filename="avatar.png") + ).build_http_request(dumper) + assert request.url == "/users/1/avatar" + assert request.form == {"caption": "Portrait"} + assert request.file["avatar"][0] == "avatar.png" + assert AdaptixLoader(retort).load( + {"id": 1, "name": "Ada", "extra": 42}, recipes.User + ) == recipes.User(1, "Ada") diff --git a/zensical.toml b/zensical.toml new file mode 100644 index 0000000..86e6bb3 --- /dev/null +++ b/zensical.toml @@ -0,0 +1,105 @@ +[project] +site_name = "unihttp" +site_description = "unihttp – modern library for creating declarative API clients." +site_url = "https://unihttp.readthedocs.io/en/latest/" +repo_url = "https://github.com/goduni/unihttp" +repo_name = "goduni/unihttp" +edit_uri = "edit/master/site/" +docs_dir = "site" +site_dir = ".build/docs" +watch = ["src", "examples"] +extra_css = ["stylesheets/overview.css", "stylesheets/installation.css"] +nav = [ + { "Getting started" = [ + { "Overview" = "index.md" }, + { "Installation" = "getting-started/installation.md" }, + { "Sync quickstart" = "getting-started/quickstart.md" }, + { "Async quickstart" = "getting-started/async.md" }, + ] }, + { "User guide" = [ + "guides/index.md", + { "Requests" = [ + { "Methods and parameters" = "guides/methods.md" }, + { "Optional fields and Omitted" = "recipes/partial-updates.md" }, + { "File uploads" = "recipes/files.md" }, + ] }, + { "Clients and middleware" = [ + { "HTTP backends" = "integrations/backends.md" }, + { "Middleware" = "guides/middleware.md" }, + { "Authentication" = "recipes/authentication.md" }, + ] }, + { "Serialization" = "guides/serialization.md" }, + { "Responses and errors" = [ + { "Response data and metadata" = "guides/responses.md" }, + { "Error handling" = "guides/errors.md" }, + { "Retries" = "recipes/retries.md" }, + { "Streaming downloads" = "guides/streaming.md" }, + ] }, + ] }, + { "API reference" = [ + "reference/index.md", + { "Methods and binding" = "reference/methods.md" }, + { "Clients" = "reference/clients.md" }, + { "Markers and omitted values" = "reference/markers.md" }, + { "HTTP types" = "reference/http.md" }, + { "Serializers" = "reference/serializers.md" }, + { "Middleware and exceptions" = "reference/middleware.md" }, + ] }, + { "Coding agent skills" = "project/agent-skills.md" }, + { "Contributing" = "project/documentation.md" }, +] + +[project.theme] +language = "en" +features = ["navigation.indexes", "navigation.path", "navigation.footer", "content.code.copy", "content.action.edit", "content.tabs.link"] + +[[project.theme.palette]] +scheme = "slate" +toggle.icon = "lucide/sun" +toggle.name = "Switch to light mode" + +[[project.theme.palette]] +scheme = "default" +toggle.icon = "lucide/moon" +toggle.name = "Switch to dark mode" + +[project.theme.font] +text = false +code = false + +[project.markdown_extensions.attr_list] + +[project.markdown_extensions.md_in_html] + +[project.markdown_extensions.pymdownx.superfences] + +[project.markdown_extensions.pymdownx.highlight] + +[project.markdown_extensions.pymdownx.tabbed] +alternate_style = true + +[project.markdown_extensions.pymdownx.snippets] +base_path = ["."] +check_paths = true +dedent_subsections = true + +[project.plugins.mkdocstrings.handlers.python] +paths = ["src"] + +[project.plugins.mkdocstrings.handlers.python.options] +extensions = ["scripts/docs_griffe.py:UnihttpDocsExtension"] +docstring_style = "google" +show_source = false +show_signature_annotations = true +separate_signature = true +show_root_heading = true +heading_level = 2 +members_order = "source" +show_if_no_docstring = true +merge_init_into_class = true +show_signature = true + +[project.plugins.redirects.redirect_maps] +"integrations/adaptix.md" = "guides/serialization.md" +"integrations/pydantic.md" = "guides/serialization.md" +"integrations/msgspec.md" = "guides/serialization.md"