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.
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]]
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).
enforce ¶
enforce() -> None
Fail with every startup-rule violation when rules are enforced. With
enforce_rules=False the diagnostics are only logged.
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.
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=.
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.
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.
hinoki.routing.Route
dataclass
¶
Declared contract of one action, before it is bound to an application.
__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",
)
headers
instance-attribute
¶
headers = (
headers
if isinstance(headers, Headers)
else Headers(headers)
)
content_type
property
¶
content_type: str
Media type without parameters, lower-case ("" when absent).
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).
hinoki.http.response.Response ¶
Status, headers and body chosen by the handler.
__init__ ¶
__init__(
status: int = 200,
body: bytes | str = b"",
headers: Headers = (),
content_type: str | None = None,
) -> None
hinoki.http.response.set_cookie ¶
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.
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.