Skip to main content

ClientX

Typed, declarative HTTP API clients for Python 3.12+.

PyPI Python versions CI License: MIT

Overview

ClientX is a declarative API client framework designed to make writing and maintaining API clients easier while keeping the client contract explicit and well documented.

For client authors, ClientX reduces boilerplate by turning typed endpoint definitions into concrete httpx2 requests and centralizing request/response behavior. For client consumers, it pushes API contracts and guard rails into the client itself, helping prevent avoidable runtime mistakes and making integrations more predictable.

The result is less scaffolding and more focus on outcomes: authors, human or AI, spend less time on plumbing, and the developers and AI agents calling your API spend less time guessing how to use it correctly. The same endpoints become tools an AI model can call, described by your docstrings and type hints, with errors it can act on.

Quickstart

from typing import Annotated

from clientx import ClientX, Header, Json, Query, Resource, method
from pydantic import BaseModel


class User(BaseModel):
    id: int
    name: str


class NewUser(BaseModel):
    name: str


class Users(Resource, prefix="/users"):
    @method.get("/{user_id}")
    def retrieve(self, user_id: int) -> User:
        """Fetch one user by ID."""
        ...

    @method.get()
    def search(self, name: Annotated[str | None, Query()] = None) -> list[User]:
        """List users, or only those with this name."""
        ...

    @method.post()
    def create(
        self,
        user: Annotated[NewUser, Json()],
        request_id: Annotated[str | None, Header()] = None,
    ) -> User:
        """Create a user."""
        ...


class ExampleAPI(ClientX, user_agent="example-app/1.0"):
    users = Users()


with ExampleAPI("https://api.example.com") as api:
    user = api.users.retrieve(42)  # GET /users/42 -> User
    matches = api.users.search(name="Ada")  # GET /users?name=Ada -> list[User]
    new = api.users.create(NewUser(name="Ada"), request_id="r-1")  # POST /users, JSON body, request-id header -> User
  • Endpoint bodies never run. ClientX builds each request from the method's signature, sends it, and decodes the response into the return annotation.
  • Type checkers see the real signatures: api.users.retrieve(user_id: int) -> User.
  • A 4xx or 5xx response raises httpx2.HTTPStatusError.
  • The with block closes the client's connections when it ends. It's optional: a long-lived client is created once and closed with close() at shutdown, as Closing a client explains.
  • For async code, subclass AsyncClientX and AsyncResource, write the endpoints as async def methods, and await them, as Async clients explains.
  • Using mypy? Turn off its empty-body check for your client modules, as Defining endpoints explains.

Why ClientX

ClientX is inspired by FastAPI, which reads type hints to define server endpoints. ClientX applies the same idea to the client side:

  • The method signature is the contract. Path placeholders, query parameters, headers and bodies come from the method's parameters and annotations, so there's no request-building code to keep in sync.
  • The return annotation decodes the response. -> User returns the JSON body validated as a User, -> Iterator[str] streams it line by line, and -> Response returns the response itself.
  • Type checkers see real types. Decorated methods keep their signatures, so editors and type checkers see the actual parameters and return types.
  • Sync or async. Write endpoints as def methods on a ClientX, or as async def methods on an AsyncClientX, with the same decorators.
  • Mistakes surface early. A missing return annotation, a parameter that doesn't say where it goes, a placeholder that names no parameter, or a type ClientX can't decode raises an error when the class is defined, not on the first request.
  • Pydantic v2 throughout. Send models as JSON bodies, or spread them into query parameters, headers or form fields, and decode responses into models.
  • Built on httpx2. A client is an httpx2.Client, or an httpx2.AsyncClient, so every option is available, including auth, timeouts, proxies and custom transports.
  • Ready for AI agents. clientx.tools turns each endpoint into a tool a model can call: its description from the docstring, a JSON Schema of its arguments, and errors that tell the model what went wrong, never your credentials.

Features

  • Declarative endpoint definitions with HTTP verb decorators.
  • Responses decoded from the return annotation, with streaming, and your own decoder when you need one.
  • Path parameters filled from method arguments and percent-encoded (e.g. "/users/{user_id}").
  • Request parts declared with helpers named like FastAPI's (Query, Header, Json, Body, Form, File): every parameter but a path placeholder's says where it goes.
  • Resources that group endpoints under a path prefix.
  • Built-in deprecation warnings per endpoint.
  • Full access to httpx2.Client configuration through ClientX(...) arguments.
  • Async clients (AsyncClientX, AsyncResource) with the same decorators, for async def endpoints.
  • AI tools from the same endpoints (clientx.tools): descriptions from docstrings, JSON Schemas, and errors a model can act on.

Project status

ClientX is a passion project that comes from my experience integrating APIs. Every small prototype against a new API means writing the same boilerplate again, and third-party clients are hit or miss. ClientX lets me focus on outcomes rather than plumbing, and I hope it does the same for you. I maintain it in my spare time, so replies may take a while, but issues and pull requests are always welcome.

ClientX is pre-1.0, so the API may change between minor versions. Changes are listed in the changelog.

Install

pip install clientx

Using an AI coding assistant? Point it at llms.txt, a compact guide to ClientX's patterns and pitfalls.

Guide

  • Defining endpoints: the verb decorators and their options, the rules for an endpoint method, deprecating endpoints, and endpoint names.
  • Building requests: how parameters become the path, query string, headers and body.
  • Responses: how the return annotation decides what an endpoint returns, streaming, your own decoder, and errors for 4xx and 5xx responses.
  • Resources: grouping endpoints under a path prefix, nesting them, and plain methods for logic such as pagination.
  • Client configuration: creating and closing a client, the base URL and User-Agent class defaults, authentication, logging and event hooks.
  • Async clients: AsyncClientX and AsyncResource for async def endpoints, concurrent requests, and async streaming.
  • Testing: testing a client without the network.
  • AI tools: a client's endpoints as tools a model can call.
  • Errors: the errors ClientX raises, and when.
  • API reference: every public name, with its signature and arguments.

Development

See CONTRIBUTING.md for setup, checks, and conventions.

Acknowledgments

ClientX is inspired by FastAPI and built on Pydantic and httpx2, and I'm grateful to the developers behind all three. It's an independent project, though, and isn't affiliated with or endorsed by any of them.

License

ClientX is released under the MIT License.

Metadata

Release files for clientx 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for clientx 0.2.1
File Size Uploaded Provenance Actions
clientx-0.2.1.tar.gz 58.8 kB With provenance Details for clientx-0.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for clientx 0.2.1
File Interpreter ABI Platform Actions
clientx-0.2.1-py3-none-any.whl Python 3 none any Details for clientx-0.2.1-py3-none-any.whl

Total release size: 125.5 kB

Release files / clientx-0.2.1.tar.gz

Download URL clientx-0.2.1.tar.gz
Size 58.8 kB
Tags Source
SHA-256 checksum
How to use checksums
0a5cdab5f70e1644500f333bef4ecf82696b0dc47745d9b1928afec0a5163ba9
BLAKE2b-256 checksum
How to use checksums
c67371d6c4ca785bc1ddba6913fb9f8d3da896f8690b19ed528751e4e471aa66
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

Release files / clientx-0.2.1-py3-none-any.whl

Download URL clientx-0.2.1-py3-none-any.whl
Size 66.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b86f48a55d15f6d859c7578d6d1d766689e54805d3741e54a776db16cd0bf0ff
BLAKE2b-256 checksum
How to use checksums
257e97c10d93bdaf928adba0c453fde3d8940d655ba291602db12ff3fa6e61db
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

Security for clientx 0.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for clientx-0.2.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page