pre-alpha

5.2 · Reference

Core API: application, routing and HTTP

hinoki.app.Hinoki

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.

_startup_url instance-attribute

_startup_url = check_startup_url(startup_url)

_timezone instance-attribute

_timezone = ZoneInfo(built_in.timezone) if built_in else UTC

settings instance-attribute

settings = settings

_automatic_database instance-attribute

_automatic_database: DatabaseModule | None = automatic

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.

__init__

__init__(
    *,
    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,
    parsers: Sequence[Parser] | None = None,
    renderers: Sequence[Renderer] | None = None,
) -> None

_project_routes staticmethod

_project_routes(caller: FrameType) -> list[Includable]

Without include=, the routes hinoki.toml declares, when the manifest names the module that builds this application.

admin_settings

admin_settings() -> AdminSettings | None

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

_configure_runtime

_configure_runtime(
    built_in: AppSettings | None,
    runtime: RuntimeConfig | None,
) -> None

_configure_docs

_configure_docs(
    docs: DocsSettings,
    title: str | None,
    version: str | None,
    openapi_url: str | Unset | None,
    docs_url: str | Unset | None,
    redoc_url: str | Unset | None,
) -> None

_configure_policy

_configure_policy(
    built_in: AppSettings | None,
    rules: RuleSet | None,
    enforce_rules: bool,
    parsers: Sequence[Parser] | None,
    renderers: Sequence[Renderer] | None,
) -> None

_initialize_registries

_initialize_registries(
    commands: Sequence[Command | type[Command]],
    on_startup: Sequence[Hook],
    on_shutdown: Sequence[Hook],
) -> None

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.

_collect_routes

_collect_routes(
    items: tuple[object, ...],
) -> tuple[list[Route], list[RouteGroup]]

_stage_router

_stage_router(pending: list[Route]) -> Router

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.

__call__ async

__call__(
    scope: MutableMapping[str, Any], receive: Any, send: Any
) -> None

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.

_check_mutable

_check_mutable() -> None

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 = ''

__init_subclass__

__init_subclass__(
    path: str | None = None, **kwargs: object
) -> None

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

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 instance-attribute

_handlers: list[Callable[..., object]] = []

_included instance-attribute

_included = False

handlers property

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

The decorated handlers in declaration order.

__init__

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

_include

_include() -> None

_decorate

_decorate(
    declaration: RouteDeclaration, fn: Callable[P, R]
) -> Callable[P, R]

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

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

__init__

__init__(prefix: str, *items: object) -> None

hinoki.routing.Route dataclass

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

is_async property

is_async: bool

name property

name: str

__init__

__init__(
    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,
) -> None

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,
) -> 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,
) -> 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,
) -> 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,
) -> 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,
) -> 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,
) -> 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

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

__slots__ class-attribute instance-attribute

__slots__ = (
    "COOKIES",
    "GET",
    "body",
    "cached",
    "client",
    "headers",
    "host",
    "method",
    "parsers",
    "path",
    "path_params",
    "request_id",
    "scheme",
    "user",
)

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.

__init__

__init__(
    *,
    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,
) -> None

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

Status, headers and body chosen by the handler.

__slots__ class-attribute instance-attribute

__slots__ = ('body', 'headers', 'status')

status instance-attribute

status = status

body instance-attribute

body = raw

headers instance-attribute

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

__init__

__init__(
    status: int = 200,
    body: bytes | str = b"",
    headers: Headers = (),
    content_type: str | None = None,
) -> None
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

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
)

__init__

__init__(
    auth: BaseAuth[Any], permissions: Iterable[str] = ()
) -> None

hinoki.errors.APIError

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

Bases: APIError

hinoki.errors.Unauthorized

Bases: APIError

hinoki.errors.Forbidden

Bases: APIError

hinoki.errors.NotFound

Bases: APIError

hinoki.errors.Conflict

Bases: APIError