GuidesData
Schemas¶
A Schema describes data that crosses the API boundary and validates it
strictly. Models describe tables; a column reaches a client only when a
Schema names it.
# notes/apps/billing/schemas.py
from datetime import datetime
from typing import Annotated
from uuid import UUID
from hinoki import UNSET, Field, Schema, Unset
class InvoiceIn(Schema):
reference: Annotated[str, Field(min_length=1, max_length=40)]
class InvoicePatch(Schema):
reference: Annotated[str, Field(min_length=1, max_length=40)] | Unset = UNSET
paid: bool | Unset = UNSET
class InvoiceOut(Schema):
id: UUID
reference: str
paid: bool
created_at: datetime
Validation, construction and JSON serialization run in Rust.
Validate input¶
data = InvoiceIn.validate({"reference": "INV-1"})
- No coercion.
"1"is not1. Text sources are the explicit exception:Schema.validate_text(),Form[...],Query[...]andXML[...]first convert text to theint,floatandboolthe fields declare. - Unknown keys are refused unless the class ignores them.
- Every problem is reported with its path, up to 50, in
errors.ValidationError.details; a request answers 422.
Constraints, normalization and custom checks are in validate input. Supported field types are in scalar field types and collections and unions.
Partial updates¶
Declare a field X | Unset = UNSET. A field the client did not send stays
UNSET and is left out of dump() and to_dict(), so
await invoice.aupdate_from(patch) writes only what was sent.
Convert to and from rows¶
# inside an async operation
invoice = await Invoice.acreate(data, customer_id=customer.id)
await invoice.aupdate_from(patch)
out = InvoiceOut.from_model(invoice)
outs = InvoiceOut.from_models(rows)
- Server keywords win over client values, and a
Schemanever carries the primary key. from_model(row, **extra)reads the expected attributes; relations must already be loaded.from_models(rows)converts a synchronous iterable to a list. See schemas from models.to_dict()returns Python values (UUID and datetime stay objects);dump()returns the JSON-compatible form. Both skipUNSET.
Construct, change and project¶
Schema(...) takes Python values (UUID, aware datetime, nested Schema
instances) and validates them immediately. Schema.validate(data) is the
wire path: JSON-compatible input, aliases resolved, errors with wire names.
from_model() validates too, but accepts the naive datetimes some drivers
return.
An instance is frozen. replace(**changes) returns a validated copy; an
unknown name raises TypeError:
card = InvoiceOut.validate(payload)
paid = card.replace(paid=True)
dump() projects to JSON-compatible data:
out.dump(exclude_unset=True)
out.dump(include={"id", "reference"})
out.dump(by_alias=False)
includeandexcludetake Python field names, top level only; exclusion wins.exclude_unset=Trueomits fields filled by defaults that the caller did not supply; explicit"",None,0orFalseare kept. A custom__init__makes it raiseTypeError.- With no options
dump()honours customdump()overrides; recursive options refuse a custom-dumped nested value. An override using the new options must accept the same keyword-only signature. - Filtering a dump is not authorization and does not change the OpenAPI
document: declare a
Schemawith only the fields the caller may see. dumpandreplaceare reserved method names; a field with either name raisesRegistrationError.
Wire aliases¶
# notes/apps/billing/schemas.py (continued)
class CustomerOut(Schema):
display_name: Annotated[str, Field(alias="displayName")]
person = CustomerOut.validate({"displayName": "Aki"})
assert person.dump() == {"displayName": "Aki"}
assert person.to_dict() == {"display_name": "Aki"}
The alias is the only accepted input key; sending both names is an error.
dump(), validation errors and the OpenAPI document use wire names; a check's
default path is translated, an explicit Invalid(path=...) is already a wire
path. name: str = Field(alias="...") works too. Aliases are unique and cannot
contain ., [ or ]. Models take no aliases.
Document a field¶
class TagOut(Schema):
name: Annotated[
str, Field(max_length=40, description="Tag label.", examples=("priority",))
]
legacy: Annotated[str | None, Field(deprecated=True)] = None
description, examples and deprecated appear in the OpenAPI document next
to the property and change nothing about validation.
Computed fields¶
from hinoki import computed_field
class CustomerCard(Schema):
first: str
last: str
@computed_field(alias="displayName", description="First and last name")
def full_name(self) -> str:
return f"{self.first} {self.last}"
CustomerCard(first="Ada", last="Lovelace").dump() includes
"displayName": "Ada Lovelace". Computed values are output only: they follow
the declared fields in dump() and responses (both lanes), are readOnly in
OpenAPI, are left out of to_dict(), and a client that sends one gets an
unknown-field error. The method takes only self and needs a return
annotation; a name clash with a field is a RegistrationError.
computed_fields() returns them; subclasses inherit them.
Class configuration¶
from hinoki import SchemaConfig, SchemaExtra
class VendorEvent(Schema, config=SchemaConfig(extra=SchemaExtra.IGNORE)):
event_id: str
revision: int
SchemaExtra.IGNORE discards unknown keys in decoded input and request bodies;
declared fields stay strict, and ignored values are never stored or dumped.
Constructor keywords and from_model(..., **extra) keep their strict
signatures; each nested Schema uses its own configuration. The OpenAPI
document marks the schema additionalProperties: true.
Generic schemas¶
from hinoki import http
class Envelope[T](Schema):
data: T
count: int = 0
@http.get("/me")
async def me() -> Envelope[CustomerOut]:
return Envelope[CustomerOut](data=CustomerOut(display_name="Ada"))
Envelope[CustomerOut] is a cached Schema subclass with its own OpenAPI
component (Envelope_CustomerOut_). The bare Envelope cannot validate or be
a field; self-referencing generics and generic subclasses of generic schemas
raise RegistrationError.
See also¶
- Validate input
- Scalar field types
- Collections and unions
- Schemas from models
- Glossary: what "schema" means in these docs