apiroute
Build API clients declaratively: one @route per endpoint, safe defaults, httpx underneath. REST, GraphQL and SOAP fit in one client class and share its auth, retries, hooks and test mocks. A Python port of the Ruby gem client-api-builder.
- One decorator per call.
@route("/users/{id}")for REST andgraphql_route("query ...")for GraphQL. Signatures are checked when the class is created, so a typo fails at import time, not in production. - GraphQL built for hand-written queries. You write the query, apiroute checks it against the API's schema when the class is created, fills its variables from the method's arguments, unwraps
data, raisesGraphQLErrorwith any partial data, and won't re-send a mutation that may already have run. - Pagination for any API.
paginate=ItemCursor(),NextUrl(),Cursor(...),PageNumber()orOffset()turns a list route into a lazy iterator over every page's items, sync or async, with guards against endless loops and against next-page URLs on other hosts. - Retries you can trust. Exponential backoff with jitter and
Retry-Aftersupport, and ashould_retryhook for anything else. - Tokens that refresh themselves.
OAuth2ClientCredentialsandOAuth2RefreshTokenfetch a token, renew it before it expires, and after a 401 refresh it and send the request once more. - Rate limits, revalidation and tracing.
rate_limiter=waits instead of getting a 429,conditional_cache=revalidates GETs with ETags, andtelemetry=traces each attempt with OpenTelemetry. - Event streams.
stream="sse","ndjson"or"lines"yields server-sent events, JSON values or lines as they arrive, and an SSE stream reconnects withLast-Event-ID. - Typed results. A return annotation turns JSON into a pydantic model or a dataclass.
- Sync and async from the same class.
client.get_user(...)orawait client.aio.get_user(...). - Testing included.
MockTransportanswers requests by operation name, path or predicate,block_network()stops real calls, and a pytest plugin provides both as fixtures. - Code generation.
apiroute generate openapi|wsdl|graphqlturns OpenAPI/Swagger specs, WSDLs, and GraphQL schemas with your own.graphqloperations into clients, with models. - Small footprint. The only required dependency is httpx; pydantic, SOAP, GraphQL checks and codegen are optional extras.
from apiroute import Client, graphql_route, route
class GitHub(Client):
base_url = "https://api.github.com"
@route("/users/{username}") # REST
def get_user(self, username: str) -> dict: ...
@graphql_route(
"""
query Repo($owner: String!, $repoName: String!) {
repository(owner: $owner, name: $repoName) { stargazerCount }
}
""",
data="repository.stargazerCount",
) # GraphQL, on the same client
def stars(self, owner: str, repo_name: str) -> int: ...
Installation
pip install apiroute # or: uv add apiroute
pip install apiroute[pydantic] # to return pydantic models
pip install apiroute[codegen] # to generate clients from OpenAPI/Swagger specs, WSDLs and GraphQL schemas
pip install apiroute[soap] # to run generated SOAP clients
pip install apiroute[graphql] # to check GraphQL documents against the API's schema when a class is created
pip install apiroute[otel] # to trace requests with OpenTelemetry
apiroute needs Python 3.10 or newer, and httpx.
Quick start
from apiroute import Client, Query, Retries, Section, route
class GitHubApi(Client):
base_url = "https://api.github.com"
headers = {
"Accept": "application/vnd.github.v3+json",
"Authorization": lambda self: f"Bearer {self.access_token}",
}
retries = Retries.exponential(attempts=5, initial=0.1, max=10, jitter=True)
def __init__(self, access_token: str, org: str, **kwargs):
super().__init__(**kwargs) # base_url=..., transport=...
self.access_token = access_token
self.org = org
@route("/users/{username}") # GET, inferred from the name
def get_user(self, username: str) -> dict: ...
@route("/users/{username}/repos", query={"per_page": "{per_page}"})
def get_repos(self, username: str, per_page: int = 30) -> list: ...
# POST, inferred; {org} comes from self.org
@route("/orgs/{org}/repos", body={"name": "{name}", "private": "{private}"})
def create_org_repo(self, name: str, private: bool = False) -> dict: ...
@route("POST", "/uploads")
def create_upload(self, body: dict) -> dict: ...
class issues(Section):
inherit = ("headers",)
@route("/repos/{owner}/{repo}/issues")
def list(self, owner: str, repo: str, state: Query = None) -> list: ...
gh = GitHubApi(access_token="ghp_...", org="acme")
gh.get_user("octocat")
gh.issues.list("acme", "api", state="open")
gh.with_options(timeout=5, retries=1).get_repos("octocat")
Routes
@route([method,] path, query=..., body=..., expected=..., returns=..., timeout=..., stream=...)
-
Method inference. A name that is, or starts with,
post,create,addorinsertfollowed by_is POST.put,update,modifyandchangeare PUT,patchis PATCH, anddelete,removeanddestroyare DELETE. Anything else is GET. -
Placeholders. Write
{name}in paths, query values and body values (paths also take:name). The value comes from the argument with that name, or else from the client's attribute or method. A string that is exactly"{name}"keeps the value's type. -
Other arguments must be annotated with
Query,Query("name"),Header("X-Name")orBody. The exception is a parameter namedbodyon a route without a body template. Otherwise the class fails to build withRouteDefinitionError. -
Returns. Parsed JSON by default (
Nonefor an empty body), orreturns="text" | "bytes" | "response". -
Errors. Any status outside
expected(any 2xx when it's unset) raisesUnexpectedResponse, which carries the.response. -
Errors inside a 200.
check=, a callable taking thehttpx.Response, accepts or rejects a response whose status is expected, for APIs that always answer 200 and put the failure in the body. ReturnFalse(or any false value butNone) to raiseUnexpectedResponse, raise an exception of your own, or returnNoneor a true value to accept. It runs inside the retry loop, before the body is parsed, so what it raises goes throughshould_retry. Astream=route can't take it, since its body isn't read yet. For a check every route shares, overridecheck_response.@route("/orders", check=lambda response: response.json()["status"] != "error") def list_orders(self) -> dict: ...
-
Falling back to the client. A parameter whose default is
FROM_CLIENTtakes the client's attribute of the same name when the caller leaves it out:def list_members(self, org: str = FROM_CLIENT).
Response hook
Give the method a keyword-only parameter annotated Result and its body runs after the request. The parameter receives the processed result (parsed JSON, or whatever returns asks for), and a value the body returns replaces it. Returning None keeps the result. Callers never see the parameter.
@route("/users/{username}")
def get_login(self, username: str, *, data: Result) -> str:
return data["login"]
gh.get_login("octocat") # "octocat"
For type checkers, mark the parameter with its default instead: *, data: dict = FROM_RESPONSE. Its annotation is then the response's own type (a model there converts the response, as with Result), and callers aren't asked for it.
Streaming
stream= |
Destination | Returns |
|---|---|---|
"file" |
the path in a file parameter, written wb |
the httpx.Response |
"io" |
the writable object in an io parameter, left open |
the httpx.Response |
"iter" |
none | a ChunkIterator of bytes (an AsyncChunkIterator through .aio) |
"lines" |
none | an EventIterator of the body's lines as str, in its declared charset, else UTF-8 (an AsyncEventIterator through .aio) |
"ndjson" |
none | an EventIterator of JSON values, one per line (blank lines skipped) |
"sse" |
none | an EventIterator of ServerSentEvents from a text/event-stream body |
@route("/files/{id}", stream="file")
def download(self, id: int, file: str): ...
with gh.get_events() as events: # stream="iter"; the with block closes the connection
for chunk in events:
...
- The status is checked before any of the body is read. An error response raises
UnexpectedResponsewith its body readable, and nothing is written: an existing file is left untouched. - File paths with a null byte or a
..segment are rejected before the request is sent, as in the Ruby gem. Absolute paths are allowed. - Opening the stream is retried like any request; a failure while the body is being read is raised, not retried.
- In async calls, an
ioobject whosewritereturns an awaitable (such as an aiofiles file) is awaited.
Lines, NDJSON and server-sent events
stream="lines", "ndjson" and "sse" decode the body as it arrives. Each item is yielded as soon as its line (or, for SSE, its event) is complete, so a chat completion or a log tail can be shown while it streams:
from apiroute.streaming import ServerSentEvent
class Llm(Client):
base_url = "https://api.example.com"
timeout = None # a stream may sit idle longer than a request should
@route("POST", "/v1/chat", stream="sse")
def chat(self, body: dict) -> Iterator[ServerSentEvent]: ...
@route("/v1/jobs/{id}/log", stream="ndjson")
def job_log(self, id: str) -> Iterator[LogLine]: ... # each line becomes a LogLine
with llm.chat({"messages": [...]}) as events:
for event in events:
if event.data == "[DONE]":
break
print(event.json()["delta"], end="")
ServerSentEventhasdata(itsdata:lines joined with newlines),event("message"unless the event names one),id(the last event ID the stream set) andjson(). Events are parsed as the HTML standard says: comments and events without data are skipped, and an event the body ends in the middle of is dropped.- NDJSON values are converted like paginated items: by
model=, or byXin anIterator[X]return annotation. A line that isn't JSON raisesjson.JSONDecodeErrorafter the values before it have been yielded. - Reconnecting. When an SSE stream's connection fails mid-body, it reconnects as the route's
retriesallow: the same request, sent withLast-Event-IDset to the last event ID received, after the backoff delay or the server'sretry:time, whichever is longer. Failures are counted from one again after each event, and a204answer ends the stream. As with retries, a route that isn't idempotent (aPOST, unless it saysidempotent=True) never reconnects, since that would send it again. A body that ends cleanly is the end of the stream; lines and NDJSON streams never reconnect. - Closing. Like
stream="iter", the connection stays open until the body ends or the iterator is closed; use awithblock (async withthrough.aio) to close it when you stop early.
Typed returns
A return annotation that contains a dataclass or a pydantic model converts the JSON response. That includes -> User, -> list[User], -> dict[str, User] and -> User | None. Routes without a def take model= instead. Plain annotations (dict, list, Any) leave the JSON as parsed.
@route("/users/{username}")
def get_user(self, username: str) -> User: ...
list_users = route("/users", model=list[User])
- Pydantic models are validated with pydantic's
TypeAdapter, with its usual type coercion. Install it withpip install apiroute[pydantic]. - Dataclasses are built by apiroute itself, so they don't need pydantic. Keys the dataclass doesn't declare are ignored, and a missing required field fails.
- Errors. A body that doesn't fit raises
ResponseValidationError, which carries the.responseand the underlying.error. - With a response hook, the
Resultparameter's type is used (user: Annotated[User, Result()]). The return annotation then describes what the hook returns. - Late-defined types. A model defined below the client class (
-> "Team") is looked up on the first call. - Other return modes. Only JSON is converted;
returns="text","bytes","response"and streams are left alone.
Routes without a def
For simple endpoints, assign the route and let the class generate the method, as the Ruby gem does:
class GitHubApi(Client):
org: str # declared, so {org} falls back to self.org
get_user = route("/users/:username") # (*, username)
list_repos = route("/orgs/{org}/repos", query={"page": "{page}"}) # (*, org=FROM_CLIENT, page)
create_gist = route("/gists") # (*, body=None), POST
gh.get_user(username="octocat")
gh.list_repos(page=2)
- Every placeholder becomes a keyword-only parameter, in path, then query, then body order.
- A name the class declares (a class attribute, method, property or annotation such as
org: str) is optional and falls back to the client. In a section, declare it on the section; the value still comes from the root client. - POST, PUT and PATCH routes without a body template take an optional
body. help(),inspect.signatureand wrong-argumentTypeErrors work. Editors and type checkers can't see a signature made at runtime, though, so prefer adefwhere autocomplete and type checking matter.
Namespaces
Routes declared inside a namespace block get its path prefix, as in the gem. Blocks nest.
class Api(Client):
with namespace("/admin"):
list_users = route("/users") # GET /admin/users
@route("/users/{id}")
def delete_user(self, id: int): ... # DELETE /admin/users/{id}
Per-request options
client.with_options(headers=..., query=..., body=..., timeout=..., retries=..., returns=...) returns a view of the client whose route calls also send these options. Calls can be chained.
headersandquerymerge over the class and route values. ANonevalue leaves that header or param out.bodyis shallow-merged over the route's body when both are dicts, and aNonevalue removes that key. Any other body (a list or a string, or when the route has no dict body) replaces the route's body.url, an absolute URL, replaces the base URL, path and query; the client's ownquery_paramsare added when it doesn't carry them. Paginated routes use it for next-page URLs.
@route("/users", body={"user": {"name": "{name}"}, "notify": True})
def create_user(self, name: str) -> dict: ...
client.with_options(body={"notify": None, "source": "import"}).create_user("Ann")
# sends {"user": {"name": "Ann"}, "source": "import"}
Pagination
REST APIs page their lists in many ways. paginate= takes a strategy from apiroute.pagination and turns a route into an iterator over the items of every page:
from collections.abc import Iterator
from apiroute.pagination import ItemCursor, NextUrl
class Stripe(Client):
base_url = "https://api.stripe.com"
@route("GET", "/v1/customers", paginate=ItemCursor())
def customers(self, limit: Query = None, email: Query = None) -> Iterator[Customer]: ...
class GitHub(Client):
base_url = "https://api.github.com"
@route("GET", "/repos/{owner}/{repo}/issues", paginate=NextUrl())
def issues(self, owner: str, repo: str, per_page: Query = None) -> Iterator[dict]: ...
for customer in stripe.customers(limit=100): # pages fetched as iteration reaches them
...
first_ten = list(itertools.islice(gh.issues("octocat", "Hello-World"), 10))
for page in stripe.customers().pages(): # whole pages: .items, .data, .response, .index
...
async for customer in stripe.aio.customers():
...
| Strategy | For | Next page | Stops when |
|---|---|---|---|
Cursor(param, token="next_cursor", header=None, location="query") |
Slack, Google, Notion | param set to the token at the body's dotted path token, or in response header header; location="body" sends it in the body |
the token is missing, null or "" |
ItemCursor(param="starting_after", field="id", has_more="has_more", items="data") |
Stripe | param set to the last item's field |
has_more is false |
NextUrl(link="next", path=None) |
GitHub, Django REST framework | the Link header's rel="next" URL, or the URL at the body's dotted path |
there's no next URL |
PageNumber(param="page", start=1, size=None, total_pages=None) |
page numbers | param plus one |
an empty page; the body's total_pages; else a page shorter than the size parameter sent |
Offset(param="offset", limit="limit", total=None) |
offset and limit | param plus the items received |
an empty page; the body's total; else a page shorter than the limit sent |
-
Where the items are. Each strategy takes
items, a dotted path to the page's list ("data","response.results"), where""(the default, except forItemCursor) means the body is the list. A path that's missing or isn't a list raisesValueError. -
Every page is an ordinary request. It goes through the client's headers,
on_request, retries (each page retried on its own), idempotency keys and status checks, with the caller's arguments (filters, page size) on every page. The first page is requested as called, so passing a cursor or page starts there. -
Items are converted by
model=, or byXin anIterator[X]return annotation; otherwise they're dicts..pages()gives each page's items as decoded. -
Lazy and restartable. Nothing is requested until iteration starts. Cap it with
isliceorbreak;.pages()starts again from the first page. -
Explicit signals win.
PageNumberandOffsetfall back on the short-page rule only when the API gives no total, and only when the request sent a page size: a server that caps the page size below what was asked makes a full page look short. Offsets and page numbers can also skip or repeat items when the list changes while you iterate; prefer a cursor when the API has one. -
It can't loop or leak. A next request equal to the one before (the same cursor again) raises
ValueErrorrather than paging forever, as doesItemCursormeeting an empty page that says there's more. A next URL resolves against the page's URL, and one on another scheme, host or port thanbase_urlraisesValueErrorbefore anything is sent to it, so the client's credentials never go elsewhere. -
Custom strategies. Any object with
items(page)(the page's list) andnext(page)(aNextRequestorNone) works. APagehasdata,response,request(theNextRequestthat asked for it),index,itemsandsent(name)(a query parameter as this page's request sent it).NextRequest(query=..., body=..., url=...)merges query and body values over the caller's arguments, or replaces the URL:class Since: def items(self, page): return page.data["events"] def next(self, page): if page.response.headers.get("X-Done") == "1": return None return NextRequest(query={"since": page.data["last_seen"]})
-
A paginated route reads JSON pages itself, so it can't also take
returns=,stream=,decoder=or aResultparameter.
Long-running operations
Some APIs answer a request that takes a while with 202 Accepted and a URL to check on it. poll=Poll(...) makes the method wait for the operation and return its result:
from apiroute.polling import Poll
class Reports(Client):
@route("POST", "/v1/exports", poll=Poll(interval=2, timeout=600))
def export(self, body: dict) -> Export: ...
@route("POST", "/v1/operations", poll=Poll(status="done", result="response", error="error"))
def start(self, body: dict) -> dict: ... # Google's long-running operations
- When it polls. It polls when the response is a
202with a status URL inOperation-Location,Azure-AsyncOperationorLocation, or a200or201with either of the first two. Any other response is the result, as it would be withoutpoll=. It GETs the status URL everyintervalseconds (or the response'sRetry-After, when that's longer), and a later202may move the status URL. - When it's done. The operation is done when the status body's
statusfield (a dotted path,"status"by default) is insucceeded("succeeded","completed","done"...; case doesn't matter) or istrue. The result is that body, the value at the dotted pathresult, or the body at the URL the dotted pathresult_urlnames (Azure'sresourceLocation). It's converted by the route's model or return annotation. A status body without a status field is the result too, and a303 See Otheris followed to it. - Failures. A status in
failed("failed","canceled","error"...), or a seterrorfield, raisesapiroute.polling.OperationFailed, with.status,.bodyand.response. Running pasttimeoutseconds (default 600;Nonewaits for ever) raisesPollTimeout. - Polls are ordinary requests. They're GETs with the client's headers, auth, hooks, rate limiter and tracing, retried as reads are, even when the first request was a
POSTthat isn't retried. A status URL on another host than the request's is refused rather than sent the client's credentials.
Sections
A nested class that subclasses Section groups routes under the client, as client.<class name>:
class Api(Client):
base_url = "https://api.example.com"
headers = {"Authorization": lambda self: f"Bearer {self.token}"}
class users(Section):
inherit = ("headers",) # use the client's headers too
list = route("/users")
class uploads(Section):
base_url = "https://uploads.example.com" # its own host
headers = {"Authorization": lambda self: f"Upload {self.upload_token}"}
create = route("/files")
api.users.list()
api.uploads.create(body=data)
- A section uses its parent's
base_urlunless it sets one. It inherits nothing else unless listed ininherit, as in the gem:"headers"and"query_params"merge under the section's own, and"retries"and"timeout"are the root client's unless the section sets its own. Generated sections inherit all four, so a client's retry and timeout policy, from--base-classor a subclass, covers every route. {name}placeholders, callable headers, the overridable methods and the transport all belong to the root client, so a section can use the client's state.- Sections nest, are created once per client, and remain reachable as classes (
Api.users).
Retries
retries = Retries(attempts=3, sleep=0.5) # 3 attempts in total, 0.5 s apart
retries = Retries.exponential(attempts=5, initial=0.1, max=10) # 0.1, 0.2, 0.4, 0.8 s
retries = Retries(attempts=5, sleep=0.1, backoff=2, max_sleep=10, jitter=True)
-
attemptsis the total number of attempts. The default is one, so nothing is retried until you configure it. -
The sleep before retry n is
sleep * backoff ** (n - 1), capped atmax_sleep.jitter=Truesleeps a random time up to that; a number from 0 to 1 shortens it by up to that fraction. -
Only timeouts, network errors and protocol errors are retried, unless
should_retrysays otherwise. A retriedUnexpectedResponsewith aRetry-Afterheader waits that long when it is longer than the backoff delay (never shorter:Retry-After: 0still backs off), capped atmax_sleep. -
Only safe methods are retried once the server may have the request. A read timeout or a connection dropped mid-response may mean the server already did the work, so those errors are retried only for
GET,HEADandOPTIONSroutes.POST,PUT,PATCHandDELETEroutes aren't retried after them, so a charge or an order can't happen twice. Errors before anything was sent (connection refused, connect and pool timeouts), and statuses you retry inshould_retry(429, 503), are retried for every route. -
Generated clients follow the same rule. OpenAPI
POSToperations and every SOAP operation (SOAP is alwaysPOST) aren't retried after a read timeout. A hand-written base class (--base-class) can setidempotency_key, or overrideshould_retryfor statuses. -
Per request, from the client: override
idempotent(self, request)to decide for each call.TrueorFalseoverrides the route, andNonekeeps it. That's how a generated client marks its safe operations from its base class, since it can't edit the routes:class TradingAuth(Client): # eBay's Trading API: every operation is a SOAP POST def idempotent(self, request): return True if request.operation.startswith(("Get", "Verify")) else None
-
idempotent=Trueon a route says repeating it is safe (aPOSTsearch, aPUTthat replaces), andidempotent=Falsesays aGETisn't. -
Idempotency keys make retrying a
POSTsafe on APIs that support them (Stripe, Adyen, PayPal, Square).route(..., idempotency_key="Idempotency-Key"), oridempotency_key = "Idempotency-Key"on the client (for every non-idempotent route, sections included), sends that header with a new UUID for each call, the same on every retry of it, and such routes are retried normally.idempotency_key=Falseon a route turns the client's off, and a key you pass inwith_options(headers=...)is used as is.class Stripe(Client): base_url = "https://api.stripe.com/v1" retries = Retries.exponential(attempts=4) idempotency_key = "Idempotency-Key" @route("POST", "/charges", body_format="form") def create_charge(self, body: dict) -> dict: ... # retried safely: one key per call
-
with_options(retries=3)changes the attempts for one call;with_options(retries=Retries(...))replaces the policy.
Rate limits, conditional requests and tracing
Three class settings work on every request a client sends, its retries, pages and stream reconnects included. A section uses its client's unless it sets its own (or None).
from apiroute.caching import ConditionalCache
from apiroute.rate_limiting import RateLimiter
from apiroute.telemetry import OpenTelemetry
class GitHub(Client):
base_url = "https://api.github.com"
rate_limiter = RateLimiter(requests=10, per=1.0, headers=True)
conditional_cache = ConditionalCache()
telemetry = OpenTelemetry()
Rate limiting
RateLimiter waits before a request rather than sending it and getting a 429. This matters most for loops and for paginated routes, which can burst through a quota.
requestsperperseconds is a token bucket holdingburstrequests (default:requests). Up toburstrequests go at once, and the rest are spaced out. A request that finds the bucket empty still takes its turn, so waiting requests go in order.headers=Truefollows the server's own counters. When a response says the quota is spent, every request waits until it resets. It reads the IETFRateLimitfield (r=0;t=30),RateLimit-Remaining/RateLimit-Reset, andX-RateLimit-Remaining/X-RateLimit-Reset, whose reset may be seconds or a Unix time. After a429or503withRetry-After, every request waits that long, not just the retry. Use either option, or both.- One
RateLimiteris one budget, shared by every thread and event loop that uses it. As a class attribute it limits every instance together; give instances their own for separate budgets. Budgets are per process. - Waits go through the same sleep as retries, so
apiroute.testing'srecorded_sleeps()andmock_transport()record them instead of waiting.
Conditional requests
ConditionalCache keeps 200 GET responses that have an ETag or Last-Modified header. The next GET of the same URL sends If-None-Match or If-Modified-Since, and a 304 answer returns the kept body as a 200, converted to the route's model as usual. On GitHub, a 304 doesn't count against the rate limit.
- Responses are kept per URL (query included) and per
AuthorizationandCookieheader, so one caller never gets another's. They're also matched on the request headers the response'sVarynames.Cache-Control: no-store,Vary: *, streams, and requests you made conditional yourself aren't cached. - A revalidated response has the
304's headers over the kept ones (a newDate, fresh rate limit counters), andresponse.extensions["apiroute_cache"] == "revalidated". Hooks see it as a200. - It holds
max_entriesresponses (default 1,024), dropping the least recently used, in memory. It's safe to share between threads and instances, andclear()empties it.
Tracing with OpenTelemetry
OpenTelemetry() (from the otel extra) makes each request attempt a client span.
- The span is named after the request's operation: the route's
operation=, an OpenAPIoperationId, or the method name. - Its attributes follow OpenTelemetry's HTTP conventions:
http.request.method,url.full(asredact_urlshows it, so secrets in the query are masked),server.address,server.portandhttp.response.status_code. - Errors: a
4xxor5xxstatus, or an exception, marks the span as an error witherror.type. Retries are separate spans, and a stream's span ends once its status is in. - Context: spans nest under the caller's current span, and the trace context is sent with each request (
traceparent) unlesspropagate=False. Spans come from the global tracer provider unless you passtracer_provider.
Authentication that refreshes
Static credentials go in headers or query_params. For tokens that expire, set the client's authenticator: before every attempt it supplies the current credential, and when the API answers 401 it fetches a fresh one and sends the request once more. That resend isn't counted as a retry, and a second 401 is raised.
from apiroute.auth import OAuth2ClientCredentials
class Orders(Client):
base_url = "https://api.example.com"
def __init__(self, client_id: str, client_secret: str, **kwargs):
super().__init__(**kwargs)
self.authenticator = OAuth2ClientCredentials(
"https://auth.example.com/oauth/token",
client_id,
client_secret,
scope="orders:read",
extra={"audience": "https://api.example.com"}, # other form fields some servers want
)
OAuth2ClientCredentials(token_url, client_id, client_secret, ...)is the client credentials grant, for server-to-server APIs.OAuth2RefreshToken(token_url, client_id, refresh_token, client_secret=None, access_token=None, on_refresh=None, ...)is the refresh token grant, for acting for a user after an authorization flow you ran. When the server rotates refresh tokens, the new one replaces the old;on_refreshis called with every newAccessToken, so you can store it.access_token=AccessToken(...)starts with a token you already have.- Tokens are kept and shared. A token is reused until
leewayseconds (default 30, or half its lifetime if that's shorter) before it expires. AnAccessTokensays when withexpires_in(seconds, as OAuth replies do) orexpires_at(a Unix time, as many other token APIs and a JWT'sexpdo).authenticator.seed(token)starts with a token you saved from an earlier run. Concurrent calls wait for one fetch: sync calls across threads, async calls per event loop. Each instance has its own token unless the authenticator is set on the class. - Client authentication. The client secret is sent as HTTP Basic (
client_secret_basic, which every server must accept);auth_method="post"sends it as form fields instead. Without a secret, onlyclient_idis sent (a public client). - Token requests use the client's transports, so connection pools,
mock_transport()andMockTransportanswer them too (their operation is"token"). Sections use their client's authenticator.on_requestruns after the credential is applied, so a signature can cover it. - Failures. A token endpoint that refuses (
invalid_client,invalid_grant...) raisesapiroute.auth.AuthError, with.error,.descriptionand.response. It isn't retried, and its message never includes the secret or refresh token. A network error reaching the endpoint is raised as httpx's error, so the call's retries may retry it. - Other schemes. Subclass
OAuth2TokenAuthenticatorand return a different grant's form fields fromgrant(), or subclassTokenAuthenticatorand implementfetch_token(client)(andafetch_tokenfor non-blocking async) for tokens from anywhere else.shared_transports(client)gives the keyword arguments for a helper client that sends through the same transports as the API client, so its requests share connection pools and test mocks. For a credential that isn't a bearer token, subclassAuthenticatoritself and implementcredential,applyandinvalidate. Overriderejects(error)for an API that reports an expired credential some other way, such as with an exception you raise fromcheck_response.
from apiroute import Client, route, shared_transports
from apiroute.auth import AccessToken, TokenAuthenticator
class AcmeAuth(Client):
base_url = "https://auth.acme.com"
refresh = route("POST", "/session/refresh")
class AcmeTokens(TokenAuthenticator): # JSON in, {token, refreshToken, expiresAt} out
def __init__(self, refresh_token: str):
super().__init__()
self.refresh_token = refresh_token
def fetch_token(self, client):
reply = AcmeAuth(**shared_transports(client)).refresh(
body={"refreshToken": self.refresh_token}
)
self.refresh_token = reply["refreshToken"] # rotated on every refresh
return AccessToken(reply["token"], expires_at=reply["expiresAt"])
from apiroute.auth import Authenticator
class Session(Authenticator): # a login session, renewed when the API says it expired
def credential(self, client):
if self.session_id is None:
self.session_id = login(client)
return self.session_id
def apply(self, request, credential):
return dataclasses.replace(request, headers={**request.headers, "X-Session": credential})
def invalidate(self, credential):
if self.session_id == credential:
self.session_id = None
GraphQL
graphql_route declares a GraphQL operation that you write yourself. In GraphQL the caller decides what the response contains, so apiroute leaves the selection set to you and takes care of the rest: the request envelope, variables, errors and unwrapping. GraphQL operations can sit next to REST routes in the same client, sharing its headers, retries, hooks and test helpers.
from dataclasses import dataclass
from apiroute import Client, graphql_route
@dataclass
class Repository:
name: str
issues: dict
class GitHub(Client):
base_url = "https://api.github.com"
@graphql_route(
"""
query Repo($owner: String!, $repoName: String!, $first: Int) {
repository(owner: $owner, name: $repoName) {
name
issues(first: $first) { nodes { title } }
}
}
""",
data="repository",
)
def repo(self, owner: str, repo_name: str, first: int | None = None) -> Repository: ...
viewer = graphql_route("query Viewer { viewer { login } }", data="viewer.login")
@graphql_route(
"mutation Star($id: ID!) { addStar(input: {starrableId: $id}) { clientMutationId } }"
)
def star(self, id: str) -> dict: ...
- The request. A POST to
path(/graphqlby default, under anynamespace()or section) with the JSON body{"query", "operationName", "variables"}. - Variables. Each variable is filled from the argument with the same name, else the argument with its snake_case name (
$repoNamefromrepo_name), else a client attribute.variables={"userID": "user_id"}maps a variable to an argument explicitly. An argument passed asNoneis left out, so the document's default for that variable applies. A required variable with nothing to fill it, or an argument that fills no variable (unless it's aHeaderorResult), raisesRouteDefinitionErrorwhen the class is created. - Routes without a
def. A baregraphql_route(...)gets one keyword-only parameter per variable. Required variables are required parameters; the others default toNone. - The response. The route returns
data, or the value at the dotteddata=path inside it, orNoneif a step along that path is null. The result is converted bymodel=or the return annotation, as with@route. - Errors. A response with
errorsraisesGraphQLError, which carries.errors,.data(anything the server resolved anyway),.codes(each error'sextensions.code, or its top-leveltype, where GitHub putsNOT_FOUND) and.response. Witherrors="partial", a response that has errors but non-nulldatareturns that data and logs the errors. A 400 with a GraphQLerrorsbody raisesGraphQLError; any other status outside 2xx raisesUnexpectedResponse. - Operation names. The operation's name is
RequestSpec.operation, soon_request,on_responseandmock.on(operation="Repo")can tell operations apart even though they all share one URL.operation_name=picks one operation from a document that has several, or names an anonymous operation. Without it, an anonymous operation is named after its method. - Retries. Queries are idempotent, though they're sent as POST, so they're retried like a
GET. A mutation is not retried after an error that may have happened once the server had the request: read and write timeouts or errors, and protocol errors. Errors before anything was sent, such as connection failures and pool timeouts, are still offered toshould_retry. Passidempotent=Truefor a mutation that is safe to repeat. - Checking documents. apiroute reads each document's operation type, name and variables itself. With
pip install apiroute[graphql], it also parses the document with graphql-core when the class is created, so a syntax error raisesRouteDefinitionErrorat import time instead of failing on the server. To check documents against the API's schema as well, see below.
Pagination
Most GraphQL lists are Relay connections, read a page at a time. paginate= turns a route into an iterator over every item, following pageInfo.endCursor for you:
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class Issue:
number: int
title: str
class GitHub(Client):
base_url = "https://api.github.com"
@graphql_route(
"""
query Issues($owner: String!, $name: String!, $after: String) {
repository(owner: $owner, name: $name) {
issues(first: 100, after: $after, states: OPEN) {
pageInfo { hasNextPage endCursor }
nodes { number title }
}
}
}
""",
paginate="repository.issues",
)
def open_issues(self, owner: str, name: str) -> Iterator[Issue]: ...
for issue in gh.open_issues("python", "cpython"): # 100 per request, as many requests as it takes
print(issue.number, issue.title)
first_ten = list(itertools.islice(gh.open_issues("python", "cpython"), 10)) # one request
async for issue in gh.aio.open_issues("python", "cpython"):
...
- How it pages. The method returns an iterator, so nothing is sent until you iterate, and each page is requested only when iteration reaches it. Each request passes the previous page's
endCursoras$after, untilhasNextPageis false. Usecursor=for a variable with another name. Passingafter=starts from that cursor. - What it yields. The connection's
nodes, or eachedges[].node, at the dottedpaginatepath (aliases count). Items are converted bymodel=, or byXin anIterator[X]return annotation; otherwise they're dicts. A null connection (a repository that doesn't exist) yields nothing. - What the operation needs. A
$aftervariable, which is checked when the class is created, andpageInfo { hasNextPage endCursor }plusnodesoredges { node }on the connection, which is checked as pages arrive. A server that answershasNextPagewith no cursor, or with the same cursor again, raisesValueErrorinstead of looping forever. - Every page is an ordinary request, with your headers, hooks and retries. A
GraphQLErroron a later page raises from the iteration, after the earlier items.
Persisted queries
persisted=True sends automatic persisted queries: a SHA-256 hash of the document instead of the document itself, which saves bandwidth on large operations. It works with servers that support the protocol, such as Apollo Server, GraphQL Yoga (with its plugin) and Hasura.
viewer = graphql_route("query Viewer { viewer { login } }", persisted=True)
- A cached query is one request, carrying
extensions.persistedQuery(the hash) and noquery. - On a miss (
PersistedQueryNotFound), the route sends the document once more along with the hash, which registers it, and returns that result. Later calls are hash-only again. You see one call and one result;on_requesthooks and mocks see both requests. - A server without APQ gets the full document, and that client sends full documents for that route from then on. Other client instances aren't affected. That covers a server answering
PersistedQueryNotSupported, and one that doesn't know the protocol at all and answers with a request error, as GitHub does ("A query attribute must be specified"). - Other GraphQL errors raise as usual, without another request. Works with
.aioandpaginate=, where every page is sent by hash. - Logging: protocol replies (a miss, or not supported) are logged at DEBUG, not as WARNING failures.
File uploads
Put a file in a variable and the call is sent as a GraphQL multipart request, the format GraphQL Yoga, Apollo Server (with graphql-upload), Hasura and most GraphQL servers accept:
from apiroute.graphql import Upload
set_avatar = graphql_route(
"mutation SetAvatar($userId: ID!, $file: Upload!) { setAvatar(userId: $userId, file: $file) { url } }"
)
client.set_avatar(user_id="u1", file=Upload("avatar.png")) # a path
client.set_avatar(user_id="u1", file=Upload(png_bytes, "me.png")) # bytes, with a filename
with open("avatar.png", "rb") as f:
client.set_avatar(user_id="u1", file=f) # an open binary file
Upload(source, filename=None, content_type=None)takes bytes, a path, or a binary file object. The filename defaults to the path's or file's name, and the content type is guessed from the filename (elseapplication/octet-stream).- Files can be anywhere in the variables: lists of files, and files inside input objects. The request has
operations(the usual JSON, with each file's place asnull),map, and one part per file. Calls without files are plain JSON, as before. - Files are read when the request is built, so a retry, or a persisted-query registration, resends the same bytes. Large files are held in memory.
- Apollo Server rejects multipart requests without a CSRF header. Add
headers = {"Apollo-Require-Preflight": "true"}to the client or route.
Schema validation
Set graphql_schema and every GraphQL route is validated against the API's schema when the class is created. A misspelled field, a wrong argument, or a variable of the wrong type fails at import time instead of in production:
class GitHub(Client):
base_url = "https://api.github.com"
graphql_schema = "schema.graphql" # next to this module; a .json introspection result works too
viewer = graphql_route("query Viewer { viewer { logn } }")
RouteDefinitionError: GitHub.viewer: the document doesn't match graphql_schema:
- Cannot query field 'logn' on type 'User'. Did you mean 'login'? (line 1, column 25)
- The schema. A path to an SDL file (
.graphql,.graphqls,.gql), a path to a.jsonintrospection result (with or without its{"data": ...}envelope), or agraphql.GraphQLSchema. A relative path is resolved against the directory of the module that declaresgraphql_schema, so a packaged client can ship its schema next to its code. GitHub publishes its schema asschema.docs.graphql. - What's checked. Everything graphql-core validates: fields, arguments, variable types and usage, fragments, and the operation's root type. All of a document's problems are reported in one
RouteDefinitionError. - When. When the class is created, or on a route's first use with
compile_routes = "lazy". Each schema file is loaded once per process, so a large schema such as GitHub's costs its build time once, on the first class that uses it. - Inheritance. Subclasses inherit
graphql_schema. A section without its own uses the schema of the class it's nested in, andgraphql_schema = Noneturns validation off for a class or section. Inherited routes stay validated against the schema of the class that defined them. - Skipping one route.
graphql_route(..., validate=False)skips the schema check for a route that uses fields your schema file doesn't have yet, such as preview features. Its syntax is still checked. - Without graphql-core. Setting
graphql_schemawithoutpip install apiroute[graphql]raisesRouteDefinitionError, rather than silently skipping the checks you asked for.
In tests, graphql_response(data=..., errors=...) from apiroute.testing builds the response, and MockCall.graphql_variables returns the variables that were sent:
from apiroute.testing import graphql_response, mock_transport
with mock_transport() as mock:
mock.on(operation="Viewer").respond(graphql_response(data={"viewer": {"login": "octocat"}}))
assert GitHub().viewer() == "octocat"
assert mock.last.graphql_variables == {}
Webhooks
apiroute.webhooks covers the requests an API sends you. Check the signature against the raw body before trusting it, then parse the payload:
from apiroute.webhooks import StripeSignature, WebhookSignatureError
stripe_signature = StripeSignature(os.environ["STRIPE_WEBHOOK_SECRET"])
@app.post("/stripe")
async def stripe_webhook(request):
body = await request.body() # the raw bytes: re-encoded JSON won't match the signature
try:
stripe_signature.verify(request.headers, body)
except WebhookSignatureError:
return Response(status_code=400)
event = webhooks.invoice_paid(body) # a generated parser; see below
| Class | Signs | Notes |
|---|---|---|
HmacSignature(secret) |
an HMAC of the body in one header | GitHub by default (X-Hub-Signature-256: sha256=<hex>); header=, prefix=, digest= and encoding="base64" fit Shopify, Slack-style and other schemes. No timestamp, so it can't detect replays |
StripeSignature(secret, tolerance=300) |
Stripe-Signature: t=...,v1=... over "<t>.<body>" |
refuses timestamps more than tolerance seconds away |
StandardWebhooksSignature(secret, tolerance=300) |
webhook-id, webhook-timestamp, webhook-signature (or svix-*) |
the Standard Webhooks spec: Svix, Resend, Clerk, OpenAI and others; secret is whsec_<base64> |
verify(headers, body)raisesWebhookSignatureError(anApiRouteError) when the signature is missing, malformed, wrong or too old.headersis any mapping (header names aren't case-sensitive), andbodyis the raw bytes or text.- Rotating secrets: give a list, and a signature from any of them is accepted. Comparisons take constant time.
parse_payload(body, model=None)parses the JSON body, and converts it tomodelwhen given (a pydantic model, a dataclass, or a type holding them, such aslist[Event]).
Errors
| Exception | Raised when | Carries |
|---|---|---|
RouteDefinitionError |
a route is wrong (an unused parameter, a bad template value or option); raised when the class is created | the class, route and reason in its message |
UnexpectedResponse |
the status isn't expected (any 2xx when expected is unset), or a JSON route's body isn't JSON |
.response, .status_code, .request, .route_name |
ResponseValidationError |
the JSON doesn't fit the route's model | .response, .error, .route_name |
GraphQLError |
a GraphQL response has errors |
.errors, .data, .codes, .response, .operation |
httpx.TransportError subclasses |
the network fails, after retries run out | httpx's details |
WebhookSignatureError (apiroute.webhooks) |
a webhook's signature is missing, wrong or too old | the reason in its message |
OperationFailed, PollTimeout (apiroute.polling) |
a poll= route's operation failed, or didn't finish in time |
.status, .body, .response; .timeout, .url |
AuthError (apiroute.auth) |
a token endpoint refused to issue a token, or answered with something that isn't one | .error, .description, .response |
ValueError |
a class setting is invalid (a base_url scheme, body_format, inherit), or a streamed file path is unsafe |
the reason in its message |
The first four, WebhookSignatureError, OperationFailed, PollTimeout and AuthError derive from ApiRouteError. client.last_response holds the most recent response for debugging; it is per client, so don't rely on it when one client is shared between threads.
Class settings
| Attribute | Default |
|---|---|
base_url |
none; http or https only. A query string in it (a provider key such as ?api-key=...) is kept and sent first |
headers, query_params |
{}. Values may be callables taking the client. Both merge down subclasses, and None removes a key |
timeout |
30 seconds |
retries |
Retries() (one attempt) |
body_format |
"json", "form" or callable(client, data) |
query_format |
"flat", "nested" (a[b]=1) or callable(client, data) returning pairs |
authenticator |
None. An apiroute.auth authenticator that applies a changing credential to every request and refreshes it after a 401; see Authentication that refreshes. Usually set in __init__ |
rate_limiter, conditional_cache, telemetry |
None. A RateLimiter, ConditionalCache or OpenTelemetry; see Rate limits, conditional requests and tracing. A section uses its client's unless it sets its own |
follow_redirects |
None: the transport's httpx setting (httpx doesn't follow). True follows 3xx answers for this API whatever the transport; a section uses its parent's unless it sets one |
Methods to override
| Method | Runs | Default |
|---|---|---|
on_request(self, request) |
before every attempt, sync or async; may return a changed RequestSpec |
sends the request as is |
on_response(self, request, response, elapsed) |
after every response, whatever its status; for streams, before the body is read | nothing |
check_response(self, request, response) |
after on_response, inside the retry loop and before the status check; raise to reject the response |
accepts it |
should_retry(self, error, attempt) |
when an attempt fails | retries httpx timeouts, network and protocol errors |
idempotent(self, request) |
once per call, before its first attempt: True or False decides whether errors after the request may have reached the server are retried |
None: the route's own (GET, HEAD, OPTIONS, or its idempotent=) |
escape_path(self, value) |
for every path value | percent-encodes everything but A-Z a-z 0-9 - . _ ~ |
encode_value(self, value) |
for each value JSON can't hold, in JSON bodies and GraphQL variables, and for query, form and multipart values; returns something JSON can hold, which is converted again if it needs to be | converts UUIDs, dates, times and datetimes (ISO 8601), timedeltas (ISO 8601 durations), Decimals and Fractions (text), IP addresses and networks, paths, time zones, enums (their value), sets, other mappings, dataclasses, pydantic models and numpy values; raises TypeError for anything else |
redact_url(self, url) |
for the URL in an UnexpectedResponse message, and so in retry log lines |
masks secret-looking query values and a userinfo password |
soap_header(self, operation) |
when building a SOAP envelope; returns a dict for its Header | no Header |
To send a type the default doesn't know, such as a database driver's range type, handle it and pass everything else on:
class Bookings(Client):
def encode_value(self, value):
if isinstance(value, psycopg.types.range.Range):
return {"lower": value.lower, "upper": value.upper}
return super().encode_value(value)
request.operation names the call: the route's operation= (generated clients set it to the spec's operationId or WSDL operation name), else the method name. It's useful for logging, metrics and APIs that want the call name in the request.
class SignedApi(Client):
def on_request(self, request):
signature = hmac.new(self.secret, request.url.encode(), "sha256").hexdigest()
return dataclasses.replace(request, headers={**request.headers, "X-Signature": signature})
def on_response(self, request, response, elapsed):
metrics.timing("api.request", elapsed, tags=[f"status:{response.status_code}"])
Network errors don't reach on_response; every failed attempt is logged on the apiroute logger, with the route, the attempt number and the error.
check_response is for APIs that report a failure inside a successful response, such as a 200 whose body says the call was rate limited (for one route, @route(..., check=...) does the same). Whatever it raises goes through should_retry like any other failure:
class RateLimited(Exception): ...
class TokenApi(Client):
retries = Retries.exponential(attempts=5, initial=1, max=30)
def check_response(self, request, response):
if response.json().get("code") == 4029: # "too many requests", sent with status 200
raise RateLimited(request.operation)
def should_retry(self, error, attempt):
return isinstance(error, RateLimited) or super().should_retry(error, attempt)
Transports: how requests are sent
An API class only describes the API. How its requests reach the network is a transport, chosen for the environment at startup rather than baked into the class. The same GitHubApi can open a fresh connection per request in a web server and keep a pool per thread in a background worker.
| Transport | Connections | Suits |
|---|---|---|
OneShotTransport (default) |
a new one per request, closed once the response is read | web servers, forking process managers, low request volume |
PooledTransport |
one httpx.Client (one pool) shared by all threads |
many threads or short-lived threads, HTTP/2 |
ThreadLocalTransport |
one httpx.Client per thread, closed when the thread ends |
a fixed set of worker threads |
HttpxClientTransport |
an httpx.Client you own |
custom setups; for tests, see Testing |
Each takes httpx.Client keyword arguments, such as limits, http2=True, proxy and verify. The SSL context is built once per transport, so a one-shot request costs a new connection but not a reload of the CA bundle. Pooled and thread-local transports open new clients in a forked child.
import httpx
from apiroute import (
HttpxClientTransport,
PooledTransport,
ThreadLocalTransport,
close_transports,
use_transport,
)
# worker.py: each worker thread keeps its own connections
use_transport(ThreadLocalTransport())
# or one shared pool for one API, with HTTP/2
use_transport(PooledTransport(http2=True, limits=httpx.Limits(max_connections=20)), GitHubApi)
# one instance, e.g. in a test
gh = GitHubApi("token", "acme", transport=HttpxClientTransport(httpx.Client(transport=mock)))
close_transports() # at shutdown
A client uses its own transport= argument if it was given one. Otherwise it uses the transport registered for its class or the nearest base class, and otherwise the process default. Sections use their root client's transport. A custom transport is any object with send(spec) -> httpx.Response, stream(spec) (a context manager yielding an unread httpx.Response, needed only for streaming routes) and close().
Async
The same client class works with await: client.aio is a view whose route calls return coroutines.
user = gh.get_user("octocat") # sync
user = await gh.aio.get_user("octocat") # async, same class and routes
issues = await gh.aio.issues.list("acme", "api") # sections too
await gh.aio.with_options(timeout=5).get_user("a") # with_options, in either order
Async calls have transports of their own, registered beside the sync ones. use_transport sends an async transport (one whose send is a coroutine) to the async side, so configuring one side never changes the other.
| Transport | Connections |
|---|---|
AsyncOneShotTransport (default) |
a new one per request |
AsyncPooledTransport |
one httpx.AsyncClient per event loop (an AsyncClient can't be shared across loops) |
AsyncHttpxClientTransport |
an httpx.AsyncClient you own |
use_transport(AsyncPooledTransport(http2=True)) # async default for every client
gh = GitHubApi("token", "acme", async_transport=AsyncHttpxClientTransport(async_client))
await aclose_transports() # at shutdown, inside the event loop
Retries sleep with asyncio.sleep. should_retry, escape_path, on_request, on_response and callable headers stay plain sync methods, shared by both sides.
Type checking
apiroute ships type information (py.typed), and routes keep their signatures for mypy, pyright and editors such as VS Code's Pylance:
class GitHubApi(Client):
@route("/users/{username}")
def get_user(self, username: str, *, fields: str | None = None) -> dict[str, Any]: ...
gh.get_user("octocat") # dict[str, Any]
gh.get_user(42) # error: "int" isn't "str"
gh.get_user("octocat", page=2) # error: no parameter "page"
- Decorated routes (
@routeand@graphql_routeon adef) are typed as their method withoutself. Apaginate=route annotatedIterator[Issue]yieldsIssues, REST or GraphQL. - Generated clients are typed end to end:
client.pets.models.get_pet(1)is aPetwith typed fields, and the dict routes have their own signatures. Their section and.modelsattributes are annotated, with the classes imported for type checkers only, so loading stays lazy. Generated packages pass mypy and pyright. - Routes without a
def(get_user = route(...)) get their signature when the class is created, so type checkers see a callable taking anything and returningAny. - Nested sections (
class issues(Section)inside a client) are typed as instances by pyright and Pylance. mypy can't follow that, so to mypy their routes areAny, never an error. For full mypy types, put the section in its own module and reach it withissues: IssuesSection = lazy(".issues", "IssuesSection"), as generated clients do. - Defaults:
FROM_CLIENTandFROM_RESPONSEare valid for any parameter type. - Route bodies: they're never run, so end them with
...(after a docstring too). mypy still reportsempty-bodyfor those. Turn it off for client modules with a# mypy: disable-error-code="empty-body"line, as generated files do. .aioandwith_options()views areAny, because their methods return coroutines or depend on the options.
Testing
apiroute.testing fakes the network at the transport. Your clients, routes, hooks and retries all run for real, but requests are answered by the test. Inside mock_transport(), every client sends its requests, sync and async, to one MockTransport, including a class that has its own use_transport registration. The previous registrations come back when the block ends.
import httpx
from apiroute.testing import mock_transport
def test_user_name():
with mock_transport() as mock:
mock.on(operation="getUser").respond(httpx.Response(200, json={"login": "octocat"}))
mock.respond(httpx.ConnectError("down"), httpx.Response(201, json={})) # queued, in order
assert app.user_name("octocat") == "octocat" # code that builds its own GitHubApi
app.star("octocat") # fails once, then the retry gets the 201
assert mock.calls[0].operation == "getUser"
assert mock.calls[0].params["fields"] == "login"
assert mock.last.json() == {"user": "octocat"}
assert mock.sleeps == [0.5] # retries record their waits instead of sleeping
- Answering requests. A request gets the first matching route from
mock.on(operation=, method=, path=, where=), else the next response queued withmock.respond(...), else thehandlerpassed tomock_transport(handler). Anything else raisesUnmatchedRequest, which names the operation and URL. A route's responses are used in order and its last one repeats. - What a response can be. An
httpx.Response, an exception to raise (anhttpxerror gets the request attached), or a function taking thehttpx.Request, such as anhttpx.MockTransporthandler. - Recorded calls. Each
MockCallinmock.calls(and inroute.calls) has theRequestSpecthat apiroute built and thehttpx.Requestencoded from it, as it would have gone on the wire. It also offersoperation,method,url,path,params,headers,contentandjson().operationis the spec'soperationIdfor generated clients, so tests can match on the call name instead of the URL. - Unused responses. If the block ends normally with queued responses unused, it fails. Pass
assert_all_used=Falseto allow it. - Clients with their own transport. A client given
transport=keeps it. To mock a single instance, passtransport=mock, async_transport=mock.aioto aMockTransport()you build yourself. - Retries without the mock.
recorded_sleeps()makes retries record their waits instead of sleeping, for tests that use respx or their ownhttpx.MockTransport. - Blocking the real network.
block_network()fails any request that reaches httpx's real network transports, whatever the client's transport is. Mocks are unaffected.
apiroute registers a pytest plugin with two opt-in fixtures. apiroute_mock is a mock_transport() that lasts for the test. apiroute_block_network guards the test, or the whole suite when used from an autouse fixture:
# conftest.py
import pytest
@pytest.fixture(autouse=True)
def _no_network(apiroute_block_network):
pass
Recording and replaying real responses
cassette(path) records what the real API answers the first time a test runs, and replays it on later runs, without the network:
from apiroute.testing import cassette
def test_repository_stats():
with cassette("tests/cassettes/repository_stats.json"):
assert stats.for_repository("dougyouch/apiroute").stars > 0
- Modes.
mode="once"(the default) replays the file when it exists and records it when it doesn't."record"always sends real requests and replaces the file;"replay"requires the file. A recording is saved only when the block ends without an error. - Matching. A request is matched to a recording by method and URL, and by body with
match_body=True(JSON compared as data). Each recording plays once, in order. A request with no unplayed match raisesCassetteMismatch, andassert_all_played=Truefails a block that leaves recordings unplayed. - Secrets stay out of the file.
Authorization,Cookieand any request header whose name looks secret (token,key,secret,session...) are saved as"[REDACTED]", as areSet-Cookieand the query valuesredact_urlmasks; live requests are matched in the same masked form. For secrets elsewhere, such as in a body,redact=is called with each interaction's JSON and returns a scrubbed copy. - The file is readable JSON, with bodies saved as JSON, text, or base64 for binary content. A streamed response is read in full while recording, and replays like any other. Retries during replay don't wait.
Checking mocks against the spec
A mock written by hand, or recorded a year ago, can drift from the API. ResponseSchemas(GeneratedClient) reads the response type of every operation from a generated client's .models layer. Given as check= to MockTransport, mock_transport() or cassette(), it validates every 2xx JSON response against its operation's model, and raises MockResponseMismatch (an AssertionError) with pydantic's explanation when it doesn't fit:
from apiroute.testing import ResponseSchemas, mock_transport
PETS = ResponseSchemas(PetsApi)
def test_adopt():
with mock_transport(check=PETS) as mock:
mock.on(operation="getPet").respond(httpx.Response(200, json={"id": 1}))
adopt(1) # MockResponseMismatch: getPet: GET .../pets/1: ... name: Field required
Operations the client doesn't declare, and responses that aren't 2xx JSON, pass unchecked. It needs pydantic, and imports every section of the client the first time it's used.
Code generation
apiroute generate writes a client package from an OpenAPI 3.0/3.1 or Swagger 2.0 spec, from a WSDL 1.1 document (document/literal, SOAP 1.1 and 1.2), or from a GraphQL schema plus your own operation files (see GraphQL clients). Specs can be file paths or URLs, in JSON or YAML.
apiroute generate openapi github.yaml -o gh --client-name GitHubApi # dict routes only
apiroute generate openapi github.yaml -o gh --client-name GitHubApi --models # plus pydantic models
apiroute generate wsdl "https://example.com/weather?wsdl" -o weather --models
The package has two layers:
from gh import GitHubApi
class MyGitHub(GitHubApi): # yours, outside gh/: regenerating never touches it
headers = {"Authorization": lambda self: f"Bearer {self.token}"}
def __init__(self, token: str, **kwargs):
super().__init__(**kwargs)
self.token = token
gh = MyGitHub("ghp_...")
gh.meta.get() # each tag is a section; dicts in and out
gh.repos.get("octocat", "hello-world")
gh.repos.models.get("octocat", "hello-world") # -> FullRepository (with --models)
await gh.repos.models.aio.get("octocat", "hello-world")
gh/
client.py GitHubApi: untagged routes; each tag a lazily imported section
models/ with --models
client.py gh.models: typed versions of the root routes
models.py a lazy index of the models
schemas/*.py one module per model (models that refer to each other share one)
repos/
client.py gh.repos: the tag's dict routes
models/
client.py, models.py, schemas/*.py
Nothing is imported until it's used. On GitHub's spec (1,242 operations, 4,035 models), constructing the client takes 0.6 ms, a dict call about 3 ms all in, and the first typed call costs pydantic's own import plus a few milliseconds for the models it returns.
-
Your code goes outside the package. Subclass the client to add behaviour, such as auth a spec doesn't declare (above); headers merge down subclasses. Regenerating removes only files the generator wrote, and refuses to write into a directory it didn't create.
-
Auth can live in a hand-written base class.
--base-class mypackage.auth:MyAuthmakes the generated root client extendMyAuth(aClientsubclass) instead ofClient, and leaves out the spec's security schemes. The base class owns credentials, throughheaders,query_params,on_requestor, for SOAP,soap_header, and regenerating never touches it:class TradingAuth(Client): # eBay Trading: credentials in the SOAP header, call name in the query def __init__(self, token: str, **kwargs): super().__init__(**kwargs) self.token = token def soap_header(self, operation): return {"RequesterCredentials": {"eBayAuthToken": self.token}} def on_request(self, request): return dataclasses.replace( request, params=[*request.params, ("callname", request.operation)] )
-
A relative server URL needs a host. A spec read from a URL resolves a relative
serversentry (/api/v2) against the spec's own address. Read from a file, it can't, so pass the host:--base-url https://api.example.com/api/v2. The option also overrides the spec's servers. -
Specs that say "never null" when the API sends null. Models follow the spec, so a field the spec declares non-nullable fails validation when the response has
nullthere; GitHub's REST description, for one, declares a label'sdescriptiona string, but labels without one come backnull.--nullable-fieldstypes every model field as acceptingNone(description: str | None). Required fields stay required: they must be present, but may be null. The dict layer is unaffected. -
APIs that send enum values the spec doesn't list. An enum becomes a
Literal, so a value missing from the spec fails validation; weather.gov, for one, lists the 16 compass points for a forecast'swindDirectionbut sends""when the wind is calm.--open-enumstypes every enum of two or more values in the models as also taking any other value of its type (Literal['N', 'NNE', ...] | str). A single-valueLiteralstays closed, since it tells the members of a union apart (GeoJSON'stype: "Feature"). The dict layer and the methods' parameters are unaffected. -
Tagged unions. A
oneOforanyOfwith adiscriminatoris a plain union by default, which pydantic tries member by member: errors list every member's complaints.--discriminatorsmakes it a tagged union,Annotated[Cat | Dog, Field(discriminator="pet_type")], which pydantic picks the member of by the discriminator's value. That's faster, and an error names that member's problem, or the tags it expected. Each member's discriminator property becomes required, typed as theLiteralof the values naming it: itsmappingentries, else its schema's name, as the OpenAPI spec says.--nullable-fieldsand--open-enumsleave it closed. A union whose members aren't all models with that property stays plain. Since this is stricter, check that the API sends the values the spec names before turning it on. -
Naming operations yourself. Sections come from tags and methods from
operationIds. For a spec where those make poor names (Stripe's has no tags, and IDs likePostCustomersCustomer),--operation-names names.jsonmaps operation IDs to dotted names:{"PostCustomers": "customers.create", "GetIssuingCards": "issuing.cards.list"}. An operation without anoperationIdis keyed by its method and path as the spec writes them:{"GET /api/data/metar": "metars.list"}. The last part is the method, and the parts before it are sections, nested as deep as you like (api.issuing.cards.list()) and loaded lazily level by level. Operations the map doesn't name stay where the spec put them; a name that matches no operation is a warning, and two methods with one name, or a method named like a section, are errors. -
Paginated
_allmethods.--pagination rules.yamlpicks the operations that page and says how. Each one keeps its one-page method and gains<name>_all, with the same arguments, iterating every page's items: dicts, or.modelsyielding the item model (stripe.customers.models.list_all(limit=100)yieldsCustomers). Rules are tried in order and the first match wins; a rule selects by any ofoperations(operation IDs or glob patterns),method(defaultGET),has_parameterandresponse(array, or{has: [...]}naming properties), and givespaginatewith a strategytype(cursor,item_cursor,next_url,page,offset) and its arguments, as in Pagination (pageisPageNumber):- name: Stripe lists has_parameter: [starting_after] response: {has: [data, has_more]} paginate: {type: item_cursor} - name: GitHub lists response: array has_parameter: [page] paginate: {type: next_url} # the Link header
The generator prints how many operations each rule matched and warns about one that matched none; an unknown type or argument, an
itemspath that isn't an array in an operation's response, or an_allname that's already taken stops it. Without a matching rule, an operation'sx-speakeasy-paginationextension is used (offsetLimit,cursorandurl, with$.dotted.paths); one apiroute can't map is a warning. -
Query and form styles follow the spec. A section with
style: deepObjectquery parameters sends them with bracketed names (created[gt]=1&expand[]=customer); others repeat the name for a list (tag=a&tag=b). Form bodies always use brackets (metadata[key]=v,items[][price]=p). A request body that can hold nothing (an object schema with no properties andadditionalProperties: false, as on most of Stripe's reads) gets nobodyargument. -
Webhooks. An OpenAPI 3.1 spec's
webhooksbecomewebhooks.py, with a function per webhook that parses a request body (webhooks.new_pet(body)), andWEBHOOKS, which maps the spec's names to them. With--models,models/webhooks.pyreturns the payload models instead. Check signatures first withapiroute.webhooks. -
Comparing spec versions.
apiroute diff old.yaml new.yamlreads two versions of an OpenAPI or Swagger spec the way the generator does, and lists what changes in the generated client. Breaking changes include removed or renamed methods (a newoperationIdor tag), new required parameters or body fields, removed fields, fields a response may now leave out, and changed types. Additions include new operations, optional parameters, fields, models, webhooks and enum values. It ends with the conventional commit type for regenerating:feat!,featornone.--format jsonis for scripts, such as a client repository's Build workflow choosing its commit message.--fail-on-breakingexits with status 2 when anything breaks, and--operation-namesand--discriminatorsshould match how the client is generated. Descriptions and other changes that leave the generated code alone aren't reported. -
Output passes
ruff checkandruff format. When ruff is installed, the generator runs it over the output;--no-formatskips that. -
OpenAPI: tags become sections,
operationIds become method names, and path, query and header parameters become arguments. Bodies can be JSON, form or multipart; responses can be JSON, text or binary. Schemas become models, withallOfmerged,oneOf/anyOfas unions and enums asLiteral. Bearer, basic and API key auth become constructor arguments. -
WSDL: each operation becomes a POST route with its
SOAPAction. Bodies are dicts in the xmltodict shape: child elements as keys,"@attr"for attributes,"#text"for text content, and"{namespace}local"for an element from another namespace. Faults raiseapiroute.soap.SoapFault. XML is parsed withdefusedxml.
GraphQL clients
A GraphQL API decides nothing about response shapes: the caller does. So instead of generating every field, apiroute generate graphql takes the schema and the .graphql operations you write, checks them against the schema, and generates one typed method per operation:
apiroute fetch-schema https://api.github.com/graphql -o specs/github.graphql \
-H "Authorization: Bearer $GITHUB_TOKEN"
apiroute generate graphql specs/github.graphql --operations operations/github \
--endpoint https://api.github.com/graphql --models -o gh \
--scalar DateTime=datetime:datetime
operations/github/
fragments.graphql fragments are shared by every file
viewer.graphql query Viewer { ... } -> gh.viewer()
repos/
repository.graphql query Repository(...) { ... } -> gh.repos.repository(...)
star.graphql mutation Star(...) { ... } -> gh.repos.star(...)
# A repository and its owner.
query Repository($owner: String!, $repoName: String!) {
repository(owner: $owner, name: $repoName) {
name
stargazerCount
owner { login ... on User { name } }
}
}
gh.repos.repository(owner="octocat", repo_name="hello-world") # -> {"repository": {...}}
result = gh.repos.models.repository(owner="octocat", repo_name="hello-world")
result.repository.stargazer_count # RepositoryResult -> RepositoryRepository -> int
-
Nothing is written until everything checks out. Every operation is validated against the schema first. All problems, in all files, are reported as
file:line:column, and the output directory is left alone. A deprecated field or an unused fragment is a warning. -
Files become methods, folders become sections. Each named operation is one method, named in snake_case; files directly in
--operationsgo on the root client, and each subfolder becomes a section. Variables are keyword arguments ($repoNamebecomesrepo_name); optional ones default toNoneand aren't sent, so the operation's own defaults apply. -
Methods return the whole
data.gh.repos.repository(...)returns{"repository": ...}, not the repository, so adding a second field to an operation never changes a method's return type. -
Models follow your selections. With
--models, each operation gets<Operation>Resultand one model per selected object, named by its path (RepositoryRepositoryOwner). Aliases name fields, nullable fields are| None, fields under@include/@skipdefault toNone, and fragments are merged into the models that use them. A selection on an interface or union with type conditions (... on User) becomes a union of one model per named type plus an...Otherfallback, told apart by__typename, which the generator adds to the query where it's missing. -
Inputs, enums and scalars. Input objects and enums your operations use become models and
Literalaliases.Int,Float,String,IDandBooleanmap to Python types; custom scalars areAnyunless--scalar Name=module:typemaps them. -
File uploads. An
Upload(orFile) scalar is a custom scalar, so it'sAnyin generated methods and input models. PassUpload(...)or an open file there, in dict or typed calls, and the call is sent as a multipart request. -
Persisted queries.
--persisted-queriesgenerates every route withpersisted=True, sending the hash of the document shown in the generated file. -
Pagination with
@paginate. Put it on a connection field and the generated method pages through it, as withpaginate=. The directive is apiroute's own: it's removed before the query is validated or sent. The method returnsIterator[dict[str, Any]], orIterator[<item model>]from.models, and the generator checks for$after,pageInfo { hasNextPage endCursor }andnodesoredges { node }:query Issues($owner: String!, $name: String!, $after: String) { repository(owner: $owner, name: $name) { issues(first: 100, after: $after) @paginate { pageInfo { hasNextPage endCursor } nodes { number title } } } }
-
--endpointsets the root client'sbase_urland the routes' path. Without it, routes post to/graphqland you passbase_url=when you construct the client.--client-name,--base-class,--modelsand--no-formatwork as for the other formats. -
The schema can be an SDL file, a
.jsonintrospection result, or an endpoint URL to introspect (with-Hfor auth). For a repository that regenerates on a schedule, save it withfetch-schemaand generate from the file: SDL diffs cleanly, and builds stay reproducible. Header values are used as given, so take tokens from the environment. -
Generated clients don't validate at run time, so they don't need graphql-core; the generator already did. Generating needs
pip install apiroute[codegen].
Security
- Base URLs must be
httporhttpsand have a host. This is checked when the class is created and when abase_urlis passed to a client, which keeps a misconfiguration from reachingfile:and similar schemes. - Path values are percent-encoded so each stays one path segment:
get_file(name="a/b c")requests/files/a%2Fb%20c, so a value can never add..or a segment. Overrideescape_pathto allow/. - URLs are joined, not resolved: the request URL is
base_urlplus the path, so a route can't replace the host. - Secrets stay out of messages: an
UnexpectedResponseshows its URL throughredact_url, which masks the values of query parameters whose names contain a secret word (api_key,apikey,accessToken,client_secret,sig, ...) and a password in the userinfo. The retry log lines print that message. Overrideredact_urlfor a key elsewhere, such as in the path;.requestkeeps the real URL. - TLS is verified by default (httpx). Turning it off takes an explicit
verify=Falseon a transport. - Streamed files are only opened once the status has passed, and paths with a null byte or a
..segment are rejected.
Thread safety
- Route definitions are compiled once, when the class is created, and never change afterwards.
PooledTransportis safe to share between threads, andThreadLocalTransportgives each thread its own connections.OneShotTransportshares nothing.- A client instance holds no connections, so one instance can be shared between threads. The exception is
last_response, which is per instance and changes with every request. namespaceblocks are tracked per thread.
Development
uv sync
uv run pytest
uv run ruff check .
Metadata
Release files for apiroute 2.10.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| apiroute-2.10.0.tar.gz | 511.5 kB | Without provenance | Details for apiroute-2.10.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| apiroute-2.10.0-py3-none-any.whl | Python 3 | none | any | Details for apiroute-2.10.0-py3-none-any.whl |
Total release size: 806.4 kB
Release files / apiroute-2.10.0.tar.gz
| Download URL | apiroute-2.10.0.tar.gz |
|---|---|
| Size | 511.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5ca648e6c546be5ff79ced8463906819d70da4e237c49f2b30da88bcd0c113b2
|
|
BLAKE2b-256 checksum How to use checksums |
14dab3c923e6e0169d616d196cc8e282cc613f8f8e67175baf8dee8274cece9d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / apiroute-2.10.0-py3-none-any.whl
| Download URL | apiroute-2.10.0-py3-none-any.whl |
|---|---|
| Size | 294.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ae6a76db5ee9944093fba823a1ad9a5a68fa4a70cfcb1510c6df52939f5d5608
|
|
BLAKE2b-256 checksum How to use checksums |
b8f2ee9a30b55ed3ac60f6f5d6027821be0aafcc43d5c40679f58e4a38fc4dea
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for apiroute 2.10.0
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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
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.