Skip to content

API Reference

hawkapi.HawkAPI

Bases: Router

The main application class. An ASGI 3.0 callable.

Integrates routing, middleware pipeline, DI container, and lifespan management.

__init__(*, title='HawkAPI', version='0.1.0', description='', debug=False, validation_error_status=400, max_body_size=10 * 1024 * 1024, prefix='', tags=None, container=None, lifespan=None, docs_url='/docs', redoc_url='/redoc', scalar_url='/scalar', openapi_url='/openapi.json', observability=None, serverless=False, health_url='/healthz', request_timeout=None)

openapi(api_version=None)

Generate (or return cached) the OpenAPI schema.

Pass api_version to get a spec filtered to routes of that version.

add_middleware(middleware_class, **kwargs)

Add a middleware class to the stack.

Middleware is applied in order: first added = outermost (runs first).

on_startup(func)

Register a startup hook (decorator).

on_shutdown(func)

Register a shutdown hook (decorator).

exception_handler(exc_class)

Register a custom exception handler.

include_router(router)

Include a sub-router and invalidate cached OpenAPI specs.

include_controller(controller_class)

Include a controller and invalidate cached OpenAPI specs.

hawkapi.Router

Collects routes and mounts into the application.

routes property

All registered routes.

tree property

The underlying radix tree used for route matching.

add_route(path, handler, *, methods, name=None, status_code=200, response_model=None, tags=None, summary=None, description=None, include_in_schema=True, deprecated=False, version=None, permissions=None)

Register a route directly.

delete(path, *, status_code=204, response_model=None, tags=None, summary=None, description=None, name=None, include_in_schema=True, deprecated=False, version=None, permissions=None)

Register a DELETE route handler.

get(path, *, status_code=200, response_model=None, tags=None, summary=None, description=None, name=None, include_in_schema=True, deprecated=False, version=None, permissions=None)

Register a GET route handler.

include_controller(controller_class)

Mount a class-based controller.

Collects all decorated methods and registers them as routes.

include_router(router)

Mount a sub-router. Its routes are merged into this router's tree.

mount(path, app)

Mount a sub-application (e.g., StaticFiles) at the given path.

Usage

app.mount("/static", StaticFiles(directory="static"))

patch(path, *, status_code=200, response_model=None, tags=None, summary=None, description=None, name=None, include_in_schema=True, deprecated=False, version=None, permissions=None)

Register a PATCH route handler.

post(path, *, status_code=201, response_model=None, tags=None, summary=None, description=None, name=None, include_in_schema=True, deprecated=False, version=None, permissions=None)

Register a POST route handler.

put(path, *, status_code=200, response_model=None, tags=None, summary=None, description=None, name=None, include_in_schema=True, deprecated=False, version=None, permissions=None)

Register a PUT route handler.

websocket(path, *, name=None, permissions=None)

Register a WebSocket handler.

hawkapi.Route dataclass

Represents a single registered route.

hawkapi.Request

HTTP request wrapper with lazy parsing for maximum performance.

client property

Client address as (host, port), or None if unavailable.

content_type property

The Content-Type header value, or None if absent.

cookies property

Parsed cookies from the Cookie header (lazily cached).

headers property

Parsed request headers (lazily cached).

method property

The HTTP method (GET, POST, etc.).

path property

The request path.

path_params property

Path parameters extracted from the URL by the router.

query_params property

Parsed query parameters (lazily cached).

query_string property

The raw query string as bytes.

scope property

The raw ASGI scope.

url property

Full request URL reconstructed from scope.

url_scheme property

URL scheme (http or https).

body() async

Read and return the full request body (lazily cached).

form() async

Parse form data (urlencoded or multipart).

json() async

Deserialize the request body from JSON (lazily cached).

hawkapi.Response

Base HTTP response that sends via the ASGI protocol.

headers property

Response headers as a string-to-string dictionary.

__init__(content=b'', *, status_code=200, headers=None, content_type='text/plain; charset=utf-8')

Create a response with content, status code, and optional headers.

hawkapi.JSONResponse

High-performance JSON response using msgspec.json.encode.

__init__(content=None, *, status_code=200, headers=None)

Create a JSON response, serializing content with msgspec.

hawkapi.HTTPException

Bases: Exception

Raise to immediately return an HTTP error response.

Usage

raise HTTPException(404, detail="User not found") raise HTTPException(403, detail="Forbidden", headers={"X-Reason": "expired"})

to_response()

Convert to an ASGI-compatible Response.

hawkapi.Depends

Marker to declare a dependency.

Usage in route handlers

async def handler(db: Annotated[DBSession, Depends(get_db)]): ...

Usage in container registration

container.scoped(DBSession, factory=lambda pool=Depends(DatabasePool): pool.session())

Usage with named dependencies

async def handler(cache: Annotated[Redis, Depends(name="cache_redis")]): ...

hawkapi.Container

DI Container with lifecycle management.

Usage

container = Container() container.singleton(DatabasePool, factory=create_pool) container.scoped(DBSession, factory=create_session) container.transient(RequestLogger, factory=RequestLogger)

Inside routes (automatic via framework):

async def handler(session: DBSession): ...

Outside routes (manual):

async with container.scope() as scope: session = await scope.resolve(DBSession)

has(service_type, name=None)

Check if a provider is registered.

override(service_type, *, factory, name=None)

Temporarily replace a provider (for testing).

register(service_type, *, factory, lifecycle, name=None)

Register a dependency provider.

resolve(service_type, name=None) async

Resolve a dependency directly (for singletons or transients).

For scoped dependencies, use container.scope() instead.

scope()

Create a new dependency scope (e.g., for a request).

scoped(service_type, *, factory, name=None)

Register a scoped dependency (created once per scope/request).

singleton(service_type, *, factory, name=None)

Register a singleton (created once, shared globally).

transient(service_type, *, factory, name=None)

Register a transient dependency (new instance every time).