unihttp
unihttp is a modern library for creating declarative API clients.
Documentation
Table of Contents
Features
- Declarative: Define API methods using standard Python type hints.
- Type-Safe: Full support for static type checking.
- Backend Agnostic: Works with
httpx, httpx2, aiohttp, requests, niquests, zapros and the standard library urllib.
- Extensible: Powerful middleware and error handling systems.
Installation
To include a specific HTTP backend (recommended):
pip install "unihttp[httpx]" # For HTTPX (Sync/Async) support
# OR
pip install "unihttp[httpx2]" # For HTTPX2 (Sync/Async) support
# OR
pip install "unihttp[niquests]" # For niquests (Sync/Async) support
# OR
pip install "unihttp[requests]" # For Requests (Sync) support
# OR
pip install "unihttp[aiohttp]" # For Aiohttp (Async) support
# OR
pip install "unihttp[zapros]" # For Zapros (Sync/Async) support
The standard library urllib backend (UrllibSyncClient) requires no extra —
it works out of the box with a plain pip install unihttp, which is handy for
dependency-free environments.
Serialization Backends
unihttp allows you to choose your preferred serialization framework:
- Adaptix (recommended): High-performance serialization for standard Python types (dataclasses, TypedDict).
- Pydantic: Native support for Pydantic models.
- msgspec: Native support for
msgspec.Struct models — ideal if you already define your models as structs and want them serialized directly.
You will need to pass the appropriate request_dumper and response_loader when initializing your client.
See Powered by Adaptix, Pydantic Integration or
msgspec Integration for configuration details.
Quick Start
1. Define Methods
unihttp uses markers to map method arguments to HTTP request components.
from dataclasses import dataclass
from unihttp.markers import Path, Query, Body, Header, Form, File
from unihttp.method import BaseMethod
@dataclass
class User:
id: int
name: str
email: str
@dataclass
class GetUser(BaseMethod[User]):
__url__ = "/users/{id}"
__method__ = "GET"
id: Path[int]
compact: Query[bool] = False
@dataclass
class CreateUser(BaseMethod[User]):
__url__ = "/users"
__method__ = "POST"
name: Body[str]
email: Body[str]
2. Client Implementation Strategies
You can choose between a purely declarative style using bind_method or a more imperative style using call_method.
Option A: Declarative Client (via bind_method)
This is the most concise way to define your client. You simply bind the methods to the client class.
Note
PyCharm Users: There is currently a known issue with displaying type hints for descriptors like bind_method (
see PY-51768). This is expected to be fixed in the 2026.1 version.
from unihttp.bind_method import bind_method
from unihttp.clients.httpx import HTTPXSyncClient
from unihttp.serializers.adaptix import DEFAULT_RETORT, AdaptixDumper, AdaptixLoader
class UserClient(HTTPXSyncClient):
get_user = bind_method(GetUser)
create_user = bind_method(CreateUser)
client = UserClient(
base_url="https://api.example.com",
request_dumper=AdaptixDumper(DEFAULT_RETORT),
response_loader=AdaptixLoader(DEFAULT_RETORT),
)
user = client.get_user(id=123)
Option B: Imperative Client (via call_method)
If you need more control, need to preprocess arguments, or simply prefer explicit method definitions, you can define
methods in the client and use call_method.
class UserClient(HTTPXSyncClient):
def get_user(self, user_id: int) -> User:
# You can add custom logic here before the call
return self.call_method(GetUser(id=user_id))
def create_user(self, name: str, email: str) -> User:
return self.call_method(CreateUser(name=name, email=email))
Markers Reference
unihttp provides several markers to define how arguments are serialized:
Path: Substitutes placeholders in the __url__ (e.g., /users/{id}).
Query: Adds parameters to the URL query string.
Body: Sends data as the JSON request body.
Header: Adds HTTP headers to the request.
Form: Sends data as form-encoded (application/x-www-form-urlencoded).
File: Used for multipart file uploads.
UploadFile (from unihttp.http): A wrapper for file uploads that allows specifying a filename and content
type (e.g., UploadFile(b"content", filename="test.txt")).
Raw: Sends a pre-built bytes/str value as the request body, bypassing serialization entirely. Mutually
exclusive with Body and with Form/File — combining Raw with either raises a ValueError.
Streaming Methods
For endpoints whose body you want to read incrementally (downloads, SSE, large payloads) instead of buffering it
fully, subclass StreamMethod instead of BaseMethod. There is no response_loader step — the body is never
fully read.
from dataclasses import dataclass
from unihttp.method import StreamMethod
from unihttp.markers import Path
@dataclass
class DownloadFile(StreamMethod):
__url__ = "/files/{id}"
__method__ = "GET"
id: Path[int]
Either way, the call returns immediately with status_code/headers available; .data is an unconsumed
ChunkStream (or AsyncChunkStream) — use it as a context manager so the underlying connection is released even if
you stop iterating early.
Option A: Declarative Client (via bind_method)
bind_method detects StreamMethod subclasses automatically and routes them through call_method_stream.
class FileClient(HTTPXSyncClient):
download_file = bind_method(DownloadFile)
client = FileClient(base_url="https://api.example.com", ...)
with client.download_file(id=123).data as stream:
for chunk in stream:
f.write(chunk)
# Async client, note the extra `await`
async with (await client.download_file(id=123)).data as stream:
async for chunk in stream:
await f.write(chunk)
Option B: Imperative Client (via call_method_stream)
with client.call_method_stream(DownloadFile(id=123)).data as stream:
for chunk in stream:
f.write(chunk)
# Async client, note the extra `await`
async with (await client.call_method_stream(DownloadFile(id=123))).data as stream:
async for chunk in stream:
await f.write(chunk)
Use __chunk_size__ on the method to control how many bytes are read per chunk (defaults to 65536).
Middleware
Middleware allows you to intercept requests and responses globally. This is useful for logging, authentication, or
modifying requests on the fly.
from unihttp.middlewares.base import Middleware
from unihttp.http.request import HTTPRequest
from unihttp.http.response import HTTPResponse
class LoggingMiddleware(Middleware):
def handle(self, request: HTTPRequest, next_handler) -> HTTPResponse:
print(f"Requesting {request.url}")
# Call the next handler in the chain
response = next_handler(request)
print(f"Status: {response.status_code}")
return response
client = HTTPXSyncClient(
# ...
middleware=[LoggingMiddleware()]
)
Per-Call and Per-Method Middleware
Client-level middleware runs for every call. To scope middleware to a single request or a single bound method, pass
middleware to call_method/call_method_stream or bind_method. Chain order is outermost-first: client
self.middleware, then these.