Schemas API#
fastapi_restly.schemas implements the Pydantic schema layer: schema base
classes, the ReadOnly and WriteOnly field markers, the UTCDatetime
field type and the in_utc() function for times in UTC, relationship
reference types, and schema generation from SQLAlchemy models.
See also
Relationships covers MustExist checked foreign
keys and the JSON format of IDRef / IDSchema relationship fields.
Schemas & Validation describes schema bases, field markers, and
aliases in prose.
- fastapi_restly.schemas.ReadOnly#
Marks a field as excluded from generated create and update schemas. The field remains available in responses.
- fastapi_restly.schemas.WriteOnly#
Marks a field as input-only by setting Pydantic’s serialization exclusion. See Store a Pydantic model in a JSON column for restrictions inside JSON documents.
- class fastapi_restly.schemas.BaseSchema#
Bases:
BaseModelThe base of a Restly schema: a Pydantic model with
from_attributes=True, so it can read a SQLAlchemy object by its attributes.It also has
ser_json_inf_nan="strings", so a response writes a NaN or an infinity as the text"NaN","Infinity"or"-Infinity". JSON has no number for these values, and Pydantic’s default writesnull, which loses the value. Afloatfield reads the text back. This needs FastAPI 0.130 or later, with its default response class. A Pydantic model of your own in a field follows its own setting.It also checks where the
ReadOnly,WriteOnlyandMustExistmarkers are placed. A marker deep inside the type of a field, such asReadOnly[int] | None, would have no effect. So the class raisesRestlyConfigurationErrorwhen Python defines it. Put the marker around the whole type:ReadOnly[int | None].
- class fastapi_restly.schemas.MustExist#
Existence-checked scalar foreign key:
MustExist[int, Post].The first argument is the type of the id, the second the model of the row. The field stays the id everywhere (JSON, column,
data.<field>). On write, Restly checks that the row exists (404 on a miss), among the rows of the model’sdefault_scope.
- class fastapi_restly.schemas.IDRef(value: Any = ..., *, id: ReadOnly[Any])#
Bases:
IDSchemaFlat-id reference to a related row, for a RELATIONSHIP-named field.
Use
IDRef[T]when the field is named after a relationship (author: IDRef[User],products: list[IDRef[Product]]), not after a*_idcolumn. The JSON value is the raw id (5); input also accepts{"id": N}. Restly resolves the id to the related ORM object, sodata.authoris anIDRefwrapper (read.id), not a plain scalar.For a scalar foreign-key COLUMN (
author_id,task_id) usefr.MustExist[int, T]instead – it keeps the field a plain checked id (data.author_id == 1), rather than making a*_idfield an object wrapper. For a nested{"id": N}value on a relationship, useIDSchema[T].author: IDRef[User] # to-one relationship, flat id products: list[IDRef[Product]] # serializes as [1, 2, 3]
Resolution applies the referenced model’s
default_scope: a reference to a row the scope hides raisesNotFound, as a missing row does. A model without adefault_scoperesolves by primary key alone. A session rule, such as a tenant rule added withwith_loader_criteria, reaches the lookup too, except for an object that is already in the session. A rule that is neither goes inauthorize, wheredata.<field>.idis the requested id. See “Which rows can a reference reach?” on the Relationships guide page.
- class fastapi_restly.schemas.IDSchema(*, id: ReadOnly[Any])#
Bases:
BaseSchemaThe base of a view’s main schema, which adds a read-only
id. As the type of a field,IDSchema[Model]is a reference to a related row.As a BASE CLASS (
class UserSchema(IDSchema): ...) it adds the resource’s own read-onlyid– the common use.As a FIELD TYPE on a RELATIONSHIP-named field (
author: IDSchema[User]) the JSON value is{"id": N}(JSON-API / React-Admin); Restly resolves the id to the related ORM object, sodata.authoris a wrapper (read.id). UseIDRef[User]for a flat id (5) instead.
For a scalar foreign-key COLUMN (
author_id), usefr.MustExist[int, T]rather thanIDSchema/IDRef: it keeps the field a plain checked id instead of turning a*_idfield into an object wrapper.
- class fastapi_restly.schemas.TimestampsSchemaMixin(*, created_at: ReadOnly[UTCDatetime], updated_at: ReadOnly[UTCDatetime])#
Bases:
BaseModelSchema mixin that adds two fields:
created_atandupdated_at.It is the schema side of
TimestampsMixin. Both fields areReadOnly[UTCDatetime], so the responses contain them, in UTC, and the create and update bodies that Restly generates leave them out. When a client sends them in a body, Restly ignores them. The fields have no default, so the object that a response reads must have both attributes.The mixin adds nothing else, so combine it with
IDSchemaorBaseSchema. Put it before the base class, so thatidstays the first field in the responses:class UserSchema(fr.TimestampsSchemaMixin, fr.IDSchema): name: str
A schema that Restly generates for a model with
created_atandupdated_atcolumns uses this mixin.- created_at: ReadOnly[UTCDatetime]#
When the row was created. It is
ReadOnly: the responses show it, and the create and update bodies that Restly generates leave it out.
- updated_at: ReadOnly[UTCDatetime]#
When the row last changed. It is
ReadOnly: the responses show it, and the create and update bodies that Restly generates leave it out.
- fastapi_restly.schemas.UTCDatetime#
A
datetimefield in UTC. It reads a time without an offset as UTC, and changes a time with an offset to the same time in UTC. So the object of the schema always has the time in UTC, and JSON shows it withZ, such as2024-01-01T09:30:00Z. See Keep times in UTC.alias of
Annotated[datetime,AfterValidator(func=in_utc)]
- fastapi_restly.schemas.derive_schema(model: type[Any], *, name: str | None = None) type[BaseSchema]#
Generate a Pydantic schema from a SQLAlchemy model.
This is the same schema that a view generates when it has no
schema: one field per column, and no relationship fields. A foreign key column, such asauthor_id, is an ordinary field unless it hasinit=False. These fields are markedReadOnly:id,created_atandupdated_at, acolumn_propertyover a SQL expression, and a column that the constructor does not take (init=False).A time column gets a field of type
UTCDatetime, which holds the time in UTC.A field allows
Noneonly when its column is nullable. The create schema follows the constructor: the client may leave out a field when its column is nullable, or when the constructor does not require it and the model then still gives the column a value. That value comes from the column (insert_default,server_default) or from the constructor (adefaultother thanNone, or adefault_factory). Such a field has the defaultNone, which Pydantic does not validate. Restly does not pass it to the constructor, so the model’s default applies.- Parameters:
model – The SQLAlchemy model class.
name – Name for the generated schema class. Defaults to the model name followed by
Schema, as inUserSchema.
- Returns:
A Pydantic schema class.
- fastapi_restly.schemas.derive_create_schema(schema: type[_SchemaT], model: type[Any]) type[_SchemaT]#
Build the create schema from a view’s main schema: the schema without its
ReadOnlyfields, named<Resource>Create.A view without its own
create_schemagets this class. The class is a subclass ofschema. Each call with the same arguments returns the same class, so a custom route can name the class that the view uses:UserCreate = fr.schemas.derive_create_schema(UserSchema, User)
- Parameters:
schema – The main schema.
model – The view’s model. The class also leaves out a primary key that the server generates, as a view does.
- Returns:
The create schema.
- Raises:
RestlyConfigurationError –
schemais a SQLModel table class.
- fastapi_restly.schemas.derive_list_response_schema(response_schema: type[BaseModel], *, pagination: Pagination | None = NumberedPagination()) type[BaseModel]#
Build the list response schema of a view: the envelope of its pagination, filled with its response schema, named
<Resource>ListResponse.This is what a view’s
list_response_schemais unless it sets another class. On a react-admin view it is a plain list. A route on a router, or outside the view, can name it, so OpenAPI shows one type for both routes:UserResponse = fr.schemas.derive_response_schema(UserSchema) UserListResponse = fr.schemas.derive_list_response_schema( UserResponse, pagination=AppView.pagination ) class UserView(AppView): schema = UserSchema @fr.get("/inactive", response_model=UserListResponse) async def inactive(self, list_params): ...
Each call with the same response schema and envelope returns the same class. Only the envelope of the pagination matters: two paginations with the same envelope give the same class.
- Parameters:
response_schema – The view’s response schema, such as the one from
derive_response_schema().pagination – The view’s pagination.
Noneis a view without pagination, as on the view. The default is the default pagination.
- Returns:
The list response schema.
- fastapi_restly.schemas.derive_response_schema(schema: type[_SchemaT]) type[_SchemaT]#
Build the response schema from a view’s main schema: the schema without its
WriteOnlyfields, named<Resource>Response.A view without its own
response_schemagets this class. Restly builds it also when the schema has noWriteOnlyfields, so OpenAPI showsUserResponseand not the main schema.The class is a subclass of
schema. Each call with the same schema returns the same class, so a custom route can name the class that the view uses:UserResponse = fr.schemas.derive_response_schema(UserSchema) class UserView(fr.AsyncRestView): schema = UserSchema @fr.get("/me", response_model=UserResponse) async def me(self): ...
- Parameters:
schema – The main schema.
- Returns:
The response schema.
- Raises:
RestlyConfigurationError –
schemais a SQLModel table class.
- fastapi_restly.schemas.derive_update_schema(schema: type[_SchemaT], model: type[Any]) type[_SchemaT]#
Build the update schema from a view’s main schema: the schema without its
ReadOnlyfields, with each other field optional, named<Resource>Update.A view without its own
update_schemagets this class. The class is a subclass ofschema. Each call with the same arguments returns the same class, so a custom route can name the class that the view uses.schemacan be a class of your own, such as the create schema of a view that setscreate_schema, so thatPATCHfollows that body:class UserCreate(fr.BaseSchema): name: str class UserView(fr.AsyncRestView): create_schema = UserCreate update_schema = fr.schemas.derive_update_schema(UserCreate, User)
- Parameters:
schema – The main schema, or another class to start from.
model – The view’s model. The class also leaves out a primary key that the server generates, as a view does.
- Returns:
The update schema.
- Raises:
RestlyConfigurationError –
schemais a SQLModel table class.
- fastapi_restly.schemas.in_utc(value: datetime) datetime#
valueas the same time in UTC. A time without an offset is UTC.This is the rule of
fr.UTCDatetime, as a function. Give a time from the database to it before you compare it with a time from a schema, as indata.ends_at > fr.in_utc(obj.starts_at). A time from a column without a time zone has no offset, and on SQLite no time has one. See Keep times in UTC.- Raises:
ValueError – the time in UTC is not between the years 1 and 9999.