Skip to main content

aio-apiclient

Tests Status PyPI Version Python Versions

Most HTTP APIs are a URL, a method and a JSON body. This library lets you spell that as an attribute chain:

repo = await client.api.repos.klen["aio-apiclient"].get()

GET https://api.github.com/repos/klen/aio-apiclient is built from the chain, the body comes back already parsed, and the same client keeps your auth headers, params and middlewares for every call. It runs on either httpx or aiohttp, and the client is generic over the response type you ask for.

Install

pip install aio-apiclient[httpx]      # or aio-apiclient[aiohttp]
uv add aio-apiclient[httpx]

Python 3.11 or newer. One of the two backends is required; installing both is fine, and the client picks the first one available unless you name one.

Quick start

from apiclient import APIClient

client = APIClient(
    "https://api.github.com",
    headers={"Authorization": "token OAUTH-TOKEN"},
)

repo = await client.api.repos.klen["aio-apiclient"].get()
print(repo["full_name"])

Paths with dots or an unusual shape are addressed with [...] instead of a dot, so Slack's RPC-style methods work too:

await client.api["users.profile.set"].post(
    json={"profile": {"status_text": "working", "status_emoji": ":computer:"}},
    read_response_body=False,
)

Endpoints

Every attribute adds a path segment, every [...] adds one segment too (its value is stringified, surrounding slashes stripped). Calling the chain sends the request:

await client.api.users()  # GET  /users
await client.api.users.post()  # POST /users
await client.api.users[42].get()  # GET  /users/42
await client.api.users[42].put({"a": "b"})  # PUT  /users/42, body -> data=

The last segment is the HTTP method when it is get, post, put, patch, delete, head or options, and no method is passed explicitly. Endpoints whose own path ends with one of those words need the method spelled out:

await client.api.files.delete(method="DELETE")  # DELETE /files/delete

A positional argument becomes the request body, data= form-encoded, json= for JSON; everything else is passed to the backend unchanged. Rendering an endpoint (str(), repr(), logging) never changes it, and the same endpoint object can be awaited as many times as you like.

Responses

read_response_body and parse_response_body decide what a call returns.

read_response_body parse_response_body You get
True (default) True (default) JSON/dict for JSON responses, str for everything else
True False The backend response object, body already read (httpx.Response or aiohttp.ClientResponse)
False any The response object with the body not read; it is closed already, and sending is all you get

Both flags can be set per client (the default) or per call. The raw object is backend specific: httpx.Response has .status_code and .json(), aiohttp.ClientResponse has .status and .text().

Errors

raise_for_status=True is the default: any 4xx or 5xx response raises. The exception class is the backend's own (httpx.HTTPStatusError, aiohttp.ClientResponseError), so catch client.Error, which points at whichever backend is in use:

from apiclient import APIClient

client = APIClient("https://api.github.com")

try:
    await client.api.users.doesnotexist()
except client.Error as exc:
    print("API said no:", exc)

Turn it off per call (raise_for_status=False) when a 404 is an expected answer and you want to look at the body yourself.

Defaults

Keyword arguments other than the reserved ones (backend_type, backend_options, raise_for_status, read_response_body, parse_response_body, timeout, uds) are remembered as request defaults:

client = APIClient("https://api.example.com", headers={"X-Api-Key": "…"}, params={"lang": "en"})

# the dict default is merged: lang=en and q=notes are both sent
await client.api.search.get(params={"q": "notes"})

A dict passed to a call is merged into the same-named default (headers override one header, they do not replace the dict); any other type replaces the default. Defaults are copied for every request, so a middleware that edits options cannot corrupt the client.

Middlewares

A middleware sees and may change the method, the URL and the options before the request leaves. Registration order is execution order.

import time


@client.middleware
async def insert_timestamp(method, url, options):
    options.setdefault("headers", {})["X-Timestamp"] = str(time.time())
    return method, url, options

Backends

from apiclient.backends import BackendAIOHTTP, BackendHTTPX

client = APIClient("https://api.example.com", backend_type=BackendAIOHTTP)
client = APIClient("https://api.example.com", backend_type="httpx")

backend_options are forwarded to the backend constructor. Pass your own client to keep a connection pool, retries or a transport you configured yourself:

import httpx

transport = httpx.MockTransport(handler)
client = APIClient(
    "https://api.example.com",
    backend_options={"client": httpx.AsyncClient(transport=transport)},
)

Unix sockets use a uds:// root, and the path is passed to the backend as a socket path:

client = APIClient("uds:///var/run/docker.sock")
await client.api.containers.json()

Lifespan

await client.startup() and await client.shutdown() are the hooks app frameworks call on boot and on exit. Calling them is optional, with one caveat: the aiohttp backend creates its session on the first request if startup() was not called, and that session belongs to the event loop it was created in. Reuse a client inside one loop, or call startup() from the loop that will use it.

Typing

The client, the descriptor and the backend responses are generic:

import httpx

client: APIClient[httpx.Response] = APIClient("https://api.github.com")

raw = await client.api.users.me(parse_response_body=False)
raw.status_code  # typed: httpx.Response

Parsed bodies are typed as TResponseBody (dict | list | str | int | float | bool | None), because the content type is only known at runtime. The package ships py.typed and the test suite keeps type coverage at 100 percent.

Development

make install    # uv sync + git hooks
make test       # pytest, hermetic: no network, no tokens
make types      # pyrefly check + type coverage

Tests use httpx.MockTransport and a local aiohttp TestServer; add new cases the same way instead of calling a real API.

Issues and license

Bugs and ideas go to https://github.com/klen/aio-apiclient/issues. Code is under the MIT license.

Metadata

Release files for aio-apiclient 2.0.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 aio-apiclient 2.0.1
File Size Uploaded Provenance Actions
aio_apiclient-2.0.1.tar.gz 9.7 kB Without provenance Details for aio_apiclient-2.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for aio-apiclient 2.0.1
File Interpreter ABI Platform Actions
aio_apiclient-2.0.1-py3-none-any.whl Python 3 none any Details for aio_apiclient-2.0.1-py3-none-any.whl

Total release size: 21.4 kB

Release files / aio_apiclient-2.0.1.tar.gz

Download URL aio_apiclient-2.0.1.tar.gz
Size 9.7 kB
Tags Source
SHA-256 checksum
How to use checksums
d1a81ada94519c021d03b474286465d8096e6fce9be74dc55b07b680c174dfef
BLAKE2b-256 checksum
How to use checksums
b5d9fe9961eb3e6a86be318961c1c9f6a55a54bef25fc957f5161018a50b3c6b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / aio_apiclient-2.0.1-py3-none-any.whl

Download URL aio_apiclient-2.0.1-py3-none-any.whl
Size 11.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d9c395eb9898ddf335baa909419fd3e6c5a5a584f7ba4a72f2e76e894e8448a1
BLAKE2b-256 checksum
How to use checksums
f0e360b9d572aebc53fa1c17bbe85d06fd9b876ff4905201684d83d9d6195285
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for aio-apiclient 2.0.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.

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.

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