tempest_fastapi_sdk.schemas¶
Os schemas Pydantic base: BaseSchema, paginação, envelope de resposta e filtros.
BaseSchema
¶
Bases: BaseModel
Base class for every Pydantic schema in an application.
Centralizes the configuration that all DTOs share: ignore extra fields, allow building schemas from ORM attributes, serialize enum values, strip whitespace from strings, and validate assignments after construction.
Enum fields
use_enum_values=True means a field annotated with an enum
holds the value, not the member — so identity comparison
never matches, and equality only survives when the enum is
str-based. Measured on this suite::
class Kind(StrEnum): # or BaseStrEnum
GROUP = "group"
S(kind=Kind.GROUP).kind is Kind.GROUP # False
S(kind=Kind.GROUP).kind == Kind.GROUP # True
class Plain(Enum):
GROUP = "group"
S(kind=Plain.GROUP).kind == Plain.GROUP # False
Both failures type-check, run without error and simply never
enter the branch, which is the worst shape a comparison can
take. So: annotate schema fields with
:class:~tempest_fastapi_sdk.BaseStrEnum (or another
str-based enum) and compare with == / in, never
is. tests/test_enum_schema_guard.py fails when a schema
in this package annotates a field with a non-str enum.
Strings
str_strip_whitespace=True trims every str field, which is
right for names and e-mails and corrupts content: a streaming delta
" mundo" arrives as "mundo". Annotate a content field with
:data:~tempest_fastapi_sdk.RawTextField to keep it exactly as
sent; it overrides the setting for that field only.
Attributes:
| Name | Type | Description |
|---|---|---|
model_config |
ConfigDict
|
The Pydantic configuration. |
to_dict
¶
to_dict(
exclude: list[str] | None = None, include: dict[str, Any] | None = None
) -> dict[str, Any]
Serialize the schema to a plain dict.
Drops None values, removes keys listed in exclude
and merges include on top of the remaining payload.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exclude
|
list[str] | None
|
Field names to drop from the output dictionary. |
None
|
include
|
dict[str, Any] | None
|
Extra entries to merge into the output (override existing keys). |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The serialized representation. |
to_json
¶
Serialize the schema to a JSON string.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The JSON encoded representation of the schema. |
BaseResponseSchema
¶
Bases: TimestampSchemaMixin, ActiveFlagSchemaMixin, PrimaryKeySchemaMixin[IdT], Generic[IdT]
Response schema with the four columns every ORM record carries.
Composes :class:PrimaryKeySchemaMixin, :class:ActiveFlagSchemaMixin
and :class:TimestampSchemaMixin in the base order that preserves
Pydantic v2's field order (id, is_active, created_at,
updated_at).
Unsubscripted BaseResponseSchema binds id to UUID — keeping
every existing response schema unchanged. Services with integer (or
string) primary keys subclass BaseResponseSchema[int] (or compose
only the mixins their table actually carries).
Attributes:
| Name | Type | Description |
|---|---|---|
id |
IdT
|
The unique identifier of the record ( |
is_active |
bool
|
Whether the record is active (soft-delete convention). |
created_at |
datetime
|
The creation timestamp, normalized to UTC. |
updated_at |
datetime
|
The last update timestamp, normalized to UTC. |
PrimaryKeySchemaMixin
¶
Bases: BaseSchema, Generic[IdT]
Schema mixin exposing a generic id primary-key field.
Defaults to UUID when unsubscripted so existing schemas keep their
contract, and accepts any primary-key type (such as int or str)
via PrimaryKeySchemaMixin[int].
Attributes:
| Name | Type | Description |
|---|---|---|
id |
IdT
|
The unique identifier of the record. |
ActiveFlagSchemaMixin
¶
Bases: BaseSchema
Schema mixin exposing the canonical is_active boolean flag.
Pairs with :class:~tempest_fastapi_sdk.db.model.ActiveFlagMixin on
the ORM side. Existing schemas whose tables omit is_active or give
it different semantics can compose :class:PrimaryKeySchemaMixin and
:class:TimestampSchemaMixin without this mixin.
Attributes:
| Name | Type | Description |
|---|---|---|
is_active |
bool
|
Whether the record is active. |
TimestampSchemaMixin
¶
Bases: BaseSchema
Schema mixin exposing UTC-normalized created_at and updated_at.
Both fields are normalized to timezone-aware UTC after validation via
:func:~tempest_fastapi_sdk.utils.datetime.to_utc, so even ORM rows
backed by :class:~tempest_fastapi_sdk.db.model.NaiveTimestampMixin
(TIMESTAMP WITHOUT TIME ZONE) serialize on the wire with Z.
Attributes:
| Name | Type | Description |
|---|---|---|
created_at |
datetime
|
Creation timestamp normalized to UTC. |
updated_at |
datetime
|
Last-update timestamp normalized to UTC. |
DEFAULT_MAX_PAGE_SIZE
module-attribute
¶
Default ceiling on page_size for :class:BasePaginationFilterSchema.
Without one, a single request reads the whole table — and pays the cost of mapping (and, often, presigning) every row on the way out.
DEFAULT_MAX_CURSOR_LIMIT
module-attribute
¶
Default ceiling on limit for :class:CursorPaginationFilterSchema.
The value the field always carried as le=500; now overridable.
BasePaginationFilterSchema
¶
Bases: BaseSchema
Base filter schema for paginated list endpoints.
Subclass it to add domain-specific filter fields. The base
get_conditions method returns every populated field except
the pagination/sort keys, which is the contract expected by
:class:tempest_fastapi_sdk.db.repository.BaseRepository.paginate.
Field names and defaults mirror the BaseRepository.paginate
keyword arguments so passing the schema straight through works
without renaming:
.. code-block:: python
result = await repo.paginate(
filters=f.get_conditions(),
order_by=f.order_by,
page=f.page,
page_size=f.page_size,
ascending=f.ascending,
)
Attributes:
| Name | Type | Description |
|---|---|---|
page |
int
|
The page number to retrieve (1-indexed). |
page_size |
int
|
The number of items per page. |
order_by |
str | None
|
The column name to order by. |
ascending |
bool
|
Whether to order ascending. Ignored when
|
is_active |
bool | None
|
Filter by active status. |
orderable_columns |
ClassVar[frozenset[str] | None]
|
The columns
|
max_page_size |
ClassVar[int | None]
|
Inclusive ceiling on
|
Declaring both on a listing:
.. code-block:: python
class ProducerFilterSchema(BasePaginationFilterSchema):
orderable_columns = frozenset({"created_at", "name"})
max_page_size = 50
populate_by_name is on, so a subclass may rename a field on the
wire by redeclaring it with an alias and still construct the model
by its Python name. See :class:CompactPaginationFilterSchema for
the ready-made case.
get_conditions
¶
Return the dict of filter conditions for the repository.
Strips the pagination and sort keys so the resulting mapping
contains only domain-level filters consumable by
:meth:BaseRepository.paginate.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The dictionary of filter conditions. |
get_pagination_conditions
¶
Return only the pagination and sort keyword arguments.
Complements :meth:get_conditions: where that method strips the
pagination keys to expose the domain filters, this one keeps only
the pagination keys (page, page_size, order_by,
ascending). Together they let a service forward a filter
schema to :meth:BaseRepository.paginate without manually
unpacking the model, which would also leak domain filters such as
is_active into kwargs the repository does not accept:
.. code-block:: python
data = await repo.paginate(
filters=f.get_conditions(),
**f.get_pagination_conditions(),
)
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The pagination/sort keyword arguments. |
BasePaginationSchema
¶
Bases: BaseSchema, Generic[T]
Generic envelope returned by paginated endpoints.
Wraps the page of items together with the pagination metadata
the frontend needs to render controls. Field names match the
request-side :class:BasePaginationFilterSchema and the
repository keyword arguments, so the round-trip stays free of
renames.
Attributes:
| Name | Type | Description |
|---|---|---|
items |
list[T]
|
The items in the current page. |
total |
int
|
The total number of items across all pages. |
page |
int
|
The current page number (1-indexed). |
page_size |
int
|
The number of items per page. |
pages |
int
|
The total number of pages. |
populate_by_name is on, so a subclass may rename a field on the
wire by redeclaring it with an alias and still construct the model
by its Python name. See :class:CompactPaginationSchema for the
ready-made case.
The repository is unaffected either way:
:meth:tempest_fastapi_sdk.db.repository.BaseRepository.paginate
returns {"items", "total", "page", "page_size", "pages"} whatever
the envelope publishes, because the rename lives in the schema and
nowhere else.
CursorPaginationFilterSchema
¶
Bases: BaseSchema
Request filter for cursor-based pagination endpoints.
Cursor pagination scales better than offset pagination on large
tables (no COUNT(*), stable under concurrent inserts) at the
cost of losing random-access semantics. Subclass to add domain
filters; :meth:get_conditions strips the cursor/sort keys
automatically.
Attributes:
| Name | Type | Description |
|---|---|---|
cursor |
str | None
|
Opaque cursor returned by the previous
page. |
limit |
int
|
Maximum number of items to return. |
order_by |
str
|
Column to sort by. Must be a sortable column
with a stable secondary tie-break ( |
ascending |
bool
|
Whether to sort ascending. Defaults to
|
orderable_columns |
ClassVar[frozenset[str] | None]
|
The columns
|
max_limit |
ClassVar[int | None]
|
Inclusive ceiling on |
get_conditions
¶
Return only the domain-level filter conditions.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The filters with pagination/sort keys |
dict[str, Any]
|
stripped. |
get_pagination_conditions
¶
Return only the cursor pagination and sort keyword arguments.
Complements :meth:get_conditions: where that method strips the
pagination keys to expose the domain filters, this one keeps only
the pagination keys (cursor, limit, order_by,
ascending). Together they let a service forward a filter
schema to :meth:BaseRepository.cursor_paginate without manually
unpacking the model, which would also leak domain filters into
kwargs the repository does not accept:
.. code-block:: python
data = await repo.cursor_paginate(
filters=f.get_conditions(),
**f.get_pagination_conditions(),
)
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The cursor pagination/sort keyword arguments. |
CursorPaginationSchema
¶
Bases: BaseSchema, Generic[T]
Generic envelope returned by cursor-paginated endpoints.
Attributes:
| Name | Type | Description |
|---|---|---|
items |
list[T]
|
The items in the current page. |
next_cursor |
str | None
|
Cursor to request the next page,
or |
has_more |
bool
|
Whether another page is available. |
limit |
int
|
The page size used to produce this payload. |
SyncFilterSchema
¶
Bases: BaseSchema
Request filter for delta-sync (offline-first) pull endpoints.
Mirrors the keyword arguments of
:meth:tempest_fastapi_sdk.db.repository.BaseRepository.changes_since
so the schema passes straight through. An offline client persists
the server_time from the previous :class:SyncPaginationSchema
response and sends it back here as since on the next pull.
Attributes:
| Name | Type | Description |
|---|---|---|
since |
datetime | None
|
High-water mark. Only rows changed
strictly after this instant are returned. |
cursor |
str | None
|
Opaque cursor from the previous page;
|
limit |
int
|
Maximum number of items to return. |
include_deleted |
bool
|
Whether soft-deleted rows are returned
as tombstones. Defaults to |
DEFAULT_MAX_SEARCH_TERM
module-attribute
¶
Longest q :class:BaseSearchSchema accepts, in characters.
BaseSearchSchema
¶
Bases: BaseSchema
Base request schema for a text-search endpoint.
Searching is an oracle on the searched column (which rows come back says
whether each row's value contains the term), so a service that takes
fields from the request should declare searchable_columns on the
repository and here. The repository refusal is the boundary; this
one refuses earlier and documents the accepted columns. The refusal is a
:class:~tempest_fastapi_sdk.exceptions.ValidationException, not a
pydantic ValueError, so it reaches the client as the SDK's 422
envelope only with
:func:~tempest_fastapi_sdk.register_exception_handlers installed. Only
the class-level searchable_columns of a repository can be mirrored:
one passed to the repository's constructor has to be repeated here.
Declare the same set on both sides:
.. code-block:: python
class ProductRepository(BaseRepository[ProductModel]):
searchable_columns = frozenset({"name", "sku"})
class ProductSearchSchema(BaseSearchSchema):
searchable_columns = ProductRepository.searchable_columns
rows = await repo.search(body.q, fields=body.fields or ["name"])
Attributes:
| Name | Type | Description |
|---|---|---|
q |
str
|
The search term, 1 to :data: |
fields |
list[str]
|
Columns to search; empty lets the endpoint pick its default. |
searchable_columns |
ClassVar[frozenset[str] | None]
|
The columns
|
SyncPaginationSchema
¶
Bases: BaseSchema, Generic[T]
Generic envelope returned by delta-sync pull endpoints.
Extends the cursor-pagination envelope with server_time — the
instant the server started the query, which the client persists as
the next :class:SyncFilterSchema.since. Using the server clock
(not the client's, nor the max updated_at of the items) is what
keeps the watermark immune to device clock skew.
Attributes:
| Name | Type | Description |
|---|---|---|
items |
list[T]
|
The changed rows in this page (oldest change first), including soft-deleted tombstones when requested. |
next_cursor |
str | None
|
Cursor to request the next page, or
|
has_more |
bool
|
Whether another page is available. |
limit |
int
|
The page size used to produce this payload. |
server_time |
datetime
|
The server instant to persist as the
next |
LogEntrySchema
¶
Bases: BaseSchema
A single structured log record parsed from a JSON log file.
The SDK's :class:tempest_fastapi_sdk.JSONFormatter writes one JSON
object per line. This schema mirrors its core fields and accepts any
additional extra={...} keys (e.g. path, request_id,
http_500) via extra="allow" so nothing is silently dropped
by the /logs endpoint.
Attributes:
| Name | Type | Description |
|---|---|---|
timestamp |
str
|
ISO-8601 UTC timestamp ( |
level |
str
|
Log level name ( |
logger |
str
|
Name of the logger that emitted the record. |
message |
str
|
The formatted log message. |
request_id |
str | None
|
Correlation ID when present. |
exception |
str | None
|
Formatted traceback when the record
carried |
LogFilesClearedSchema
¶
Bases: BaseSchema
What a truncate request actually emptied.
Naming the files back is what makes the operation checkable: the
selector is a level name, and which files it covers is a decision of
the SDK's layout, not of the caller. "all" in particular reaches
500.log too, and a caller that assumed otherwise should be able
to see it in the response rather than in the next incident.
Attributes:
| Name | Type | Description |
|---|---|---|
cleared |
list[str]
|
File names that were truncated, in the order they were processed. A file that did not exist is created empty and still listed — the post-condition is the same either way. |
ErrorResponseSchema
¶
Bases: BaseSchema
The JSON body the SDK's exception handlers emit on failure.
Every handler registered by
:func:tempest_fastapi_sdk.register_exception_handlers — the
:class:~tempest_fastapi_sdk.exceptions.AppException handler, the
raw HTTPException 5xx handler and the unhandled-error catch-all
— writes this exact shape, so a client parses one envelope for
every failure mode.
Its reason to exist is the OpenAPI schema: without a declared model
a route can only document that it returns a 409, never what the
body looks like. Point responses= at this class (or let
:func:tempest_fastapi_sdk.error_responses do it) and the generated
client gets the envelope for free.
Branch on code, never on detail. detail is
human-readable prose that changes with the request's negotiated
locale when a
:class:~tempest_fastapi_sdk.exceptions.MessageCatalog is
registered; code is the stable contract.
Attributes:
| Name | Type | Description |
|---|---|---|
detail |
str
|
Human-readable message. Localized when a catalog is registered, otherwise the exception's literal message. |
code |
str
|
Stable, machine-readable identifier for the failure. The value a client should branch on. |
details |
dict[str, Any]
|
Structured context about the failure (which id was missing, which field conflicted). Empty when the exception attached none. |
field |
str | None
|
Name of the input the failure is about, when
the exception names one. Absent from the body — not
|
build_pagination_link_header
¶
build_pagination_link_header(
base_url: str,
*,
page: int,
page_size: int,
pages: int,
extra_params: dict[str, str] | None = None,
page_param: str = "page",
size_param: str = "page_size",
) -> str
Build a Link header for offset-based pagination.
Includes the first / prev / next / last rel values
expected by GitHub-style clients. prev / next are omitted
when they don't exist (first / last page).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_url
|
str
|
Absolute or relative URL of the collection
endpoint (e.g. |
required |
page
|
int
|
Current page number (1-based). |
required |
page_size
|
int
|
Page size. Field name matches
:class: |
required |
pages
|
int
|
Total number of pages. |
required |
extra_params
|
dict[str, str] | None
|
Extra query parameters
that must be preserved on every link (filters, sort,
etc.). Existing values on |
None
|
page_param
|
str
|
Query parameter name for the page index.
Defaults to |
'page'
|
size_param
|
str
|
Query parameter name for the page size.
Defaults to |
'page_size'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A |
str
|
|
|
str
|
nothing to link to (single page, |
CompactPaginationFilterSchema
¶
Bases: BasePaginationFilterSchema
Filter that reads the page size from size on the wire.
Same fields and same defaults as
:class:BasePaginationFilterSchema; only the query parameter is
spelled differently. Use it when a service already published
?size= and cannot rename it — an app in a store cannot be asked
to update in lockstep with the backend.
The Python name stays page_size, so
:meth:BaseRepository.paginate still takes it without a rename, and
switching a service between the two envelopes touches the schema and
nothing else.
.. code-block:: python
from fastapi import Depends
from tempest_fastapi_sdk import CompactPaginationFilterSchema
# GET /users?size=50
filters = CompactPaginationFilterSchema.model_validate({"size": 50})
filters.page_size # 50
Attributes:
| Name | Type | Description |
|---|---|---|
page_size |
int
|
Items per page, read from |
CompactPaginationSchema
¶
Bases: BasePaginationSchema[T], Generic[T]
Envelope that publishes the page size as size.
The counterpart of :class:CompactPaginationFilterSchema on the way
out: {"items", "total", "page", "size", "pages"}. Adopting the
SDK's envelope in a service that already published that shape is
otherwise a break on every paginated endpoint at once.
FastAPI serialises a response model with by_alias=True, so
declaring this as response_model is all it takes. A direct
model_dump() still answers page_size — pass
by_alias=True to see the wire name.
.. code-block:: python
from tempest_fastapi_sdk import CompactPaginationSchema
page = CompactPaginationSchema[int](
items=[1], total=1, page=1, page_size=20, pages=1
)
page.model_dump(by_alias=True)["size"] # 20
Attributes:
| Name | Type | Description |
|---|---|---|
page_size |
int
|
Items per page, published as |
decode_cursor
¶
Decode a cursor previously produced by :func:encode_cursor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cursor
|
str
|
The opaque cursor string. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The decoded payload. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
encode_cursor
¶
Serialize a cursor payload to an opaque base64-url-safe string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
dict[str, Any]
|
The cursor state to encode.
Typically |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A URL-safe base64 string without padding. |