Reference
Core API: application, routing and HTTP¶
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.
waiver_file
instance-attribute
¶
waiver_file: Path | None = (
None if waivers is None else Path(waivers)
)
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).
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.
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 ¶
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.
handlers
property
¶
handlers: tuple[Callable[..., object], ...]
The decorated handlers in declaration order.
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.
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.
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.
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.
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 ¶
Response(
status: int = 200,
body: bytes | str = b"",
headers: Headers = (),
content_type: str | None = None,
)
Status, headers and body chosen by the handler.
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.
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
¶
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.
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,
)
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.