Skip to main content
Loss of provenance

A previous release had provenance metadata, but this release does not. View details.

⚡ mini-aiohttp

mini-aiohttp v0.6.1 is a lightweight, asynchronous HTTP/1.1 client and server framework built with Python and asyncio, with optional HTTP/2, HTTP/3, WebSocket and ASGI support.

Designed for simplicity, performance, flexibility and security. The core has no required dependencies and keeps pure-Python fallbacks. Prebuilt wheels include an optional PyO3 extension that accelerates HTTP request-head parsing and buffered response serialization.

Python Version License


✨ Features

HTTP Client

  • Asynchronous HTTP/1.1 requests.

  • Connection pooling and keep-alive.

  • Per-host concurrency limits.

  • Automatic redirect handling.

  • Bounded retries for idempotent methods.

  • Cookie management, including Max-Age expiry.

  • Automatic decoding of gzip, deflate and (with an extra) br responses.

  • Streaming response downloads.

  • Async streaming uploads.

  • Multipart form and file uploads.

  • HTTP and SOCKS5/SOCKS5h proxies, including HTTPS CONNECT/tunnelling.

  • DNS caching.

  • Configurable connection and request timeouts.

  • TLS context customization, and optional certifi CA bundle.

  • Request and response hooks.

  • Response size limits.

  • Standalone WebSocket client and server (ws:// / wss://).

  • Automatic HTTPS client: ALPN selects HTTP/2 when available, otherwise HTTP/1.1; Alt-Svc enables HTTP/3 on subsequent requests (AutoClientSession).

  • Optional HTTP/2 client/server adapters using ALPN (pip install mini-aiohttp[http2]).

  • Optional HTTP/3 client/server adapters using QUIC (pip install mini-aiohttp[http3]).

HTTP Server

  • Asynchronous HTTP server with optional Rust-accelerated request parsing and response serialization (pure-Python fallbacks supported).
  • Custom routing and path parameters.
  • Middleware support.
  • ASGI 3 adapter (ASGIApp) for uvicorn, hypercorn and other ASGI servers.
  • Gzip response compression middleware (gzip_middleware).
  • HTTP/1.1 persistent connections.
  • Chunked request-body decoding.
  • Chunked streaming responses.
  • HTTPS support using SSLContext.
  • Static file serving.
  • Path traversal protection.
  • Graceful server shutdown.
  • Connection limits.
  • Runtime server statistics.

Security

  • HTTP header validation.
  • Request framing validation.
  • Content-Length and Transfer-Encoding conflict protection.
  • CORS middleware.
  • Security headers.
  • Token-bucket rate limiting, and a Redis-backed limiter for multiple servers.
  • IP/CIDR policies.
  • Secure cookie helpers.
  • JWT bearer authentication middleware (extra).
  • JSON request validation, plain or with pydantic models (extra).
  • Bounded request and response parsing, fuzz-tested with hypothesis.

Observability (extras)

  • Prometheus metrics middleware and /metrics handler.
  • OpenTelemetry server spans.

📦 Installation

Core (no required dependencies):

pip install mini-aiohttp

Requires Python 3.11 or newer.

Prebuilt wheels are published for Linux x86_64, macOS (x86_64 and arm64) and Windows x86_64, on Python 3.11, 3.12 and 3.13. These wheels include the native Rust extension (mini_aiohttp._native). On any other platform, pip builds from the source distribution. If no Rust toolchain is available, the build still succeeds and the package uses its pure-Python parser and response serializer. Nothing in the API changes between the two.

Optional extras:

Extra What it adds
http2 HTTP/2 client and server (h2)
http3 HTTP/3 client and server (aioquic)
brotli br Content-Encoding support
orjson Faster Response.json / Request.json
certifi Mozilla CA bundle for HTTPS
speed orjson + uvloop (use with use_uvloop())
prometheus Prometheus metrics middleware
jwt JWT bearer auth middleware
pydantic Pydantic-validated JSON bodies
otel OpenTelemetry tracing middleware
all Every runtime extra above
pip install "mini-aiohttp[http2,http3]"
pip install "mini-aiohttp[brotli,orjson,certifi]"
pip install "mini-aiohttp[prometheus,jwt,pydantic,otel]"
pip install "mini-aiohttp[all]"

Install a specific version:

pip install mini-aiohttp==0.6.1

Upgrade an existing installation:

pip install --upgrade mini-aiohttp

Verify installation:

pip show mini-aiohttp

🚀 Quick Start

Create an HTTP Server

import asyncio
from mini_aiohttp import Server, Response, gzip_middleware

app = Server()
app.middleware_(gzip_middleware(min_size=1024))

@app.route("/")
async def home(req):
    return Response.json({
        "message": "Welcome to mini-aiohttp",
        "version": "0.6.1"
    })

@app.route("/hello/{name}")
async def hello(req):
    return Response.json({
        "hello": req.params["name"]
    })

async def main():
    await app.start("127.0.0.1", 8080)

    try:
        await asyncio.Event().wait()
    finally:
        await app.close()

asyncio.run(main())

Run under uvicorn (ASGI)

# myapp.py
from mini_aiohttp import ASGIApp, Response, Server

server = Server()

@server.route("/hello/{name}")
async def hello(req):
    return Response.json({"hello": req.params["name"]})

asgi_app = ASGIApp(server)
pip install uvicorn
uvicorn myapp:asgi_app --host 127.0.0.1 --port 8000

HTTP Client

import asyncio
from mini_aiohttp import ClientSession

async def main():
    async with ClientSession() as session:
        response = await session.get(
            "https://example.com"
        )

        print("Status:", response.status)
        print("Body:", response.text())

asyncio.run(main())

Faster event loop (optional)

import asyncio
from mini_aiohttp import use_uvloop

use_uvloop()  # needs the 'speed' extra; returns False if uvloop is missing
asyncio.run(main())

Prometheus metrics (optional)

from mini_aiohttp.extras.metrics import prometheus_middleware, metrics_handler

app.middleware_(prometheus_middleware())
app.route("/metrics")(metrics_handler())

JWT auth (optional)

from mini_aiohttp.extras.jwt_auth import jwt_auth

app.middleware_(jwt_auth(secret="change-me", audience="my-api", exempt=("/health",)))

@app.route("/me")
async def me(req):
    return Response.json(req.user)   # decoded claims

Pydantic-validated JSON (optional)

from pydantic import BaseModel
from mini_aiohttp.extras.pydantic_json import validated_json

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

@app.route("/users", method="POST")
@validated_json(User)
async def create(req):
    return Response.json({"ok": True, "name": req.model.name})

Rate limiting across servers (optional)

import redis.asyncio as redis
from mini_aiohttp.extras.redis_limiter import RedisRateLimiter

limiter = RedisRateLimiter(redis.Redis(), rate=20)  # 20 requests/second per client
app.middleware_(limiter.middleware())

📖 API Reference

Everything below is exported from the top-level package (from mini_aiohttp import ...) unless a module path is given. mini_aiohttp.__version__ holds the package version string.

Server

Server(*, max_connections=100_000, read_timeout=15.0, max_body_size=10 * 1024 * 1024, backlog=4096)
Method or property Purpose
route(path, method="GET") Decorator that registers a handler. Use {name} for path parameters, available as req.params. Literal routes take priority over parameterized ones. The first registration of the same method and path wins.
middleware_(fn) Registers async def fn(req, call_next). Middleware runs for every request, including 404, 405 and static files.
static(prefix, directory, *, max_file_size=50 * 1024 * 1024) Serves files under prefix. Only GET and HEAD are allowed. Paths must stay inside directory, so .. and symlinks cannot escape it. Files are streamed in 64 KiB chunks. Larger files get 413.
start(host="127.0.0.1", port=8080, *, reuse_port=False, ssl=None) Starts listening. Pass an ssl.SSLContext (server side) to serve HTTPS. Returns the asyncio server.
serve_forever(host="127.0.0.1", port=8080, **kwargs) Starts and runs until cancelled.
close(*, grace=5.0) Stops accepting connections, lets in-flight requests finish for up to grace seconds, then closes the rest. Does not raise on slow shutdown.
port Bound port (useful with port=0).
stats Snapshot of counters, see Server Statistics below.

Handlers may return a Response, or a str or bytes value, which is sent as a 200 response.

HEAD requests are answered by the matching GET route (the body is dropped and Content-Length reports the GET body length). Static files also answer HEAD.

Server responses and limits:

Situation Result
No route for the path 404
Path exists, method does not 405
Handler raises an exception 500 (logged with traceback)
Request line or header line longer than 8 KiB 431
Request head larger than 256 KiB, or more than 100 headers 431
Body larger than max_body_size 413
Duplicate Host, Content-Length or Transfer-Encoding header 400
Content-Length and Transfer-Encoding together 400
Transfer-Encoding other than exactly chunked, or non-HTTP/1.1 chunked body 501
HTTP version other than 1.0 or 1.1 505
More than max_connections open, or server draining 503
Idle or slow client longer than read_timeout Connection closed

HTTP/1.1 connections are kept alive unless the client sends Connection: close. HTTP/1.0 connections are kept alive only with Connection: keep-alive. Expect: 100-continue is answered.

Request

Passed to every handler and middleware.

Attribute or method Description
method, path, query, version Request line parts. query is the raw query string.
headers Dict with lowercase header names.
body Request body as bytes (decoded from chunked encoding if needed).
params Path parameters from {name} segments.
client Peer IP address as a string, or None.
text() Body decoded as UTF-8.
json() Body parsed as JSON. Raises ValueError on invalid input.
query_params() Query string as {name: [values]}, blanks kept.
form() Parsed multipart/form-data body as {name: [str or UploadedFile, ...]}. Raises ValueError on bad bodies, so catch it and return 400.
user, model Set by the jwt_auth and validated_json extras.

The server does not parse cookies. Read them from req.headers["cookie"].

Response

Response(status=200, body=b"", headers=None)
  • body may be str (encoded as UTF-8) or bytes. headers names are stored lowercase.
  • When not set, content-type defaults to text/plain; charset=utf-8. content-length and connection are added automatically.
  • Response.json(data, status=200): JSON body with application/json; charset=utf-8.
  • Response.stream(chunks, status=200, headers=None): sends an async iterable of bytes or str as a chunked response, without buffering it all in memory. Streamed bodies are closed if the connection drops.
  • add_set_cookie(raw): queues a Set-Cookie header. Use the set_cookie helper for safe defaults.
  • text(encoding="utf-8"): body as text, for buffered responses.
  • reason, is_streaming: status reason phrase and streaming flag.

On the client side, a Response also has status, headers (lowercase names), body (bytes), set_cookies (raw Set-Cookie values) and these methods for streamed bodies: iter_chunks(), aread() and aclose(). text() on a streamed response raises RuntimeError until aread() has been called. To parse a JSON body on the client, use json.loads(response.body). Response.json is a constructor for server responses, not an instance method.

ASGI adapter

from mini_aiohttp import ASGIApp

ASGIApp(server, *, on_startup=None, on_shutdown=None)

ASGIApp wraps a Server so that any ASGI 3 server can run it: uvicorn, hypercorn and similar. The adapter does no routing of its own. Routes, middleware, static files and the 404, 405 and 500 responses all come from Server.

Area Behaviour
HTTP requests Go through the same dispatch code as the built-in server, so middleware runs for every request.
Path Uses the ASGI raw_path when provided, so percent-escapes are decoded once, as on the built-in server.
Request body Larger than max_body_size gets 413 before routing, as on the built-in server.
HEAD The body is dropped and Content-Length is kept.
Streaming Response.stream chunks are passed to the ASGI server, which does the chunked framing.
Framing headers Your Content-Length and Transfer-Encoding headers are ignored, because the ASGI server sets framing.
Client disconnect No response is sent.
Lifespan on_startup and on_shutdown run once each. If one raises, the server receives a lifespan.*.failed message.
WebSocket Refused with a close before accept. Use WebSocketServer on its own port.
Limits Request-line length, header count, idle timeout and connection cap are enforced by the ASGI server, not by Server. max_body_size still applies.
Statistics Requests served through ASGIApp are counted in server.stats.

Example:

from mini_aiohttp import ASGIApp, Response, Server

server = Server()

@server.route("/users/{user_id}")
async def user(req):
    return Response.json({"id": req.params["user_id"]})

async def open_resources():
    ...  # e.g. create a database pool

async def close_resources():
    ...  # e.g. close it

asgi_app = ASGIApp(server, on_startup=open_resources, on_shutdown=close_resources)

ClientSession

ClientSession(
    *, timeout=10.0, connect_timeout=5.0, max_per_host=1000, max_idle_per_host=100,
    max_response_size=1 GiB, max_redirects=10, retries=0,
    retry_statuses=(429, 502, 503, 504), backoff=0.5, cookies=True,
    ssl_context=None, proxy=None, dns_cache_ttl=300.0,
    on_request=(), on_response=(), user_agent="mini-aiohttp",
)

Use it as an async context manager, or call close() yourself.

Method Description
get(url, **kwargs) Shortcut for request("GET", url, ...).
post(url, **kwargs) Shortcut for request("POST", url, ...).
request(method, url, *, headers=None, data=None, json=None, form=None, files=None, timeout=None, stream=False, allow_redirects=True) Sends one request and returns a Response.
close() Closes pooled connections.

request arguments:

  • data: str or bytes body, or an async iterable of chunks. An async iterable is sent with Transfer-Encoding: chunked.
  • json: any JSON-serializable value. Sets Content-Type: application/json unless you set one.
  • form: dict of fields, sent as multipart/form-data.
  • files: dict mapping a field name to (filename, bytes, content_type), sent with form.
  • json cannot be combined with form or files. A streaming data body cannot be combined with json, form or files.
  • timeout: overrides the session timeout for this request. It covers sending the request and reading the response headers, and for non-streamed responses the whole body.
  • stream=True: reads the body lazily with iter_chunks(), aread() or aclose().
  • allow_redirects=False: returns the 3xx response instead of following it.

Defaults and behaviour:

  • Default headers: Host, User-Agent, Accept: */*, and Accept-Encoding: gzip, deflate (plus br when the brotli extra is installed). A caller header with the same name, in any case, replaces the default.
  • You cannot set Content-Length or Transfer-Encoding yourself. The client raises ValueError.
  • Retries (retries) apply only to GET, HEAD, PUT, DELETE, OPTIONS and TRACE, and never to streaming bodies. POST and PATCH are never retried. Backoff is exponential, capped at 10 seconds. A numeric Retry-After is honoured up to 60 seconds.
  • Redirects (301, 302, 303, 307, 308) are followed up to max_redirects. 303 becomes GET. 301 and 302 become GET when sent as POST. A streaming body cannot be replayed for 307 or 308. Authorization and Proxy-Authorization are removed when the redirect goes to another origin. Only http and https targets are followed.
  • Response bodies are decoded for gzip, deflate and br. After decoding, content-encoding and content-length are removed from headers.
  • Bodies larger than max_response_size raise ClientError. Pass None to disable the limit.
  • Response headers: more than 200 headers, or a line longer than 64 KiB, raise ClientError.
  • Cookies are stored in session.cookie_jar (None when cookies=False). A caller-supplied Cookie header turns off automatic cookies for that request.
  • on_request hooks are called as hook(method, url, headers), and may be async. on_response hooks are called as hook(response), and may be async.
  • Connection pooling is per host, port and scheme. The DNS cache uses dns_cache_ttl seconds (0 disables it).

AutoClientSession

AutoClientSession(*, timeout=10.0, ssl_context=None, **client_options)

A session for mixed HTTP/1.1, HTTP/2 and HTTP/3 traffic.

  • For https URLs, the first request uses HTTP/2 when ALPN negotiates it. Otherwise it uses HTTP/1.1.
  • Responses with an Alt-Svc: h3=... header switch later requests to that origin over HTTP/3. A failed HTTP/3 request falls back to the other protocols.
  • HTTP/2 is used only when ssl_context is not given. With a custom context, requests use HTTP/1.1, and HTTP/3 if Alt-Svc advertises it.
  • Methods: request(method, url, *, headers=None, data=b""), get(url, **kwargs), post(url, **kwargs), close(). It supports async context management. It always returns a buffered Response, so it has no stream option.
  • Other keyword arguments go to ClientSession for the HTTP/1.1 path.

Batch requests

from mini_aiohttp import fetch_all, gather_requests
  • fetch_all(requests, *, concurrency=100, timeout=10.0, return_exceptions=True): opens a session, runs all requests, and closes it.
  • gather_requests(session, requests, *, concurrency=100, return_exceptions=True): runs requests on an existing session.

Each item in requests can be a URL string (GET), a (method, url) or (method, url, kwargs) tuple, or a dict such as {"method": "POST", "url": ..., "json": ...}. Results come back in input order. By default a failed request is returned as its exception object, and it does not cancel the others. concurrency must be an integer of at least 1.

results = await fetch_all([
    "https://example.com/a",
    ("POST", "https://example.com/b", {"json": {"x": 1}}),
    {"method": "GET", "url": "https://example.com/c"},
])

Cookies

from mini_aiohttp import CookieJar

CookieJar stores Set-Cookie values and returns the matching Cookie header. It supports the Domain, Path, Secure and Max-Age attributes. Expires is ignored. A Domain attribute that does not match the response host is rejected. Host-only cookies are the default. Expired cookies are removed. update(url, set_cookie_values) and header_for(url) are the main methods. ClientSession creates one automatically (cookies=True).

WebSocket

from mini_aiohttp import WebSocket, WebSocketServer, WebSocketError

Client:

WebSocket.connect(url, *, headers=None, ssl_context=None, timeout=10.0)  # ws:// or wss://
  • send(data): str is sent as a text message, bytes-like as a binary message.
  • recv(): returns a str for text, bytes for binary, or None after a close frame. Pings are answered automatically.
  • close(code=1000, reason=""): sends a close frame. reason is at most 123 UTF-8 bytes.
  • closed: True after the connection has closed.
  • headers cannot override handshake headers (Host, Upgrade, Connection, Sec-WebSocket-Key, Sec-WebSocket-Version).
ws = await WebSocket.connect("wss://example.com/chat")
await ws.send("hello")
reply = await ws.recv()
await ws.close(1000, "bye")

Server:

WebSocketServer(handler, *, ssl=None, max_connections=1000)
  • handler is async def handler(websocket, path). path is the request target, including any query string.
  • start(host="127.0.0.1", port=8765) and close().
  • The server is standalone. It is not mounted on the HTTP/1.1 Server class.
  • Frames and messages are limited to 16 MiB. The handshake must complete within 10 seconds.
  • The Origin header is not checked, and the handler receives only the path, not the headers.
async def handler(ws, path):
    while True:
        msg = await ws.recv()
        if msg is None:
            break
        await ws.send(msg)

server = WebSocketServer(handler)
await server.start("127.0.0.1", 8765)

WebSocketError is raised for invalid handshakes, frames, or use of a closed connection.

HTTP/2 adapters (extra: http2)

from mini_aiohttp import HTTP2Client, HTTP2Server
  • HTTP2Client(*, ssl_context=None, timeout=15.0): get(url, *, headers=None) and request(method, url, *, headers=None, data=b""). Both return (status, headers, body). Only https:// URLs are supported. ALPN must negotiate h2. Each request uses its own connection.
  • HTTP2Server(handler, *, ssl_context, max_body_size=10 * 1024 * 1024): start(host="127.0.0.1", port=8443) and close(). The handler is async def handler(method, path, headers, body) and returns (status, headers, body). The adapter sets h2 as the ALPN protocol on ssl_context, so use a context dedicated to this server.
import ssl

ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ctx.load_cert_chain("cert.pem", "key.pem")

async def handler(method, path, headers, body):
    return 200, {"content-type": "text/plain"}, b"hello over h2"

server = HTTP2Server(handler, ssl_context=ctx)
await server.start("127.0.0.1", 8443)

HTTP/3 adapters (extra: http3)

from mini_aiohttp import HTTP3Client, HTTP3Server

HTTP/3 runs over QUIC on UDP and requires TLS 1.3. It is not a fallback for TCP connections, and the endpoint must support HTTP/3.

  • HTTP3Client(*, verify=True, timeout=15.0): get(url, *, headers=None) and request(method, url, *, headers=None, data=b""). Both return (status, headers, body). verify=False disables certificate verification.
  • HTTP3Server(handler, *, certificate, private_key, max_body_size=10 * 1024 * 1024): start(host="0.0.0.0", port=443) and close(). certificate and private_key are file paths. The handler signature is the same as HTTP/2.

Security helpers

from mini_aiohttp import cors, security_headers, RateLimiter, ip_policy, set_cookie, require_json
  • cors(*, allow_origins, allow_methods=("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"), allow_headers=("Content-Type", "Authorization"), allow_credentials=False, max_age=600): middleware. Only origins in allow_origins are reflected, by exact match. "*" is allowed only without credentials, otherwise ValueError. Preflight requests (OPTIONS with Access-Control-Request-Method) get 204.
  • security_headers(*, csp="default-src 'self'", hsts_max_age=None): middleware. Adds X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: no-referrer, a CSP, and optionally HSTS. Headers the handler already set are kept.
  • RateLimiter(*, rate, burst, max_clients=10_000, clock=time.monotonic): token bucket keyed by client IP. rate is tokens per second, burst is the bucket size. check(key) returns None if allowed, or the seconds to wait. middleware() returns 429 with Retry-After. Memory is bounded by max_clients.
  • ip_policy(*, allow=None, deny=None): middleware that allows or denies IP addresses and CIDR networks. deny is checked first. If allow is given, only those networks pass. Clients with an unknown address get 403. IPv4-mapped IPv6 clients are checked as IPv4.
  • set_cookie(resp, name, value, *, max_age=None, path="/", secure=True, httponly=True, samesite="Lax"): adds a Set-Cookie header to resp and returns resp. The value is URL-encoded. SameSite=None requires secure=True.
  • require_json(schema): decorator for handlers. schema maps field names to types, or tuples of types such as (int, float). A missing field or wrong type gets 400, and so does invalid JSON. A bool is rejected for an int field.
@app.route("/users", method="POST")
@require_json({"name": str, "age": int})
async def create(req):
    return Response.json({"ok": True})

Compression

from mini_aiohttp import gzip_middleware

gzip_middleware(*, min_size=1024, level=6) compresses buffered responses for clients that accept gzip. It skips bodies under min_size, responses that already have Content-Encoding, and types that are not text, JSON, JavaScript, XML or SVG. Streamed responses pass through unchanged. It adds Vary: Accept-Encoding. level must be 1 to 9.

Multipart uploads

  • Client: session.request("POST", url, form={"title": "x"}, files={"avatar": ("a.png", data, "image/png")}).
  • Server: req.form() returns {name: [str or UploadedFile]}. UploadedFile is a dataclass with filename, content_type and data. At most 200 parts are accepted.

Proxies

  • proxy="http://host:port": HTTP proxy. HTTPS targets use CONNECT tunnels.
  • proxy="socks5://user:pass@host:port": SOCKS5 proxy. DNS is resolved locally.
  • proxy="socks5h://...": SOCKS5 proxy with DNS resolved by the proxy.

An HTTP proxy must support CONNECT for HTTPS. Proxy authentication is supported for SOCKS5 only.

Optional accelerators

  • use_uvloop(): switches asyncio to uvloop if it is installed. Call it before asyncio.run(). Returns True when it switched.
  • brotli extra: enables br decoding. Without it, a br response raises ClientError.
  • orjson extra: used automatically by Response.json, Request.json and the JSON helpers when installed.
  • certifi extra: the default TLS context uses the certifi CA bundle.

Extras (mini_aiohttp.extras)

Each extra imports its package only when it is used.

  • metrics.prometheus_middleware(registry=None, *, namespace="http") and metrics_handler(registry=None): counts requests by method and status, records latency by method, and serves the Prometheus text format. Extra: prometheus.
  • jwt_auth.jwt_auth(secret, *, algorithms=("HS256",), audience=None, issuer=None, exempt=()): requires Authorization: Bearer <token>. Decoded claims are stored in req.user. Missing or invalid tokens get 401 with WWW-Authenticate. exempt lists exact paths that skip authentication. Extra: jwt.
  • pydantic_json.validated_json(model): decorator that parses the body into a pydantic v2 model and stores it in req.model. Invalid JSON gets 400. Validation errors get 422 with {"detail": [...]}. Extra: pydantic.
  • redis_limiter.RedisRateLimiter(client, *, rate, window=1, prefix="mini-aiohttp:rl", clock=time.time): fixed-window rate limit shared across processes. client is any async Redis client with incr and expire, such as redis.asyncio.Redis. check(key) is async. middleware() returns 429 with Retry-After. No extra package is needed.
  • tracing.tracing_middleware(*, tracer_name="mini_aiohttp"): creates one server span per request, with the method, path and status code. Spans use the globally configured OpenTelemetry tracer. Extra: otel.

Errors

  • ClientError: client-side failures, including malformed responses, oversized bodies, too many redirects and unsupported encodings.
  • WebSocketError: WebSocket handshake, frame and connection errors.
  • ValueError: invalid arguments, such as an unsupported URL scheme or an invalid header.
  • The server never lets a handler exception reach the client. It returns 500 and logs the traceback.

🌊 Streaming Responses

Create asynchronous chunked responses without buffering the complete response body.

import asyncio
from mini_aiohttp import Server, Response

app = Server()

@app.route("/stream")
async def stream(req):

    async def generate():
        for i in range(5):
            yield f"Message {i}\n"
            await asyncio.sleep(1)

    return Response.stream(
        generate(),
        headers={
            "Content-Type": "text/plain"
        }
    )

asyncio.run(
    app.serve_forever("127.0.0.1", 8080)
)

Supports HTTP/1.1 chunked response transfer.


📊 Server Statistics

Monitor basic server activity:

print(app.stats)

Example output:

{
    "active_connections": 0,
    "total_connections": 1,
    "total_requests": 2,
    "status_counts": {
        200: 1,
        404: 1
    },
    "uptime_requests_per_connection": 2.0
}

Statistics are process-local and represent basic runtime counters.


🧪 Testing

From a source checkout, install the development tools:

pip install -e ".[dev,all]"

Run tests with coverage:

python -m pytest -v --cov

Lint, format and type-check:

ruff check .
ruff format --check .
mypy

Enable the git hooks once:

pre-commit install

Build distributions:

pip install build twine
python -m build
python -m twine check dist/*

⚙️ Compatibility

Component Support
Python 3.11+
Type hints Yes (py.typed)
HTTP/1.1 Yes
HTTPS Server Yes
Chunked Requests Yes
Streaming Responses Yes
Content-Encoding gzip, deflate (core); br (brotli extra)
Response compression gzip middleware (core)
SOCKS5 Yes, HTTP targets
HTTP/2 Optional adapters (HTTP2Client, HTTP2Server)
HTTP/3 Optional adapters (HTTP3Client, HTTP3Server)
WebSockets Standalone RFC 6455 client/server
ASGI 3 ASGIApp for HTTP and lifespan (no WebSocket)
Prebuilt wheels Linux x86_64, macOS x86_64 and arm64, Windows x86_64 (CPython 3.11–3.13)

🛡️ Protocol Limitations

  • HTTP/2 adapter currently uses one request per connection, and requires TLS ALPN negotiation.
  • HTTP/3 requires QUIC/UDP and TLS 1.3 certificates, plus an HTTP/3-capable endpoint. It cannot be transparently substituted on arbitrary TCP connections.
  • WebSocket server is not mounted as a route on the HTTP/1.1 Server class. WebSocket support is standalone.
  • WebSocket Origin checking is not built in. If you authenticate with cookies, validate the Origin header in your handler.
  • WebSocket compression (permessage-deflate) is not implemented.
  • Static files do not support Range requests or ETag yet.
  • No automatic multi-process worker manager is included. Use your ASGI server's worker options (for example uvicorn --workers) with ASGIApp.
  • WebSockets are not available through ASGIApp. Run WebSocketServer on its own port.

Additional notes:

  • HTTP/2 and HTTP/3 are optional adapters and require their respective extras.
  • AutoClientSession uses HTTP/2 only when no custom ssl_context is given.
  • max_response_size limits encoded and decoded response sizes. Gzip/deflate use zlib's bounded-output API; Brotli's Python decoder has no output-length parameter, so its output is checked after each decoder call rather than hard-capped during allocation.
  • HTTPS proxy tunnels require a CONNECT-capable HTTP proxy or SOCKS5 proxy.
  • Streaming responses require asynchronous iterables.
  • Under ASGIApp, the ASGI server enforces the request-line, header-count and keep-alive limits from the first table above. max_connections and read_timeout on Server apply only to the built-in start() and serve_forever() path.
  • Prebuilt wheels are not published for Linux aarch64, 32-bit platforms or musl Linux. Those platforms install from the source distribution.


📄 License

This project is licensed under the MIT License.


mini-aiohttp v0.6.1

Lightweight. Asynchronous. Flexible.

Metadata

Release files for mini-aiohttp 0.6.1

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

Loss of provenance

These files do not have provenance metadata, despite files in a prior release including this data.

We recommend further investigation before installing these files. View details.

Source distribution (sdist)

Source distribution for mini-aiohttp 0.6.1
File Size Uploaded Provenance Actions
mini_aiohttp-0.6.1.tar.gz 99.8 kB Without provenance Details for mini_aiohttp-0.6.1.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for mini-aiohttp 0.6.1
File Actions
mini_aiohttp-0.6.1-cp313-cp313-win_amd64.whl CPython 3.13 CPython 3.13 Windows x86-64 Details for mini_aiohttp-0.6.1-cp313-cp313-win_amd64.whl
mini_aiohttp-0.6.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.13 CPython 3.13 Linux glibc 2.17+ x86-64 Details for mini_aiohttp-0.6.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
mini_aiohttp-0.6.1-cp313-cp313-macosx_11_0_x86_64.whl CPython 3.13 CPython 3.13 macOS 11.0+ x86-64 Details for mini_aiohttp-0.6.1-cp313-cp313-macosx_11_0_x86_64.whl
mini_aiohttp-0.6.1-cp313-cp313-macosx_11_0_arm64.whl CPython 3.13 CPython 3.13 macOS 11.0+ ARM64 Details for mini_aiohttp-0.6.1-cp313-cp313-macosx_11_0_arm64.whl
mini_aiohttp-0.6.1-cp312-cp312-win_amd64.whl CPython 3.12 CPython 3.12 Windows x86-64 Details for mini_aiohttp-0.6.1-cp312-cp312-win_amd64.whl
mini_aiohttp-0.6.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.12 CPython 3.12 Linux glibc 2.17+ x86-64 Details for mini_aiohttp-0.6.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
mini_aiohttp-0.6.1-cp312-cp312-macosx_11_0_x86_64.whl CPython 3.12 CPython 3.12 macOS 11.0+ x86-64 Details for mini_aiohttp-0.6.1-cp312-cp312-macosx_11_0_x86_64.whl
mini_aiohttp-0.6.1-cp312-cp312-macosx_11_0_arm64.whl CPython 3.12 CPython 3.12 macOS 11.0+ ARM64 Details for mini_aiohttp-0.6.1-cp312-cp312-macosx_11_0_arm64.whl
mini_aiohttp-0.6.1-cp311-cp311-win_amd64.whl CPython 3.11 CPython 3.11 Windows x86-64 Details for mini_aiohttp-0.6.1-cp311-cp311-win_amd64.whl
mini_aiohttp-0.6.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.11 CPython 3.11 Linux glibc 2.17+ x86-64 Details for mini_aiohttp-0.6.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
mini_aiohttp-0.6.1-cp311-cp311-macosx_11_0_x86_64.whl CPython 3.11 CPython 3.11 macOS 11.0+ x86-64 Details for mini_aiohttp-0.6.1-cp311-cp311-macosx_11_0_x86_64.whl
mini_aiohttp-0.6.1-cp311-cp311-macosx_11_0_arm64.whl CPython 3.11 CPython 3.11 macOS 11.0+ ARM64 Details for mini_aiohttp-0.6.1-cp311-cp311-macosx_11_0_arm64.whl

Total release size: 3.1 MB

Release files / mini_aiohttp-0.6.1.tar.gz

Loss of provenance

This file belongs to a release without provenance metadata, despite a prior release including this data.

We recommend further investigation before installing this file. View details.

Download URL mini_aiohttp-0.6.1.tar.gz
Size 99.8 kB
Tags Source
SHA-256 checksum
How to use checksums
93e82e229e048df9e1006ef1a22b840a8c666a4b2614792c415b8721b08dd56b
BLAKE2b-256 checksum
How to use checksums
487ef0bec48aae2b427291cf4dbae325b2268bc99a91f690948d2006f9ecf31e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / mini_aiohttp-0.6.1-cp313-cp313-win_amd64.whl

Loss of provenance

This file belongs to a release without provenance metadata, despite a prior release including this data.

We recommend further investigation before installing this file. View details.

Download URL mini_aiohttp-0.6.1-cp313-cp313-win_amd64.whl
Size 167.8 kB
Tags CPython 3.13 Windows x86-64
SHA-256 checksum
How to use checksums
7a14dfb66b87d5e1d9569cdae5694311ca2078e96c8b56c757df210c5075b73f
BLAKE2b-256 checksum
How to use checksums
2a8a4dec4408f803e029dfa5b2095f3fbb42e796d25620ba55d949f912d46dee
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / mini_aiohttp-0.6.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Loss of provenance

This file belongs to a release without provenance metadata, despite a prior release including this data.

We recommend further investigation before installing this file. View details.

Download URL mini_aiohttp-0.6.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 298.8 kB
Tags CPython 3.13 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
5e7415a47265d1e586c007d595b4dc767254f19921a6a607040575bed0241a61
BLAKE2b-256 checksum
How to use checksums
26186d4293fb5879460e4dc825633c80342397244c34e91b575fa434c4386f6d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / mini_aiohttp-0.6.1-cp313-cp313-macosx_11_0_x86_64.whl

Loss of provenance

This file belongs to a release without provenance metadata, despite a prior release including this data.

We recommend further investigation before installing this file. View details.

Download URL mini_aiohttp-0.6.1-cp313-cp313-macosx_11_0_x86_64.whl
Size 270.3 kB
Tags CPython 3.13 macOS 11.0+ x86-64
SHA-256 checksum
How to use checksums
4b5302953bffcedc11667f49c62172fa1af37b2f15f292578a8c50e5c1fd1065
BLAKE2b-256 checksum
How to use checksums
e3aec3c0f636123775ea0b069d3b93b1a22b25a20cf5ebf6c6cb7dbf111c8b9b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / mini_aiohttp-0.6.1-cp313-cp313-macosx_11_0_arm64.whl

Loss of provenance

This file belongs to a release without provenance metadata, despite a prior release including this data.

We recommend further investigation before installing this file. View details.

Download URL mini_aiohttp-0.6.1-cp313-cp313-macosx_11_0_arm64.whl
Size 266.3 kB
Tags CPython 3.13 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
08dab8333d66d06305c35db6d71afe54cc4ab78de1dda87ac29fab1be8acacf6
BLAKE2b-256 checksum
How to use checksums
fa389828c14455ff5b8cfdcd9472135b1caa901b935debc01d705b0ad533a33f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / mini_aiohttp-0.6.1-cp312-cp312-win_amd64.whl

Loss of provenance

This file belongs to a release without provenance metadata, despite a prior release including this data.

We recommend further investigation before installing this file. View details.

Download URL mini_aiohttp-0.6.1-cp312-cp312-win_amd64.whl
Size 168.1 kB
Tags CPython 3.12 Windows x86-64
SHA-256 checksum
How to use checksums
46d1afada5a359dc17243b1a7b8621302c5a5af5604a2aa4ab32889e6d25f793
BLAKE2b-256 checksum
How to use checksums
d4b93fab10e1241ca54776a65382ab29856090bfe9b2a7a3e5f03885050f81f2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / mini_aiohttp-0.6.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Loss of provenance

This file belongs to a release without provenance metadata, despite a prior release including this data.

We recommend further investigation before installing this file. View details.

Download URL mini_aiohttp-0.6.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 299.5 kB
Tags CPython 3.12 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
130f1788d3dc2f3338ab693195a6fc67cd4b4d0fbed80ec2e88f598aae668b74
BLAKE2b-256 checksum
How to use checksums
40e6cf2ceaad3e9fa08168c0671f1e656493e1dd619be00097bbf4b10bc8f761
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / mini_aiohttp-0.6.1-cp312-cp312-macosx_11_0_x86_64.whl

Loss of provenance

This file belongs to a release without provenance metadata, despite a prior release including this data.

We recommend further investigation before installing this file. View details.

Download URL mini_aiohttp-0.6.1-cp312-cp312-macosx_11_0_x86_64.whl
Size 270.7 kB
Tags CPython 3.12 macOS 11.0+ x86-64
SHA-256 checksum
How to use checksums
56cd2f65ecf3b0a2921d0b463b094a14c13563fdd5ab6e1ad5805ad4bb905617
BLAKE2b-256 checksum
How to use checksums
e4c41f44ab9650a13f95ec482376d799bda9419affa4cdc1a428b352a70c2501
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / mini_aiohttp-0.6.1-cp312-cp312-macosx_11_0_arm64.whl

Loss of provenance

This file belongs to a release without provenance metadata, despite a prior release including this data.

We recommend further investigation before installing this file. View details.

Download URL mini_aiohttp-0.6.1-cp312-cp312-macosx_11_0_arm64.whl
Size 266.4 kB
Tags CPython 3.12 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
2d88d1af9d8452b4ec8bcb22d7d9d1d0cafaff403e3e642ade607c1201df079e
BLAKE2b-256 checksum
How to use checksums
7ef4ba66326c1f171cbe0c7feeda39d832ce8e2c5b8e49003919b48fb51701e6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / mini_aiohttp-0.6.1-cp311-cp311-win_amd64.whl

Loss of provenance

This file belongs to a release without provenance metadata, despite a prior release including this data.

We recommend further investigation before installing this file. View details.

Download URL mini_aiohttp-0.6.1-cp311-cp311-win_amd64.whl
Size 168.3 kB
Tags CPython 3.11 Windows x86-64
SHA-256 checksum
How to use checksums
996615cc6912940b39c5241d8062f75cdd337806820c2408727230b64e7f75f3
BLAKE2b-256 checksum
How to use checksums
8182bc57e099f1e63f80c5afdcded1ab53816cf7e8fbcaacd686fe6f43f30c34
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / mini_aiohttp-0.6.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Loss of provenance

This file belongs to a release without provenance metadata, despite a prior release including this data.

We recommend further investigation before installing this file. View details.

Download URL mini_aiohttp-0.6.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 299.1 kB
Tags CPython 3.11 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
cb89fc96198a056331a6b3f9f96cc6e69f72e53827392e64c417163819d48e46
BLAKE2b-256 checksum
How to use checksums
c360b8744aa32d4cd11eb48698f30de639a6a6e63c38f0645492deb582ee12e0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / mini_aiohttp-0.6.1-cp311-cp311-macosx_11_0_x86_64.whl

Loss of provenance

This file belongs to a release without provenance metadata, despite a prior release including this data.

We recommend further investigation before installing this file. View details.

Download URL mini_aiohttp-0.6.1-cp311-cp311-macosx_11_0_x86_64.whl
Size 272.5 kB
Tags CPython 3.11 macOS 11.0+ x86-64
SHA-256 checksum
How to use checksums
8ca05c389ba9546a08a632a719b45e8918d8eb2bc99400bed78abd0656796d3c
BLAKE2b-256 checksum
How to use checksums
4de79817e16f680835bc0a83cc7f9742aa07c223f487122e4a3e12b973268776
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / mini_aiohttp-0.6.1-cp311-cp311-macosx_11_0_arm64.whl

Loss of provenance

This file belongs to a release without provenance metadata, despite a prior release including this data.

We recommend further investigation before installing this file. View details.

Download URL mini_aiohttp-0.6.1-cp311-cp311-macosx_11_0_arm64.whl
Size 268.1 kB
Tags CPython 3.11 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
3606189202b753845c68ae77ff2ae21c3e9279b7b8b14a3943bd61fe686d47f2
BLAKE2b-256 checksum
How to use checksums
ac04c860fea1fa1b81c42dc227814a2acbd66940315df5921caa94e8a6d7d33e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for mini-aiohttp 0.6.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.

Loss of provenance

A previous release of these files had provenance metadata, but this release does not.

While this could reflect a routine change by the project maintainers, it may also indicate that the release files have been compromised.

Release comparison

  • Removed 0.5.3 2 files With provenance
  • Added 0.6.1 13 files Without provenance

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