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: BaseModel

The 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 writes null, which loses the value. A float field 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, WriteOnly and MustExist markers are placed. A marker deep inside the type of a field, such as ReadOnly[int] | None, would have no effect. So the class raises RestlyConfigurationError when 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’s default_scope.

class fastapi_restly.schemas.IDRef(value: Any = ..., *, id: ReadOnly[Any])#

Bases: IDSchema

Flat-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 *_id column. The JSON value is the raw id (5); input also accepts {"id": N}. Restly resolves the id to the related ORM object, so data.author is an IDRef wrapper (read .id), not a plain scalar.

For a scalar foreign-key COLUMN (author_id, task_id) use fr.MustExist[int, T] instead – it keeps the field a plain checked id (data.author_id == 1), rather than making a *_id field an object wrapper. For a nested {"id": N} value on a relationship, use IDSchema[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 raises NotFound, as a missing row does. A model without a default_scope resolves by primary key alone. A session rule, such as a tenant rule added with with_loader_criteria, reaches the lookup too, except for an object that is already in the session. A rule that is neither goes in authorize, where data.<field>.id is the requested id. See “Which rows can a reference reach?” on the Relationships guide page.

class fastapi_restly.schemas.IDSchema(*, id: ReadOnly[Any])#

Bases: BaseSchema

The 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-only id – 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, so data.author is a wrapper (read .id). Use IDRef[User] for a flat id (5) instead.

For a scalar foreign-key COLUMN (author_id), use fr.MustExist[int, T] rather than IDSchema/IDRef: it keeps the field a plain checked id instead of turning a *_id field into an object wrapper.

id: ReadOnly[Any]#

The id of the row. In a view’s main schema, it is ReadOnly: the responses show it, and the create and update bodies that Restly generates leave it out. In a reference field, such as author: fr.IDSchema[Author], the client sends it.

get_sql_model_annotation() → type[SQLAlchemyModel] | None#

Return the annotation on IDSchema when used as:

foo: IDSchema[Foo]

This property will return “Foo”.

class fastapi_restly.schemas.TimestampsSchemaMixin(*, created_at: ReadOnly[UTCDatetime], updated_at: ReadOnly[UTCDatetime])#

Bases: BaseModel

Schema mixin that adds two fields: created_at and updated_at.

It is the schema side of TimestampsMixin. Both fields are ReadOnly[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 IDSchema or BaseSchema. Put it before the base class, so that id stays the first field in the responses:

class UserSchema(fr.TimestampsSchemaMixin, fr.IDSchema):
    name: str

A schema that Restly generates for a model with created_at and updated_at columns 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 datetime field 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 with Z, such as 2024-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 as author_id, is an ordinary field unless it has init=False. These fields are marked ReadOnly: id, created_at and updated_at, a column_property over 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 None only 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 (a default other than None, or a default_factory). Such a field has the default None, 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 in UserSchema.

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 ReadOnly fields, named <Resource>Create.

A view without its own create_schema gets this class. The class is a subclass of schema. 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 – schema is 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_schema is 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. None is 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 WriteOnly fields, named <Resource>Response.

A view without its own response_schema gets this class. Restly builds it also when the schema has no WriteOnly fields, so OpenAPI shows UserResponse and 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 – schema is 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 ReadOnly fields, with each other field optional, named <Resource>Update.

A view without its own update_schema gets this class. The class is a subclass of schema. Each call with the same arguments returns the same class, so a custom route can name the class that the view uses.

schema can be a class of your own, such as the create schema of a view that sets create_schema, so that PATCH follows 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 – schema is a SQLModel table class.

fastapi_restly.schemas.in_utc(value: datetime) → datetime#

value as 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 in data.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.