pre-alpha

Reference

Core API: application, routing and HTTP

Updated November 20, 2026 19 min read

from hinoki import Hinoki, RouteGroup, Mount, http, errors and from hinoki.project import manifest_routes. Guides: function-based APIs, class-based APIs, register routes, errors.

hinoki.app.Hinoki

Hinoki(
    *,
    settings: object | None = None,
    include: Sequence[Includable] | None = None,
    modules: Sequence[Module | type[Module]] = (),
    commands: Sequence[Command | type[Command]] = (),
    on_startup: Sequence[Hook] = (),
    on_shutdown: Sequence[Hook] = (),
    startup_url: str | None = None,
    runtime: RuntimeConfig | None = None,
    title: str | None = None,
    version: str | None = None,
    openapi_url: str | Unset | None = UNSET,
    docs_url: str | Unset | None = UNSET,
    redoc_url: str | Unset | None = UNSET,
    rules: RuleSet | None = None,
    enforce_rules: bool = True,
    waivers: str | Path | None = None,
    parsers: Sequence[Parser] | None = None,
    renderers: Sequence[Renderer] | None = None,
    middleware: Sequence[Middleware] = (),
)

A Hinoki application.

Registering routes builds the native router; nothing connects to anything, so factories returning Hinoki are safe to import and call. The instance is itself an ASGI callable (granian --interface asgi module:app); the first call freezes the declarations.

on_startup and on_shutdown list functions taking the worker's ModuleContext (async def or def). Startup hooks run once per worker after the modules have started; shutdown hooks run before they are closed, and only after a startup that completed.

startup_url optionally reserves a public GET/HEAD endpoint that returns {"status": "ok"} after worker startup. It reports startup completion, not application, database, or event-loop health.

waivers names the owner's waiver file applied to the startup rules; it must exist. Without it, hinoki-rules.toml at the project root is used.

settings instance-attribute

settings = settings

middleware instance-attribute

middleware = check_middleware(middleware)

waiver_file instance-attribute

waiver_file: Path | None = (
    None if waivers is None else Path(waivers)
)

routes property

routes: tuple[Route, ...]

startup_url property

startup_url: str | None

The fixed startup-probe path, if one was configured.

bindings property

bindings: tuple[Binding, ...]

modules property

modules: tuple[Module, ...]

commands property

commands: tuple[Command, ...]

The app's explicitly registered management commands.

on_startup property

on_startup: tuple[Hook, ...]

Startup hooks, fixed when the application is constructed.

on_shutdown property

on_shutdown: tuple[Hook, ...]

Shutdown hooks, fixed when the application is constructed.

admin_settings

admin_settings() -> AdminSettings | None

The app's admin settings group, or None without built-in settings.

now

now(clock: Clock = utc_now) -> datetime

Return an aware datetime in this application's configured timezone.

settings_database

settings_database(
    declared: list[Module],
) -> DatabaseModule | None

The database module implied by a database: DatabaseSettings field in the settings, unless the application declares its own.

module_of

module_of(module: Module | type[Module]) -> Module

An instance as given, or a class built from this app's settings.

include

include(*items: Includable) -> None

Register decorated functions, API subclasses and objects that expose an api() (the admin). Lists and tuples of those are flattened, so a feature package can export one routes list, and Mount(prefix, ...) places a feature under a path chosen here.

All-or-nothing per call: on conflict the application is unchanged.

routes_of staticmethod

routes_of(item: object) -> list[Route]

The routes an item declares: an API class, a decorated function, or an object exposing api() (the admin).

inherited_parsers

inherited_parsers(route: Route) -> tuple[Parser, ...]

Parsers for an action without its own: the application's, unless an upload action needs multipart and they do not include it.

with_defaults

with_defaults(route: Route) -> Route

The route with this application's default parsers/renderers filled in where the action did not choose its own.

install

install(*modules: Module) -> None

Install modules and include their APIs.

The whole graph (names, requirements, cycles) is validated here, so a broken graph fails in the factory, not in a worker. Nothing opens.

lookup

lookup(
    method: str, path: str
) -> Found | MethodNotAllowed | None

Distinguish a match, a wrong method and an unknown path.

HEAD resolves through a matching GET route. Method-not-allowed results advertise HEAD whenever GET is available for the path.

resolve

resolve(
    method: str, path: str
) -> tuple[Route, dict[str, str]] | None

Find the action for a request line; None if unknown or the method is not allowed (use lookup to tell them apart).

openapi

openapi() -> dict[str, Any]

The OpenAPI 3.1 document for the registered routes.

asgi

asgi() -> ASGIAdapter

The ASGI adapter for this worker; builds and validates bindings once.

enforce

enforce() -> None

Fail with every startup-rule violation when rules are enforced. With enforce_rules=False the diagnostics are only logged. The owner's waivers apply as in hinoki check: waivers= when given, else the project's hinoki-rules.toml. An invalid waiver file always fails.

error_handler

error_handler(kind: type[Exception]) -> ErrorRegistrar

Decorator: answer kind with a function of the exception that returns the APIError to send. It returns the function unchanged.

@app.error_handler(stripe.CardError)
def card_error(error: stripe.CardError) -> errors.APIError:
    return errors.APIError(error.user_message, status=402)

Errors that already are APIError subclasses need no handler.

hinoki.api.API

Base class for a resource: several methods, standard or custom.

class Posts(API, path='/posts'). Instances hold no per-request state; methods declared with @http.get/@http.post/... become actions.

prefix class-attribute

prefix: str = ''

routes classmethod

routes() -> list[Route]

Routes of this class with the prefix applied, in definition order.

Members are resolved by name, most derived class first, so an override without a decorator removes the inherited route.

apply_replacements classmethod

apply_replacements(found: list[Route]) -> list[Route]

Drop the routes that another route names in replaces=.

declared_route classmethod

declared_route(name: str, member: object) -> Route | None

mount classmethod

mount(route: Route) -> Route

hinoki.routing.RouteGroup

RouteGroup(
    prefix: str = "",
    *,
    access: Access | None = None,
    atomic: bool = False,
    errors: Sequence[type[APIError]] = (),
)

A function-based route group with a shared path prefix and defaults.

Decorated functions belong to this group and the group can be included once in a Hinoki application. Use API for class-based resources.

tasks = RouteGroup("/tasks", access=member_only, atomic=True,
                   errors=(NotFound,))

@tasks.get("/")                      # GET /tasks
async def listing(...): ...

@tasks.post("/", status=201)         # POST /tasks, atomic=True
async def create(...): ...

@tasks.get("/health", access=None)   # public on purpose, overriding the group

prefix is prepended to every path ("/" means the prefix itself), access is the default policy (pass access=None on an action to make it public), atomic=True makes POST/PUT/PATCH/DELETE transactional unless the action says atomic=False, and errors are added to each action's own. The result is an ordinary action: rules, OpenAPI and the MCP see no difference.

prefix instance-attribute

prefix = prefix

access instance-attribute

access = access

atomic instance-attribute

atomic = atomic

errors instance-attribute

errors = tuple(errors)

handlers property

handlers: tuple[Callable[..., object], ...]

The decorated handlers in declaration order.

declare

declare(
    method: str, path: str, options: dict[str, Any]
) -> RouteDeclaration

get

get(path: str, **options: Any) -> _GroupRouteDeclaration

post

post(path: str, **options: Any) -> _GroupRouteDeclaration

put

put(path: str, **options: Any) -> _GroupRouteDeclaration

patch

patch(path: str, **options: Any) -> _GroupRouteDeclaration

delete

delete(path: str, **options: Any) -> _GroupRouteDeclaration

query

query(path: str, **options: Any) -> _GroupRouteDeclaration

hinoki.routing.Includable

Includable = (
    type[API]
    | Callable[..., object]
    | RouteGroup
    | Mount
    | ExposesRoutes
    | Sequence[Includable]
)

What Hinoki(include=[...]) and app.include(...) accept: an API class, a decorated function, a RouteGroup, a Mount, an object with api() (the admin) or a list or tuple of those.

hinoki.routing.Mount

Mount(prefix: str, *items: object)

Places routes under a path prefix chosen where the application is declared.

Hinoki(include=[
    health,
    Mount("/tasks", tasks.routes),
    Mount("/billing", billing.routes),
])

The feature keeps paths relative to itself (/ and /{id}) and the root declaration shows where each feature lives. Items are anything include accepts, including lists and other mounts; prefixes join outside in.

prefix instance-attribute

prefix = prefix

items instance-attribute

items = items

hinoki.routing.Route dataclass

Route(
    method: str,
    path: str,
    handler: Callable[..., object],
    status: int,
    access: Access | None,
    atomic: bool,
    owner: type | None = None,
    pagination: PageNumberPagination | None = None,
    replaces: str = "",
    parsers: tuple[Parser, ...] = DEFAULT_PARSERS,
    renderers: tuple[Renderer, ...] = DEFAULT_RENDERERS,
    errors: tuple[type[APIError], ...] = (),
    validate_response: bool = True,
    rate_limit: RateLimitPolicy | None = None,
    middleware: tuple[Middleware, ...] = (),
)

Declared contract of one action, before it is bound to an application.

method instance-attribute

method: str

path instance-attribute

path: str

handler instance-attribute

handler: Callable[..., object]

status instance-attribute

status: int

access instance-attribute

access: Access | None

atomic instance-attribute

atomic: bool

owner class-attribute instance-attribute

owner: type | None = None

pagination class-attribute instance-attribute

pagination: PageNumberPagination | None = None

replaces class-attribute instance-attribute

replaces: str = ''

parsers class-attribute instance-attribute

parsers: tuple[Parser, ...] = DEFAULT_PARSERS

renderers class-attribute instance-attribute

renderers: tuple[Renderer, ...] = DEFAULT_RENDERERS

errors class-attribute instance-attribute

errors: tuple[type[APIError], ...] = ()

validate_response class-attribute instance-attribute

validate_response: bool = True

rate_limit class-attribute instance-attribute

rate_limit: RateLimitPolicy | None = None

middleware class-attribute instance-attribute

middleware: tuple[Middleware, ...] = ()

is_async property

is_async: bool

name property

name: str

hinoki.project.manifest_routes

manifest_routes(
    start: Path | None = None,
) -> list[Includable]

The routes hinoki.toml declares: the project's, then each app's at its prefix, for Hinoki(include=manifest_routes()).

The manifest is found from start, by default the directory of the calling file (the working directory when the caller has no file), upwards. Outside a project this raises ProjectError.

For model-backed route generation, see Generate CRUD routes and the CRUD API reference.

HTTP method decorators

Import the namespace and decorate actions: from hinoki import http, then @http.get(...). The names are not available at the top level of hinoki.

hinoki.http.get

get(
    path: str,
    *,
    status: int = 200,
    access: Access | None = None,
    atomic: bool = False,
    pagination: PageNumberPagination | None = None,
    replaces: str = "",
    parsers: Sequence[Parser] | None = None,
    renderers: Sequence[Renderer] | None = None,
    errors: Sequence[type[APIError]] = (),
    validate_response: bool = True,
    rate_limit: RateLimitPolicy | None = None,
    middleware: Sequence[Middleware] = (),
) -> RouteDeclaration

Declare a GET action. errors lists the APIError subclasses the action may raise; each carries its own status and code, which OpenAPI and the MCP tool description then show.

hinoki.http.post

post(
    path: str,
    *,
    status: int = 200,
    access: Access | None = None,
    atomic: bool = False,
    pagination: PageNumberPagination | None = None,
    replaces: str = "",
    parsers: Sequence[Parser] | None = None,
    renderers: Sequence[Renderer] | None = None,
    errors: Sequence[type[APIError]] = (),
    validate_response: bool = True,
    rate_limit: RateLimitPolicy | None = None,
    middleware: Sequence[Middleware] = (),
) -> RouteDeclaration

Declare a POST action. errors lists the APIError subclasses the action may raise; each carries its own status and code, which OpenAPI and the MCP tool description then show.

hinoki.http.put

put(
    path: str,
    *,
    status: int = 200,
    access: Access | None = None,
    atomic: bool = False,
    pagination: PageNumberPagination | None = None,
    replaces: str = "",
    parsers: Sequence[Parser] | None = None,
    renderers: Sequence[Renderer] | None = None,
    errors: Sequence[type[APIError]] = (),
    validate_response: bool = True,
    rate_limit: RateLimitPolicy | None = None,
    middleware: Sequence[Middleware] = (),
) -> RouteDeclaration

Declare a PUT action. errors lists the APIError subclasses the action may raise; each carries its own status and code, which OpenAPI and the MCP tool description then show.

hinoki.http.patch

patch(
    path: str,
    *,
    status: int = 200,
    access: Access | None = None,
    atomic: bool = False,
    pagination: PageNumberPagination | None = None,
    replaces: str = "",
    parsers: Sequence[Parser] | None = None,
    renderers: Sequence[Renderer] | None = None,
    errors: Sequence[type[APIError]] = (),
    validate_response: bool = True,
    rate_limit: RateLimitPolicy | None = None,
    middleware: Sequence[Middleware] = (),
) -> RouteDeclaration

Declare a PATCH action. errors lists the APIError subclasses the action may raise; each carries its own status and code, which OpenAPI and the MCP tool description then show.

hinoki.http.delete

delete(
    path: str,
    *,
    status: int = 200,
    access: Access | None = None,
    atomic: bool = False,
    pagination: PageNumberPagination | None = None,
    replaces: str = "",
    parsers: Sequence[Parser] | None = None,
    renderers: Sequence[Renderer] | None = None,
    errors: Sequence[type[APIError]] = (),
    validate_response: bool = True,
    rate_limit: RateLimitPolicy | None = None,
    middleware: Sequence[Middleware] = (),
) -> RouteDeclaration

Declare a DELETE action. errors lists the APIError subclasses the action may raise; each carries its own status and code, which OpenAPI and the MCP tool description then show.

hinoki.http.query

query(
    path: str,
    *,
    status: int = 200,
    access: Access | None = None,
    atomic: bool = False,
    pagination: PageNumberPagination | None = None,
    replaces: str = "",
    parsers: Sequence[Parser] | None = None,
    renderers: Sequence[Renderer] | None = None,
    errors: Sequence[type[APIError]] = (),
    validate_response: bool = True,
    rate_limit: RateLimitPolicy | None = None,
    middleware: Sequence[Middleware] = (),
) -> RouteDeclaration

Declare a QUERY action: a safe, idempotent request that carries a body (a search too large or too structured for a query string). It binds its body like POST and is never wrapped in a transaction unless asked. errors lists the APIError subclasses the action may raise; each carries its own status and code, which OpenAPI and the MCP tool description then show.

Request, response and errors

The types are available from hinoki.http, from hinoki, or from their modules hinoki.http.request and hinoki.http.response.

hinoki.http.request.Request

Request(
    *,
    method: str,
    path: str,
    scheme: str,
    host: str,
    client: tuple[str, int] | None,
    headers: Mapping[str, str],
    query: Mapping[str, list[str]],
    body: bytes,
    path_params: Mapping[str, str],
    user: Any,
    request_id: str,
    parsers: Sequence[Parser] = DEFAULT_PARSERS,
)

One HTTP request. Never mutate it; it is shared with the whole call.

method instance-attribute

method = method

path instance-attribute

path = path

scheme instance-attribute

scheme = scheme

host instance-attribute

host = host

client instance-attribute

client = client

headers instance-attribute

headers = (
    headers
    if isinstance(headers, Headers)
    else Headers(headers)
)

GET instance-attribute

GET = QueryDict(query)

COOKIES instance-attribute

COOKIES = core.parse_cookie_header(
    self.headers.get("cookie", "")
)

body instance-attribute

body = body

path_params instance-attribute

path_params = dict(path_params)

user instance-attribute

user = user

request_id instance-attribute

request_id = request_id

parsers instance-attribute

parsers = tuple(parsers)

cached instance-attribute

cached: Parsed | None = None

content_type property

content_type: str

Media type without parameters, lower-case ("" when absent).

data property

data: object

The parsed body (JSON value, or form fields as text).

POST property

POST: QueryDict

Form fields; empty when the body is not a form.

FILES property

FILES: MultiDict[UploadedFile]

Uploaded files of a multipart body; empty otherwise.

parsed

parsed() -> Parsed

The body through the parser for its content type, once; raises InvalidBody (415 for an unlisted type, 400 for a malformed body).

accepts_form

accepts_form() -> bool

hinoki.http.response.Response

Response(
    status: int = 200,
    body: bytes | str = b"",
    headers: Headers = (),
    content_type: str | None = None,
)

Status, headers and body chosen by the handler.

status instance-attribute

status = status

body instance-attribute

body = raw

headers instance-attribute

headers = [
    encode_header(name, value) for name, value in items
]

raw classmethod

raw(
    status: int,
    body: bytes,
    headers: list[tuple[bytes, bytes]],
) -> Response

A response from parts the runtime already holds, without checking them again.

with_header

with_header(name: str, value: str) -> Response

A copy with one more header.

set_cookie(
    name: str,
    value: str,
    *,
    path: str = "/",
    max_age: int | None = None,
    http_only: bool = True,
    secure: bool = True,
    same_site: str = "Lax",
) -> tuple[str, str]

A ("set-cookie", ...) header for Response(headers=[...]). The name must be a token and the value cookie-safe (no space, quote, comma, semicolon or backslash); encode richer data yourself.

hinoki.access.Access dataclass

Access(
    auth: BaseAuth[Any], permissions: Iterable[str] = ()
)

Which provider authenticates an action and which permissions it requires.

Access(auth=tokens, permissions=["posts:write"]).

Declaring an Access does not protect anything by itself: only actions that name it are protected. Enforcement belongs to the request pipeline.

auth instance-attribute

auth: BaseAuth[Any]

permissions class-attribute instance-attribute

permissions: frozenset[str] = field(
    default_factory=frozenset
)

hinoki.errors.APIError

APIError(
    message: str | None = None,
    *,
    code: str | None = None,
    status: int | None = None,
    details: list[dict[str, Any]] | None = None,
    headers: dict[str, str] | None = None,
)

Bases: Exception

An error with a public HTTP representation.

Subclasses set status, code and message; an instance may override them, which is how a handler answers with a status of its own: APIError("Card declined", status=402, code="card_declined"). details is public data, never internal state.

hinoki.errors.BadRequest

BadRequest(
    message: str | None = None,
    *,
    code: str | None = None,
    status: int | None = None,
    details: list[dict[str, Any]] | None = None,
    headers: dict[str, str] | None = None,
)

Bases: APIError

hinoki.errors.Unauthorized

Unauthorized(
    message: str | None = None,
    *,
    code: str | None = None,
    status: int | None = None,
    details: list[dict[str, Any]] | None = None,
    headers: dict[str, str] | None = None,
)

Bases: APIError

hinoki.errors.Forbidden

Forbidden(
    message: str | None = None,
    *,
    code: str | None = None,
    status: int | None = None,
    details: list[dict[str, Any]] | None = None,
    headers: dict[str, str] | None = None,
)

Bases: APIError

hinoki.errors.NotFound

NotFound(
    message: str | None = None,
    *,
    code: str | None = None,
    status: int | None = None,
    details: list[dict[str, Any]] | None = None,
    headers: dict[str, str] | None = None,
)

Bases: APIError

hinoki.errors.Conflict

Conflict(
    message: str | None = None,
    *,
    code: str | None = None,
    status: int | None = None,
    details: list[dict[str, Any]] | None = None,
    headers: dict[str, str] | None = None,
)

Bases: APIError

hinoki.errors.TooManyRequests

TooManyRequests(
    retry_after: int,
    message: str | None = None,
    *,
    code: str | None = None,
)

Bases: APIError

The one error a rate_limit policy may raise to refuse a request.

retry_after is a whole number of seconds from 1 to 86,400, sent as Retry-After; anything else is refused when the error is created.

hinoki.errors.UniqueConflict

UniqueConflict(
    message: str | None = None,
    *,
    code: str | None = None,
    status: int | None = None,
    details: list[dict[str, Any]] | None = None,
    headers: dict[str, str] | None = None,
)

Bases: Conflict

A unique value is already in use: the answer to a UniqueViolation.

hinoki.errors.ObjectNotFound

Bases: ModelError

A query that must return one row returned none. Each model has its own subclass as Model.NotFound; HTTP maps it to 404.

hinoki.errors.ErrorRegistry

ErrorRegistry()

Maps exception classes to handlers; the most specific class wins.

is_builtin

is_builtin(exc: Exception) -> bool

Whether only synchronous built-in translations can answer exc: no application handler matches it.

translate_builtin

translate_builtin(exc: Exception) -> APIError | None

translate for an exception is_builtin accepted, without a coroutine.

translate async

translate(exc: Exception) -> APIError | None

The public error for exc, or None if nothing handles it.

A handler that fails or returns something else is treated as unhandled.

Rate limits

hinoki.ratelimit.RateLimitPolicy

Bases: Protocol

Anything with a check method, def or async def.

A sync check runs on the bounded executor and must use sync clients with finite timeouts; an async one runs on the event loop.

hinoki.ratelimit.RateLimitContext dataclass

RateLimitContext(
    method: str,
    route: str,
    client: str | None,
    caller: Caller[Any] | None,
    lookup: Callable[[type[Any]], Any],
)

What a policy may decide from: no headers, credentials, body or query.

resource

resource(kind: type[T]) -> T

The worker-owned resource of this type that a module provided (for example a Redis client or the Database); LookupError if none.