# tempest-fastapi-sdk > tempest-fastapi-sdk holds the shared FastAPI + SQLAlchemy 2.0 (async) + Pydantic v2 building blocks used across Tempest services. Core: BaseAppSettings (+ composable settings mixins), BaseModel, BaseRepository[Model], BaseService, BaseController, base/pagination schemas, the AppException hierarchy + handlers (with an i18n message catalog and OpenAPI error documentation), AsyncDatabaseManager and AlembicHelper. Batteries: JWT/OAuth2 auth with a bundled signup/login/reset flow and TOTP MFA, a Django-style admin site, typed SSR pages, Server-Sent Events and WebSockets, Redis cache, FastStream queues and TaskIQ tasks (retries + dead letters), MinIO/S3 storage and uploads, Web Push, feature flags, audit trail, rate limiting and idempotency middleware, Prometheus metrics and OpenTelemetry tracing, self-hosted generative AI (local LLM, embeddings, RAG, speech), geolocation, Brazilian document/phone/PIX validation, and a `tempest` CLI that scaffolds services and generates typed clients from an OpenAPI spec. Python >= 3.12. Optional features ship as extras: [cli-ops], [cli], [auth], [email], [upload], [cache], [websocket], [webpush], [metrics], [queue], [queue-kafka], [queue-nats], [queue-redis], [tasks], [tasks-redis], [admin], [admin-sql], [minio], [storage-encryption], [http], [oidc], [openapi], [prometheus], [mfa], [webauthn], [firebase], [fastmcp], [pdf], [pdf-read], [pdf-layout], [slides], [slides-mermaid], [spreadsheet], [image], [vision], [genai], [genai-quant], [genai-rag], [genai-audio], [genai-tts-coqui], [genai-diarization], [faces], [genai-ollama], [genai-hosted], [genai-chroma], [genai-structured], [genai-onnx], [genai-vlm], [genai-hub], [genai-image], [genai-sound], [modelops], [modelops-compose], [modelops-onnx], [modelops-sklearn], [geo], [google-drive], [ssr], [sqlite], [postgres], [kurrentdb], [otel], [tests], [all]. --- Source: https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/index.md # tempest-fastapi-sdk > Shared FastAPI / SQLAlchemy / Pydantic building blocks used across every Tempest backend service. **Start every project with the same opinionated foundation already in place.**    !!! tip "A whole service, running" [Complete service](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/full-service.md) builds a minimal runnable project with composed settings, migrations in the lifespan, signup and login, a protected upload and an end-to-end test — the shortest way to see the SDK's pieces together. --- ## What you get out of the box !!! tip "Reach for the SDK when you would otherwise copy-paste these" SQLAlchemy `BaseModel`, abstract `BaseUserModel` + `BaseUserTokenModel`, async `BaseRepository` with `bulk_create_values`/`bulk_upsert`, Pydantic schemas + pagination (offset + cursor), exception envelope + handlers, settings mixins with `title`/`description`/`examples`, async DB / Redis / RabbitMQ / TaskIQ managers, Brazilian validators, JWT / password / email (with Jinja2 templates) / upload (pluggable Local + MinIO backends) utilities, Server-Sent Events, Web Push, Django-style admin site, bundled auth flow (signup / activate / login / reset), OAuth2/OIDC (Google/GitHub + generic), CSRF / Idempotency / BodySize / Prometheus / RateLimit middlewares, typed httpx `HTTPClient` with retry + circuit-breaker, MinIO/S3 (`AsyncMinIOClient`), an Alembic hook that reorders base columns, and a single CLI (`tempest db`, `tempest user`, `tempest new`, `tempest generate`). | Module | Exports | | --- | --- | | `tempest_fastapi_sdk.admin` | `AdminSite`, `AdminModel`, `make_admin_router`, `UserModelAuthBackend` | | `tempest_fastapi_sdk.api` | `register_exception_handlers`, `apply_cors`, `RequestIDMiddleware`, `IdempotencyMiddleware`, `BodySizeLimitMiddleware`, `AccessLogMiddleware`, `HoneypotBanMiddleware`, `CSRFMiddleware`, `PrometheusMiddleware`, `make_health_router`, `make_logs_router`, `make_prometheus_router`, OAuth (`GoogleOAuthClient` / `GitHubOAuthClient` / `OIDCProvider`), JWT/role/permission dependencies, `HardenedStaticFiles`, `RateLimitMiddleware`, `WebhookSignatureVerifier`, `run_server` | | `tempest_fastapi_sdk.auth` | `UserAuthService`, `make_auth_router`, schemas (`SignupSchema`, `LoginSchema`, `PasswordResetRequestSchema`, …) | | `tempest_fastapi_sdk.cache` | `AsyncRedisManager`, `@cached` | | `tempest_fastapi_sdk.controllers` | `BaseController` | | `tempest_fastapi_sdk.core` | `JSONFormatter`, `configure_logging`, request-ID context, `BaseStrEnum` / `BaseIntEnum` | | `tempest_fastapi_sdk.db` | `BaseModel`, `BaseUserModel`, `BaseUserTokenModel`, `UserTokenPurposeEnum`, `BaseRepository` (with `bulk_*`), `AsyncDatabaseManager`, `AlembicHelper` (+ `sync_schema` / `adopt`), `SchemaSyncOutcomeEnum`, `AuditMixin`, `SoftDeleteMixin`, `reorder_base_columns_first`, `compose_hooks` | | `tempest_fastapi_sdk.exceptions` | `AppException` hierarchy (404 / 409 / 401 / 403 / 422 / 429 / file-too-large / invalid-file-type / JWT) | | `tempest_fastapi_sdk.queue` | `MessageBroker` (recommended typed facade), `AsyncQueueManager` / `AsyncBrokerManager` (FastStream / RabbitMQ lifecycle wrappers) | | `tempest_fastapi_sdk.schemas` | `BaseSchema`, `BaseResponseSchema`, `BasePaginationFilterSchema`, `BasePaginationSchema`, cursor pagination | | `tempest_fastapi_sdk.services` | `BaseService` | | `tempest_fastapi_sdk.settings` | `BaseAppSettings`, `ServerSettings`, `DatabaseSettings`, `RedisSettings`, `RabbitMQSettings`, `KafkaSettings`, `JWTSettings`, `AuthSettings`, `CORSSettings`, `EmailSettings`, `LogSettings`, `TokenSettings`, `UploadSettings`, `WebPushSettings`, `TaskIQSettings` | | `tempest_fastapi_sdk.sse` | `EventStream`, `ServerSentEvent`, `sse_response`, `SSEBroker` | | `tempest_fastapi_sdk.storage` | `AsyncMinIOClient`, `ObjectStat` | | `tempest_fastapi_sdk.tasks` | `TaskQueue` (recommended typed facade), `AsyncTaskBrokerManager`, `AsyncTaskScheduler` | | `tempest_fastapi_sdk.testing` | `make_test_session`, `make_test_database`, in-memory SQLite helpers | | `tempest_fastapi_sdk.utils` | `PasswordUtils`, `JWTUtils`, `EmailUtils` (with `render_template`), `UploadUtils`, `LocalUploadStorage`, `MinIOUploadStorage`, `HTTPClient`, `RetryPolicy`, `MetricsUtils`, `LogUtils`, `AttemptThrottle`, `DownloadUtils`, BR helpers, opaque-token helpers | | `tempest_fastapi_sdk.webpush` | `WebPushDispatcher`, `WebPushPayloadSchema`, `WebPushSubscriptionSchema` | ## Five-minute quickstart ```bash # 1. Install the `tempest` CLI (with every extra) via uv uv tool install "tempest-fastapi-sdk[all]" # 2. Scaffold a new service in the current directory tempest new . # 3. Sync the generated project's deps + run the smoke test uv sync uv run pytest ``` !!! note "From CLI to project" Step 1 installs the **`tempest` CLI** in its own environment (via `uv tool`). `tempest new` scaffolds a project with **its own `pyproject.toml`**; from step 3 on it's that project's `uv` that resolves and runs everything (`uv sync` creates the local `.venv` from the generated deps). Prefer `uv` end to end — mixing a global `pip install` with the project's `uv sync` resolves two different environments. !!! note "About `[all]`" The `[all]` extra brings the application helpers, and leaves out the **18** extras that pull a heavy stack or a native binary: the local-model ones (`[genai]`, `[genai-audio]`, `[genai-tts-coqui]`, `[genai-diarization]`, `[genai-hub]`, `[genai-image]`, `[genai-onnx]`, `[genai-sound]`, `[genai-quant]`, `[genai-rag]`, `[genai-structured]`, `[genai-vlm]`), the ONNX/vision ones (`[faces]`, `[modelops-onnx]`, `[modelops-sklearn]`), plus `[admin-sql]`, `[firebase]` and `[slides-mermaid]`. Install those separately when you need them. The lightweight GenAI clients (Ollama, Chroma) are already in `[all]`. See **[Installation »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/installation.md)** for the full extras table. !!! example "What `tempest new` produces" ```text my-service/ ├── main.py # one-liner that imports run from src.server ├── pyproject.toml ├── .env.example └── src/ ├── server.py # uvicorn entrypoint + module-level app ├── api/ # routers, dependencies, app factory ├── controllers/ # thin orchestration over services ├── services/ # business logic ├── schemas/ # request/response DTOs ├── db/ │ ├── models/ │ └── repositories/ └── core/ # settings + constants + exceptions ``` ## Where to go next
"` (every finding of that code in the file) or
`" ::"` (only the one about that name). An entry that no
longer matches anything prints as `EXC002`: an exception does not outlive the
code it excused.
## Migrating an existing service
Start by **measuring**. The count per code tells how much work there is and
where to start:
```bash
tempest lint-layers | awk '{print $2}' | grep -E '^[A-Z]+[0-9]+$' | sort | uniq -c
```
The 0.328.0 scaffold itself, with no extras, gave this count (measured):
```text
11 IMP001
8 IMP002
1 LAY002
1 RTR004
3 TST001
```
Then take on **one family per PR**, each with `--rule` until it reaches zero:
1. **`IMP001`/`IMP002`** first: it is mechanical, changes no behaviour and
makes the next changes cheaper — moving a file no longer breaks an
import.
2. **`LAY001`–`LAY003`** and **`INIT001`**: move each class into its
context package, in a file without the layer suffix, and take what is
not a re-export out of the `__init__.py` files, re-exporting relatively. With step 1 done, the call sites do not change.
3. **`DI001`–`DI003`**: create `scripts/composition.py` and make the
providers call the `build_*` functions; delete the `from_session`s.
4. **`RTR003`–`RTR006`**: create `routers/api.py` and take `/api` out of the
domains; swap each domain's `APIRouter` for `TempestAPIRouter` and move
`summary=`/`description=` into `api/docs/.py`.
5. **`STR001`/`STR002`**: stateful callbacks become classes; a fixed
argument becomes `partial`.
6. **`TST001`–`TST004`**: the suite — by far the biggest bill in the transport
service (1380 of 1394 tests without the docstring shape).
7. **Tasks and schemas**, when the service has them: split registration from
work, and document the fields.
Three traps the transport service hit on the way:
!!! warning "Import cycle through the resources"
Importing `api.dependencies` (the package) from the tasks and scripts
would close a cycle with `src.tasks`. There, tasks and scripts kept
importing `api.dependencies.resources` directly — with an `IMP002`
[declared exception](#declared-exception).
!!! warning "Task names preserved"
When splitting the big `tasks.py` into domain modules, a task changes
file but **not name** — or the messages already queued are stranded. Pin
the old name in the `*_TASK_NAME` constant.
!!! warning "pytest-xdist ids"
A `parametrize` with `uuid4()` turned into text in the id blocked
`pytest -n auto`. Swap it for fixed literals before turning parallel on.
Once a family reaches zero, turn on `layers_strict = true` — from then on, a
warning that comes back fails `tempest check`.
## Recap
- **One class per file**, in `//`; the package re-exports
relatively and the rest imports through the package.
- **A file named without the layer suffix, at most 1000 lines**; the
`__init__.py` only re-exports.
- **A service receives repositories; a controller receives services.** The
graph is assembled in `scripts/composition.py`, and nobody has a
`from_session`.
- **A repository does not import a repository.**
- **One router per file**, and `/api` only in `build_api_router`; a
domain router is a `TempestAPIRouter`, with `@raises` and its text in
`api/docs`.
- **No nested function and no module `_helper`**, in the source and the
suite.
- **A task is registration only**, with a fixed name; the API enqueues by
name.
- **Documented schema**, checked by `assert_schema_metadata`.
- **Tests with `Cenário:`/`Esperado:`** that check something, with a specific
exception and a deterministic `parametrize`.
- All of it is a **warning** until you turn on `layers_strict`; what you keep
on purpose goes in `tests/architecture_exceptions.py`, with its reason.
---
Source: https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/service-standard.md
# Service standard
This page is the **citable reference** for how a Tempest service is laid
out: each item of the standard, why it exists, and **what enforces it
today** — a `tempest lint-layers` code, a `tempest check` step, or a test
`tempest new` already writes into your project. When an item has no gate,
the page says so too.
The standard is the `transport-backend`'s, the service these rules were
measured on. [#718](https://github.com/mauriciobenjamin700/tempest-fastapi-sdk/issues/718)
records why it became the reference: a new service was written by an AI
**without starting from `tempest new`**, and only a review against the
transport brought it back to a clean `lint-layers --strict`,
`lint-schemas` and `openapi-errors`.
!!! tip "Start from `tempest new`"
Everything this page describes already comes out of `tempest new`.
Writing the service by hand, or copying another one, is exactly the
mistake of #718. For a new domain inside an existing project, follow
the recipe in the `CLAUDE.md` the scaffold writes; for the file-shape
rules, see the [Recommended architecture](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recommended-architecture.md).
## What `tempest new` generates
!!! info "The `tempest` command needs the `[cli]` extra (or `[cli-ops]` on a server)"
Without either, `tempest` exits with code 2 and prints how to install it.
In development: `uv add --dev "tempest-fastapi-sdk[cli]"`. Details in
[Installation → CLI](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/installation.md#cli).
```bash
tempest new demo --extras sqlite
```
The project's directory tree (`tree -d`, measured on this page's branch):
```text
.
├── alembic
│ └── versions
├── src
│ ├── api
│ │ ├── dependencies
│ │ ├── docs
│ │ └── routers
│ ├── controllers
│ │ └── system
│ ├── core
│ │ ├── constants
│ │ │ └── messages
│ │ ├── enums
│ │ ├── exceptions
│ │ └── types
│ ├── db
│ │ ├── configs
│ │ ├── models
│ │ └── repositories
│ ├── schemas
│ ├── scripts
│ ├── services
│ └── utils
└── tests
├── integration
│ └── system
└── unit
├── architecture
└── core
```
And `tempest check` on it, untouched (`ENV=test`, which the generated
`conftest.py` pins as well):
```text
$ ruff check --extend-select ANN001,ANN201,ANN202,ANN205,ANN206 .
All checks passed!
$ ruff format --check .
61 files already formatted
$ mypy --disallow-untyped-defs --disallow-incomplete-defs .
Success: no issues found in 59 source files
$ lint-layers
Layer rules: no findings.
$ openapi-errors
Every route's declared errors match its flow (src).
$ lint-schemas
Schema metadata: src.schemas is fully documented.
$ pytest -n auto -p no:cacheprovider
...
9 passed
```
The nine tests are the ones the scaffold writes: three integration tests
of the root route and health, three architecture guards and three for the
exception contract.
## The standard, item by item
| Rule | What it looks like | What enforces it today |
| --- | --- | --- |
| One layer class per file, per context | `src///.py`, only the class + `logger` + `__all__` | `LAY001`, `LAY002` |
| A file name without the layer suffix | `services/orders/checkout.py` → `CheckoutService` (never `checkout_service.py`) | `LAY003` |
| At most 1000 lines per file, code and tests, no exception list | a big service becomes several by responsibility; a big test file, one file per theme | `SIZE001` |
| No nested `def` and no module-level `_x`, in `src` and `tests` | a stateful callback becomes a callable object | `STR001`, `STR002` |
| `__init__` imports relatively; elsewhere, import the package | `from .x import Y` / `from src.services import X` | `IMP001`, `IMP002` |
| `__init__.py` only re-exports | `from .x import Y as Y` + `__all__`; assembly in `router.py`, `factory.py`, `runner.py` | `INIT001` |
| A resource is a process singleton in one place | `api/dependencies/resources.py` (`db`, `get_session`, `get_*`) | — (scaffold convention) |
| Providers per layer; a router never sees `AsyncSession` | `api/dependencies/controllers.py` calls the `build_*` | `RTR001`, `DI001`–`DI003` |
| A controller inherits the SDK's base | `BaseController[Service]` (one service) or `Controller` (several, or none) | — (scaffold convention) |
| Login and signup come from the SDK | `UserAuthService` + `make_auth_router(..., prefix="/api/auth")` | — (no gate) |
| `/api` set in one place | `routers/api.py` → `build_api_router()` | `RTR003`, `RTR004` |
| A domain router is a `TempestAPIRouter` | `TempestAPIRouter(prefix=...)`, never `fastapi.APIRouter` | `RTR005` |
| OpenAPI text out of the router | `api/docs/.py`, one `EndpointDoc` per handler | `RTR006` |
| Exceptions: one module per status, contract in the class body | `core/exceptions/{bad_request,unauthorized,forbidden,not_found,conflict}.py` | `tests/unit/core/test_exceptions_contract.py` |
| Frozen exception contract | status, `code`, message and `field` of each class | `tests/unit/core/test_exceptions_contract.py` |
| Prose and constants out of the module that uses them | `core/constants/` + `core/constants/messages/{errors,successes}.py` | — (scaffold convention) |
| `Protocol`, alias, `NamedTuple`, enum | `core/types/.py`, `core/enums/.py` | `LAY001` (outside the layer); `ENUM001` (suffix) |
| Database | `db/configs/{connection,migrations,names}.py` | — (scaffold convention) |
| Mapping in the repository | `map_to_response` | `REPO001` (partial) |
| Graph assembled outside the request | `scripts/composition.py` (`build_*`) | `DI003` (`from_session`) |
| Every schema field documented | `Field(title=..., description=..., examples=...)` | `lint-schemas` + `tests/unit/architecture/test_schemas.py` |
| Every route declares what it raises | `@raises(...)` below the route decorator | `openapi-errors` + `tests/unit/architecture/test_openapi_errors.py` |
| Tests | `Cenário:`/`Esperado:`, checking something; `tests/{unit,integration}//` | `TST001`–`TST004` |
| Guards in the suite itself | `tests/unit/architecture/` | `test_layers.py`, `test_openapi_errors.py`, `test_schemas.py` |
| Warnings fail from the first commit | `layers_strict = true` under `[tool.tempest]` | `tempest check` |
The `LAY`, `STR`, `IMP`, `INIT`, `SIZE`, `DI`, `RTR003`–`RTR006` and `TST` codes are
**warnings**: they only fail `tempest check` with `layers_strict = true`,
which the generated `pyproject.toml` already turns on. The table of every
code, with each one's real output, is in
[CLI › Layer rules](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/lint-layers.md).
!!! note "What has no gate"
The resource singleton, `core/constants` and `db/configs` are
convention: the scaffold starts that way and the `CLAUDE.md`
recipe teaches it, but no rule fails when you deviate. They were left
out because the check would have to judge intent (what is "prose",
what is a "process resource"), and a rule that broad flags correct
code.
The controller base and the auth flow have no gate either.
`Controller` has no methods at all, so inheriting it changes nothing
that runs; what the convention protects — a controller receives
services, never a session or another controller — is already
`DI001`/`DI002`. And a hand-written `/login` route cannot be told,
from the syntax, from one that has a reason to exist (a proxy to
another provider): the gate would have to judge intent again.
## `__init__.py` only re-exports
**Why:** an `__init__.py` runs on the import of any module of its package.
A function, a composed router or a factory in there runs for whoever only
wanted a schema, sits outside the file index (nobody looks for
`build_admin_router` in an `__init__.py`) and invites an import cycle. The
package holds a docstring, relative re-exports and `__all__` — nothing
else.
❌ The package builds the router:
```python
# src/api/routers/admin/__init__.py
from fastapi import APIRouter
from .orders import router as orders_router
admin_router: APIRouter = APIRouter(prefix="/admin", tags=["admin"])
admin_router.include_router(orders_router)
```
✅ `router.py` builds it, the `__init__.py` re-exports it, and
`build_api_router` includes `build_admin_router()`:
```python
# src/api/routers/admin/router.py
from tempest_fastapi_sdk import TempestAPIRouter
from .orders import router as orders_router
def build_admin_router() -> TempestAPIRouter:
"""Assemble the admin routers under ``/admin``.
Returns:
TempestAPIRouter: ``/admin`` with every admin router included.
"""
admin: TempestAPIRouter = TempestAPIRouter(prefix="/admin", tags=["admin"])
admin.include_router(orders_router)
return admin
```
```python
# src/api/routers/admin/__init__.py
from .router import build_admin_router as build_admin_router
__all__: list[str] = ["build_admin_router"]
```
A factory goes to `factory.py` (`src/integrations/payment/factory.py`), a
seed run to `runner.py` (`src/db/seed/runner.py`), each re-exported the
same way. `INIT001` reports every statement that does more than re-export
— a `def`, a `class`, a call, a constant —, in the source and in the suite;
`if TYPE_CHECKING:` and an optional import in a `try` pass while they only
import.
## Authentication: mount the SDK's, do not write yours
**Why:** signup, activation, login, refresh, logout, `/me`, password and
email change already exist in the SDK, with the password policy, the
duplicate-email 409, session revocation and the JWT pair right. A
hand-written `AuthService` rebuilds each of those and drifts one release at
a time.
The service composes the pieces, all exported by `tempest_fastapi_sdk`:
`BaseUserModel` (the base of `UserModel`), `make_user_token_model(...)` and
`make_user_refresh_token_model(...)` (the token tables), `AuthSettings` (in
`Settings`, next to `JWTSettings`), `UserAuthService`,
`make_auth_router(...)` and, on the service's own routes,
`UserAuthService.current_user_dependency(...)` or
`make_jwt_user_dependency`.
❌ Hand-written auth routes:
```python
# src/api/routers/auth.py
from fastapi import APIRouter, Depends
from src.api.dependencies import get_auth_controller
from src.controllers import AuthController
from src.schemas import LoginSchema, TokenPairSchema
router: APIRouter = APIRouter(prefix="/auth", tags=["auth"])
@router.post("/login")
async def login(
data: LoginSchema,
controller: AuthController = Depends(get_auth_controller),
) -> TokenPairSchema:
"""Log a user in by email and password."""
return await controller.login(data)
```
✅ The service comes out of the composition root and the router is mounted
in `create_app`, like the other SDK routers:
```python
# src/scripts/composition.py
from tempest_fastapi_sdk import AsyncDatabaseManager, UserAuthService
from src.core import Settings
from src.db.models import UserModel, UserTokenModel
def build_auth_service(db: AsyncDatabaseManager, settings: Settings) -> UserAuthService:
"""Assemble the SDK's auth service over this project's tables.
Args:
db (AsyncDatabaseManager): The process-wide database manager.
settings (Settings): Settings composing ``AuthSettings`` and
``JWTSettings``.
Returns:
UserAuthService: The service ``make_auth_router`` serves.
"""
return UserAuthService(
db=db,
user_model=UserModel,
token_model=UserTokenModel,
auth_settings=settings,
jwt_settings=settings,
email=None,
)
```
```python
# src/api/app.py
from fastapi import FastAPI
from tempest_fastapi_sdk import make_auth_router
from src.api.dependencies import db, get_session
from src.core import settings
from src.scripts import build_auth_service
def create_app() -> FastAPI:
"""Build the application with the SDK's auth routes under ``/api/auth``.
Returns:
FastAPI: The configured application.
"""
app = FastAPI()
app.include_router(
make_auth_router(
build_auth_service(db, settings),
session_factory=get_session,
prefix="/api/auth",
),
)
return app
```
To extend it without rewriting a route: `signup_schema=` (a `SignupSchema`
subclass; a field that is a column lands on the row before the insert),
`on_signup=` (a `(session, user, payload)` hook inside the insert's
transaction) and `me_response_model=` (an `AuthUserSchema` subclass,
returned by `GET /auth/me`). The three appear together in one complete
example in the
[auth recipe](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/endpoints.md#an-account-born-with-more-than-email-and-password-v02780).
!!! warning "The whole prefix goes in `prefix=`, with the router mounted on the app"
`make_auth_router` writes its own prefix into the refresh cookie's
`Path` and into the URLs it builds, and it cannot see a prefix put
around it. Measured with `AUTH_TOKEN_DELIVERY=cookie`, a login followed
by `POST /api/auth/refresh` with the client's cookie jar:
| `make_auth_router(...)` | `POST /api/auth/login` | refresh cookie | `POST /api/auth/refresh` |
| --- | --- | --- | --- |
| default `/auth`, included in an `APIRouter(prefix="/api")` | `200` | `Path=/auth` | `401` |
| `prefix="/api/auth"`, `app.include_router(...)` | `200` | `Path=/api/auth` | `200` |
Included inside `build_api_router` with the default `/auth`, the route
answers at `/api/auth/login`, but the cookie goes out with `Path=/auth`
and the browser never sends it to `/api/auth/refresh`. Mounting on the
app with `prefix="/api/auth"` does not trip `RTR004`, which reads only
the `prefix=` of `APIRouter(...)` and `include_router(...)` — measured
with `tempest lint-layers` over a `tempest new --extras auth` project
with that mount in `create_app`.
## Exceptions: one module per status, contract in the body
**Why:** the status + `code` pair is what the client reads to decide what
to show, and the message is what the user sees. When the class declares
all three in its body, whoever reads the class **without instantiating
it** — `error_responses` documenting OpenAPI, the `BaseRepository` raising
the 404, `tempest openapi-errors` — sees the same contract the client
receives. An `__init__` that builds the message hides it, and makes every
`raise` remember the arguments.
The module says the status, so whoever looks for "what returns 409" opens
`conflict.py`:
```python
# src/core/exceptions/not_found.py
from typing import Any, ClassVar
from tempest_fastapi_sdk import NotFoundException
from src.core.constants.messages import errors
class ItemNotFoundException(NotFoundException):
"""Raised when an item id matches no stored record."""
code = "ITEM_NOT_FOUND"
message = errors.ITEM_NOT_FOUND
field = "item_id"
details_example: ClassVar[dict[str, Any]] = {"item_id": "3f2b8c1e"}
```
- `code` is the stable identifier. Without it the class inherits the
SDK's generic one (`"NOT_FOUND"`), and the SDK warns with
`InheritedErrorCodeWarning`.
- `message` comes from a constant, never from an f-string.
- `field` names the culprit input. Leave it unset on invalid credentials:
saying which half of the pair was wrong helps whoever is guessing.
- Data that changes per `raise` goes in `details=`:
```python
from src.core.exceptions import ItemNotFoundException
def require_item(item_id: str, found: bool) -> None:
"""Refuse a lookup that missed.
Args:
item_id (str): The id that was looked up.
found (bool): Whether the lookup matched a row.
Raises:
ItemNotFoundException: When ``found`` is false.
"""
if not found:
raise ItemNotFoundException(details={"item_id": item_id})
```
### The frozen contract
The generated `tests/unit/core/test_exceptions_contract.py` keeps, as
literals, the status, `code`, message and `field` of every class
`src.core.exceptions` re-exports — and fails when a new class lands
without an entry. Measured: with an `OrderAlreadyPaidException`
re-exported and no line in the contract, the test fails like this:
```text
E AssertionError: assert {'ItemNotFoun...aidException'} == {'ItemNotFoundException'}
E Extra items in the left set:
E 'OrderAlreadyPaidException'
1 failed, 2 passed
```
Renaming, moving or rewording an exception becomes a visible change in
that file's diff — which is an API change.
## Messages and constants out of the module that uses them
**Why:** a message string spread over a service and an exception is the
first place an AI (and we) duplicate text. With one constant per `code`,
a wording change is one line, and the reader sees where the text came
from:
```python
# src/core/constants/messages/errors.py
ITEM_NOT_FOUND: str = "Item not found."
"""Message of ``ItemNotFoundException``."""
__all__: list[str] = ["ITEM_NOT_FOUND"]
```
Import the **module**, not the constant —
`from src.core.constants.messages import errors` — so the use site reads
`errors.ITEM_NOT_FOUND`. A constant that is not client text goes in
`core/constants/.py`, re-exported by the package. An enum goes in
`core/enums/.py`; a `Protocol`, an alias and a result
`NamedTuple`, in `core/types/.py` — never next to the class in a
layer module, which holds that class alone (`LAY001`).
## Database: `db/configs`
**Why:** the engine configuration and the boot migration are decisions
for the whole process, and each has **one** place:
```python
# src/db/configs/connection.py
from tempest_fastapi_sdk import AsyncDatabaseManager, DatabaseSettings
def make_db_manager(settings: DatabaseSettings) -> AsyncDatabaseManager:
"""Build the database manager for the given settings.
Args:
settings (DatabaseSettings): The project's settings.
Returns:
AsyncDatabaseManager: A manager with the bind parameters out of
the error messages.
"""
return AsyncDatabaseManager(**settings.database_kwargs(), hide_parameters=True)
```
`hide_parameters=True` keeps the bind parameters out of the text of every
SQLAlchemy exception. Without it, a logged `IntegrityError` writes
`[parameters: (...)]` with the row's e-mail, document number or password
hash — the same defect #718 found in `tempest user create`.
`db/configs/migrations.py` holds `run_migrations`, which the lifespan
calls while `DATABASE_MIGRATE_ON_STARTUP` is on (the default). It uses
`AlembicHelper.sync_schema_async`, which covers an empty database, one
created before Alembic and one already migrated, and refuses a pending
migration that drops a table, column or constraint. Turn it off when
several replicas start together and a job runs `tempest db upgrade`.
!!! info "Neither imports the project"
`src.db.models` imports `src.db.configs` for the table names. If
`connection.py` imported `src.core`, loading the models (which
Alembic does on every revision) would build the settings. That is why
`make_db_manager` takes the settings as a parameter, typed with the
SDK's `DatabaseSettings` mixin, and `run_migrations` takes the URL.
## OpenAPI text out of the router
**Why:** the router is wiring — method, path, `Depends`, `responses=`. The
prose Swagger shows changes for other reasons, and mixed into the
decorator it gets lost in the wiring's diff. `api/docs/.py` holds
one `EndpointDoc` per handler, in `UPPER_SNAKE`:
```python
# src/api/docs/base.py
from typing import TypedDict
class EndpointDoc(TypedDict):
"""Summary and description of one endpoint in the OpenAPI document."""
summary: str
description: str
```
```python
# src/api/docs/service_info.py
from .base import EndpointDoc
INDEX: EndpointDoc = {
"summary": "Describe the service",
"description": (
"Returns the name the service runs under, read from the TITLE "
"setting. Public, no authentication."
),
}
```
And the router spreads the dictionary into the decorator:
```python
# src/api/routers/service_info.py
from fastapi import Depends
from tempest_fastapi_sdk import TempestAPIRouter
from src.api.dependencies import get_service_info_controller
from src.api.docs import service_info
from src.controllers import ServiceInfoController
from src.schemas import ServiceInfoSchema
router: TempestAPIRouter = TempestAPIRouter(tags=["root"])
@router.get("/", **service_info.INDEX)
async def index(
controller: ServiceInfoController = Depends(get_service_info_controller),
) -> ServiceInfoSchema:
"""Placeholder root endpoint returning the service name.
Args:
controller (ServiceInfoController): The injected controller.
Returns:
ServiceInfoSchema: The service title.
"""
return await controller.describe()
```
Both keys are the `summary` and `description` parameters of
`APIRouter.get`/`post`, so mypy checks the spread.
The wrong shape is what shows up when the text stays in the router: loose
`SUMMARY_*` constants at the top of the module, or `summary="..."` written
in the decorator. `tempest check` reports each keyword as `RTR006` — and,
in the same file, the `fastapi.APIRouter` as `RTR005` (see the next
section):
```python
# src/api/routers/service_info.py
from fastapi import APIRouter, Depends
from src.api.dependencies import get_service_info_controller
from src.controllers import ServiceInfoController
from src.schemas import ServiceInfoSchema
SUMMARY_INDEX: str = "Describe the service"
router: APIRouter = APIRouter(tags=["root"])
@router.get("/", summary=SUMMARY_INDEX, description="Returns the service name.")
async def index(
controller: ServiceInfoController = Depends(get_service_info_controller),
) -> ServiceInfoSchema:
"""Placeholder root endpoint returning the service name.
Args:
controller (ServiceInfoController): The injected controller.
Returns:
ServiceInfoSchema: The service title.
"""
return await controller.describe()
```
```text
$ tempest lint-layers . --rule RTR005 --rule RTR006
src/api/routers/service_info.py:10: RTR005 (warning) APIRouter(...) builds this router (`router`); build it with `TempestAPIRouter` from tempest_fastapi_sdk, which turns each handler's `@raises(...)` into its `responses=` (a plain APIRouter ignores the tag).
src/api/routers/service_info.py:13: RTR006 (warning) route `index` passes `summary=` in its decorator; keep the OpenAPI text in an `EndpointDoc` constant of api/docs/.py and spread it into the decorator (`**docs.INDEX`).
src/api/routers/service_info.py:13: RTR006 (warning) route `index` passes `description=` in its decorator; keep the OpenAPI text in an `EndpointDoc` constant of api/docs/.py and spread it into the decorator (`**docs.INDEX`).
3 layer finding(s): 0 error(s), 3 warning(s).
```
Same text, another place: move each pair into an `EndpointDoc` in
`api/docs/service_info.py` and spread it into the decorator, as above.
??? info "Why `EndpointDoc` lives in the template and not in the SDK"
The SDK already has `RouteDoc` (in `tempest_fastapi_sdk.api.route_docs`),
but it is the bilingual catalog of the **SDK's own** routes: it
accepts `None` to fall back to the function name, and is read by key.
The service's `EndpointDoc` is a two-field `TypedDict` with both keys
required, spread straight into the decorator. Publishing it from the
SDK would be public surface for a two-line type each service reads
from its own `api/docs` — the kind of wrapper we prefer not to depend
on.
## Route errors: `TempestAPIRouter` + `@raises`
**Why:** the client needs to know, from the OpenAPI document, which errors
a route returns — with each one's `code`. The list lives next to the
handler, in a `@raises(...)` right **below** the route decorator, and the
SDK's `TempestAPIRouter` turns it into the route's `responses=`. Every
domain router is a `TempestAPIRouter`, never a `fastapi.APIRouter`:
```python
# src/api/routers/product.py
from fastapi import Depends, status
from tempest_fastapi_sdk import TempestAPIRouter, raises
from src.api.dependencies import get_product_controller
from src.api.docs import product as product_docs
from src.controllers import ProductController
from src.core.exceptions import ProductNameTakenException, ProductSkuTakenException
from src.schemas import ProductCreateSchema, ProductResponseSchema
router: TempestAPIRouter = TempestAPIRouter(prefix="/products", tags=["products"])
@router.post("", status_code=status.HTTP_201_CREATED, **product_docs.CREATE_PRODUCT)
@raises(ProductNameTakenException, ProductSkuTakenException)
async def create_product(
data: ProductCreateSchema,
controller: ProductController = Depends(get_product_controller),
) -> ProductResponseSchema:
"""Create a product.
Args:
data (ProductCreateSchema): The creation payload.
controller (ProductController): The injected controller.
Returns:
ProductResponseSchema: The created product.
"""
return await controller.create(data)
```
That route's `409` comes out like this in `app.openapi()["paths"]["/api/products"]["post"]["responses"]`
(measured with `fastapi` 0.165.0, the SDK's floor, and both exceptions
declaring `code`, `message` and a docstring in the class body):
```json
{
"description": "PRODUCT_NAME_TAKEN | PRODUCT_SKU_TAKEN",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponseSchema"
},
"examples": {
"PRODUCT_NAME_TAKEN": {
"summary": "Name in use.",
"value": {
"detail": "A product with this name already exists.",
"code": "PRODUCT_NAME_TAKEN",
"details": {},
"field": "name"
}
},
"PRODUCT_SKU_TAKEN": {
"summary": "SKU in use.",
"value": {
"detail": "A product with this SKU already exists.",
"code": "PRODUCT_SKU_TAKEN",
"details": {}
}
}
}
}
}
}
```
`ErrorResponseSchema` lands in `components.schemas` and the response
points at it through `$ref`; exceptions sharing a status become one
example each, keyed by `code`.
Three details, all measured on the same app:
- **On a `fastapi.APIRouter`, `@raises` does nothing.** The tag stays on
the handler, nobody reads it, and the route comes out with only `200`
and `422` — no error, no warning. That is why `tempest check` reports an
`APIRouter` in `routers/` as `RTR005`.
- **An explicit `responses=` is for overriding one status.** The
hand-written entry replaces the generated one for that status code
**whole** — the `$ref` and that status's examples are gone. Use it only
when you really want other text for one code.
- **The aggregator stays an `APIRouter`.** The responses are built by the
router the handler is registered on, and `include_router` carries them
up unchanged. A `TempestAPIRouter` in `build_api_router` adds nothing,
and a domain `APIRouter` included into a `TempestAPIRouter` aggregator
still has no errors.
`tempest check` (the `openapi-errors` step) reads `@raises` as the route's
declaration: an exception the flow reaches that is missing from the list
fails the gate. The full recipe, with the message catalog and
`error_responses` for routers that are not yours, is in
[OpenAPI errors](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/openapi-errors.md).
## Guards in the suite itself
**Why:** `tempest check` already runs `lint-layers`, `openapi-errors` and
`lint-schemas`, but not everyone runs `tempest check` — the editor runs
`pytest`, a pre-commit hook runs `pytest`. The scaffold writes the three
gates as tests too, in `tests/unit/architecture/`:
```python
# tests/unit/architecture/test_layers.py
from pathlib import Path
from tempest_fastapi_sdk.cli.layer_lint import lint_layers
PROJECT_ROOT: Path = Path(__file__).resolve().parents[3]
def test_the_layer_rules_report_nothing() -> None:
"""Cenário: as regras de camada sobre o projeto inteiro.
Esperado: nenhum achado, nem erro nem aviso.
"""
findings = [finding.render(PROJECT_ROOT) for finding in lint_layers(PROJECT_ROOT)]
assert findings == []
```
`test_openapi_errors.py` does the same with `analyze_paths` over `src`,
and `test_schemas.py` with `assert_schema_metadata(src.schemas)`. The
layer test fails on **warnings** too — the same bar as `layers_strict`.
The suite is split by kind and area: `tests/unit//` for one class in
isolation, `tests/integration//` for a request through the app, each
directory with an `__init__.py`.
## An existing project: `tempest generate --standard`
`tempest new` only writes new projects. A service generated before this
version keeps its `core/exceptions.py`, `tests/test_smoke.py` and the
`AlembicHelper` in the lifespan — and keeps working. To bring in the
pieces of the standard that collide with nothing, run at the project
root:
```bash
tempest generate --standard
```
On a service whose `src/core/exceptions.py` holds `UserNotFoundError`
(`NotFoundException`) and `UserEmailAlreadyTakenError`
(`ConflictException`), the output is:
```text
+ src/core/constants/__init__.py
+ src/core/constants/messages/__init__.py
+ src/core/constants/messages/errors.py
+ src/core/constants/messages/successes.py
+ src/core/enums/__init__.py
+ src/core/types/__init__.py
+ tests/unit/__init__.py
+ tests/unit/architecture/__init__.py
+ tests/unit/architecture/test_layers.py
+ tests/unit/architecture/test_openapi_errors.py
+ tests/unit/architecture/test_schemas.py
+ tests/unit/core/__init__.py
+ src/core/exceptions/conflict.py
+ src/core/exceptions/not_found.py
+ src/core/exceptions/__init__.py
+ tests/unit/core/test_exceptions_contract.py
- src/core/exceptions.py
> UserEmailAlreadyTakenError -> core/exceptions/conflict.py
> UserNotFoundError -> core/exceptions/not_found.py
Standard: 16 written, 0 skipped, 2 exception(s) moved.
```
What happens:
- **Missing packages and guards** (`core/constants/`, `core/enums/`,
`core/types/`, `tests/unit/architecture/`) come from the same templates
as `tempest new`. A file that already exists is left alone unless you
pass `--force`; and a package whose flat module already exists
(`core/constants.py`) is **not** written, because the new package would
shadow the module silently — the report says why.
- **`core/exceptions.py` becomes the `core/exceptions/` package**, one
module per status. Each class's status is read by **importing** the
module, not guessed from its base: a class that inherits a 500 base and
declares `status_code = 409` goes to `conflict.py`. The `__init__.py`
re-exports everything, so `from src.core.exceptions import
UserNotFoundError` keeps working, and the flat file is deleted.
- **The contract is frozen** in `tests/unit/core/test_exceptions_contract.py`
with the status, `code`, message and `field` each class has today. A
class that builds its message in `__init__` gets a warning naming it:
the contract fails for it until the data moves into the class body and
what changes per `raise` goes in `details=`.
!!! warning "The migration refuses before writing"
If `core/exceptions.py` holds anything besides imports, classes and
`__all__` (a module-level constant or function has no status to go
to), if splitting by status would make the modules import each other,
or if the module does not import, the command exits with code 1, the
message names the file and the line, and **nothing** is written.
Running it again changes nothing: everything that exists is skipped. The
rest of the standard (`db/configs`, `scripts/composition.py`,
`api/docs/`) touches the app's wiring and stays manual — one item per PR,
in the order of the
[recommended architecture's migration](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recommended-architecture.md#migrating-an-existing-service).
Turn `layers_strict = true` on once the warnings reach zero.
## Recap
- **Start from `tempest new`**; a new domain follows the recipe of the
generated `CLAUDE.md`.
- **Exception:** one module per status, `code`/`message`/`field` in the
body, no `__init__`, per-raise data in `details=` — and one line in the
frozen contract.
- **Client text in `core/constants/messages`**; enums, types and
constants in per-domain packages.
- **`db/configs`** holds `make_db_manager` (`hide_parameters=True`) and
the boot's `run_migrations`.
- **`api/docs`** holds each handler's `EndpointDoc`.
- **`__init__.py` only re-exports**; composition in `router.py`, a
factory in `factory.py`, a seed in `runner.py`. A file named without
the layer suffix, at most 1000 lines.
- **Auth is the SDK's**: `UserAuthService` + `make_auth_router(..., prefix="/api/auth")`
mounted on the app, extended through `signup_schema`, `on_signup` and
`me_response_model`.
- **`layers_strict = true`** and the guards in `tests/unit/architecture/`
make `tempest check` and `pytest` fail on the first deviation.
---
Source: https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/tutorial.md
# Tutorial — building the *Users* feature
This tutorial walks through wiring the **Users** feature using every SDK convention. By the end you'll have:
- A SQLAlchemy `UserModel` with audit + soft-delete columns
- Pydantic schemas for create / update / response / filter
- A repository, service and controller subclassing the SDK bases
- Routers with `Depends`-injected controllers
- Domain exception subclasses serialized by the SDK's exception handler
- A paginated `GET /users` and a signup `POST /users` (with password hashing via `PasswordUtils`)
!!! tip "Tip for the impatient"
If you only want to copy the layout, scaffold it: `tempest new my_service`. The CLI ships the same skeleton this tutorial walks through.
!!! info "Auth flow already ships"
This tutorial shows how to **build** signup/login with `BaseRepository` + `BaseService` + `BaseController` — the foundation for any feature. For the **complete auth flow** (signup + email activation + JWT login + password reset), the SDK ships `UserAuthService` + `make_auth_router` since v0.31.0; jump to the **[Auth flow »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow.md)** recipe when you want the shortcut instead of implementing it manually.
!!! info "Following along"
Full-file snippets — the ones that open with a bare file-path comment (e.g. `# src/db/models/users/user.py`) — are **standalone**: paste each into the path shown. Blocks marked `(continued)` or with a `# ... above ...` comment **append** to the file shown just above; they are not a new file. The full project tree is the [mandatory project layout from Architecture →](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/architecture.md#mandatory-project-layout), and why each shape is the way it is lives in [Recommended architecture →](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recommended-architecture.md).
We'll build a complete `Users` feature from scratch, end to end. Every file below is something you write in your project; SDK primitives are imported.
### 1. Project layout
The canonical layout every Python service shipped against this SDK should adopt — `main.py` is a one-liner, `src/server.py` exposes both `run()` and the importable `app` (or re-exports it from `src/api/app.py`), `api/dependencies/` is **always a package** (auth + factory providers), `controllers/` is mandatory even when it's only a thin pass-through, `repositories/` lives **under** `db/`, and every layer holding classes keeps its modules in a **context package** — here, `users/` —, one class per module.
```text
my-service/
├── alembic.ini # generated by AlembicHelper.init
├── alembic/ # env.py + versions/ (one revision per schema change)
├── main.py # one-liner: from src.server import run; run()
└── src/
├── __init__.py # re-exports `run` from .server
├── server.py # programmatic uvicorn.run(...) + module-level `app`
├── core/
│ ├── __init__.py
│ ├── settings.py # Settings(mixins..., BaseAppSettings)
│ └── exceptions/ # one module per status: not_found.py, conflict.py, ...
├── db/
│ ├── __init__.py # re-exports BaseModel + every model
│ ├── configs/
│ │ ├── __init__.py
│ │ └── migrations.py # run_migrations: sync_schema_async() in the lifespan
│ ├── models/
│ │ ├── __init__.py # from .users import UserModel as UserModel
│ │ └── users/
│ │ ├── __init__.py
│ │ └── user.py # UserModel(BaseModel)
│ └── repositories/
│ ├── __init__.py
│ └── users/
│ ├── __init__.py
│ └── user.py # UserRepository(BaseRepository[UserModel])
├── schemas/
│ ├── __init__.py
│ └── user.py # UserCreate/Update/Response/Filter
├── services/
│ ├── __init__.py
│ └── users/
│ ├── __init__.py
│ └── user.py # UserService — business logic
├── controllers/
│ ├── __init__.py
│ └── users/
│ ├── __init__.py
│ └── user.py # UserController — orchestration (thin pass-through OK)
├── scripts/
│ ├── __init__.py
│ └── composition.py # build_user_controller — the graph assembled in one place
└── api/
├── __init__.py
├── app.py # create_app() — middleware, CORS, exception handlers, build_api_router()
├── docs/ # OpenAPI text, one module per router
│ ├── __init__.py
│ ├── base.py # EndpointDoc — summary + description TypedDict
│ └── users.py # one EndpointDoc per handler of routers/users.py
├── routers/
│ ├── __init__.py
│ ├── api.py # build_api_router(): the only place with /api
│ └── users.py # TempestAPIRouter, one per file, with only its own prefix
└── dependencies/ # ALWAYS a package, never a flat module
├── __init__.py
├── auth.py # X-Token / current_user / require_role dependencies
├── resources.py # infra singletons (db/storage/mail) + get_db/get_session
└── controllers.py # get__controller providers, which call the composition root
```
Each `__init__.py` re-exports its neighbours with a **relative** import (`from .user import UserModel as UserModel`), and the rest of the code imports through the **layer package**: `from src.schemas import UserCreateSchema`, never `from src.schemas.user import UserCreateSchema`. This keeps refactors painless — move files around without breaking imports. `tempest lint-layers` checks both (`IMP001`, `IMP002`) and the layers' shape (`LAY001`, `LAY002`).
If your service has no controllers/services/repositories yet, **still ship empty packages with the right names** — uniformity matters more than skipping a directory. Drop `db/`, `utils/`, `queue/` or `tasks/` only when the service genuinely doesn't need persistence/utilities/messaging.
### 2. Settings, server, app factory & entry point
Five files map onto five responsibilities:
| File | Responsibility |
| --- | --- |
| `src/core/settings.py` | `Settings(...mixins, BaseAppSettings)` — one source of truth for env vars. |
| `src/api/dependencies/resources.py` | infra singletons (`db = AsyncDatabaseManager(**settings.database_kwargs())`, and — opt-in — storage/mail) + `get_db` / `get_session` providers. Single owner of resource lifecycle. |
| `src/api/app.py` | thin `create_app()` factory — middleware + CORS + exception handlers + router includes + module-level `app` instance. **Imports** the resources from `dependencies`, never builds them. |
| `src/server.py` | `run()` invoking `uvicorn.run("src.api.app:app", ...)` programmatically, plus re-exports `app` so external runners (gunicorn, uvicorn CLI) can import it. |
| `main.py` | Process entry point — a single line under `if __name__ == "__main__":` calling `run()`. |
```python
# src/core/settings.py
from tempest_fastapi_sdk import (
BaseAppSettings,
DatabaseSettings,
EmailSettings,
JWTSettings,
ServerSettings,
UploadSettings,
)
class Settings(
ServerSettings,
DatabaseSettings,
JWTSettings,
EmailSettings,
UploadSettings,
BaseAppSettings,
):
"""All environment-driven configuration lives here.
Each mixin brings its own variables: SERVER_*, DATABASE_*, JWT_*,
SMTP_* and UPLOAD_*. Declare here only what no mixin models.
"""
settings: Settings = Settings()
```
Each mixin brings its own variables, with defaults and validation —
`JWT_SECRET`, `SMTP_HOST` and `UPLOAD_DIR` come from `JWTSettings`,
`EmailSettings` and `UploadSettings`, with nothing redeclared. The table of
every mixin, the `.env.example` and each one's `*_kwargs()` mapper are in
[Settings](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/settings.md).
!!! warning "`BaseAppSettings` is always the **last** base"
Every mixin already inherits `BaseAppSettings`; listed before a mixin, the
import fails with
`TypeError: Settings: BaseAppSettings must be the LAST base — ...`.
The full message and the rule are in
[Settings](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/settings.md#list-baseappsettings-last).
Infra resources (the database now; storage / mail later) live in
`src/api/dependencies/resources.py`, built **once** and reached through
`get_*` providers. `app.py` only **imports** them, so it never bloats with
resource construction:
```python
# src/api/dependencies/resources.py
from tempest_fastapi_sdk import AsyncDatabaseManager
from src.core.settings import settings
db = AsyncDatabaseManager(**settings.database_kwargs())
get_session = db.session_dependency # Depends(get_session) -> AsyncSession
def get_db() -> AsyncDatabaseManager:
"""Return the process-wide database manager."""
return db
```
```python
# src/api/app.py
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from fastapi import FastAPI
from tempest_fastapi_sdk import (
RequestIDMiddleware,
make_health_router,
register_exception_handlers,
)
from src.api.dependencies.resources import db
from src.api.routers import build_api_router
from src.core.settings import settings
from src.db.configs import run_migrations
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncGenerator[None, None]:
"""Migrate the schema and connect on startup, dispose on shutdown."""
await run_migrations(settings.DATABASE_URL)
await db.connect()
try:
yield
finally:
await db.disconnect()
def create_app() -> FastAPI:
"""Build and configure the FastAPI app."""
app = FastAPI(title="my-service", version="0.1.0", lifespan=lifespan)
app.add_middleware(RequestIDMiddleware)
register_exception_handlers(app)
# Meta endpoints sit at the root prefix.
app.include_router(make_health_router(db=db, version="0.1.0"))
# Business endpoints sit under /api/, mounted once by build_api_router().
app.include_router(build_api_router())
return app
app = create_app()
```
```python
# src/server.py
from tempest_fastapi_sdk import run_server
from src.api.app import app # noqa: F401 — re-exported for external runners
from src.core.settings import settings
def run() -> None:
"""Start the API server programmatically."""
run_server("src.api.app:app", settings=settings)
__all__: list[str] = ["app", "run"]
```
`run_server` reads `SERVER_HOST` / `SERVER_PORT` / `SERVER_RELOAD` from `settings` (falling back to `127.0.0.1` / `8000` / `False`) and forwards any extra kwargs (`workers=`, `log_config=`, `ssl_*=`) verbatim to `uvicorn.run`. See the [Programmatic server entry point recipe](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http/extras.md#programmatic-server-entry-point).
```python
# src/__init__.py
from .server import run as run
__all__: list[str] = ["run"]
```
```python
# main.py
from src.server import run
if __name__ == "__main__":
run()
```
Bind defaults: `127.0.0.1` for internal services (the SDK's `ServerSettings.SERVER_HOST` default), `0.0.0.0` only when the service is consumed by a separate origin (e.g. a frontend dev server). Never start uvicorn via `subprocess.run(["uvicorn", ...])` — always go through `run_server` (or `uvicorn.run("src.api.app:app", ...)` directly) so reload, signal handling and graceful shutdown behave correctly.
### 3. ORM model
```python
# src/db/models/users/user.py
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column
from tempest_fastapi_sdk import BaseModel
class UserModel(BaseModel):
"""One row per registered user.
Inherits from BaseModel, so it automatically gets:
- id (UUID v4, cross-DB portable via sqlalchemy.Uuid)
- is_active (bool, soft-delete flag)
- created_at, updated_at (timezone-aware TIMESTAMP, set by Python AND
the DB so the instance attribute is populated right after flush)
- __tablename__ = "user" (auto: class name without "Model" suffix,
snake-cased; override by assigning __tablename__ explicitly)
- __eq__/__hash__ by (type, id) so the same row across sessions
compares equal
- to_dict(exclude, include, remove_none) and
update_from_dict(data, allowed_fields) helpers
"""
name: Mapped[str] = mapped_column(String(64), nullable=False)
email: Mapped[str] = mapped_column(String(128), unique=True, nullable=False)
password_hash: Mapped[str] = mapped_column(String(128), nullable=False)
```
Re-export it, from the context package up, always relatively:
```python
# src/db/models/users/__init__.py
from .user import UserModel as UserModel
__all__: list[str] = ["UserModel"]
```
```python
# src/db/models/__init__.py
from .users import UserModel as UserModel
__all__: list[str] = ["UserModel"]
```
```python
# src/db/__init__.py
from tempest_fastapi_sdk import BaseModel as BaseModel
from .models import UserModel as UserModel
__all__: list[str] = ["BaseModel", "UserModel"]
```
> **Tip:** Always import models in `src/db/__init__.py`. SQLAlchemy needs to "see" every model before `BaseModel.metadata` is complete, so Alembic autogenerate (and the `create_tables()` of test fixtures) work correctly.
#### The schema in the database: migrations
The `user` table is born from an Alembic migration, not from
`create_tables()` in the lifespan — `create_tables()` adds no column to a
table that already exists, so the schema stops following the model on the
second boot. Generate the Alembic environment once, with the SDK's
`AlembicHelper.init` instead of writing `alembic.ini` and `alembic/env.py`
by hand:
```python
# scripts/alembic_init.py
from tempest_fastapi_sdk import AlembicHelper
AlembicHelper("alembic.ini").init(
"alembic",
metadata_module="src.db",
metadata_attr="BaseModel",
)
```
!!! info "The `tempest` command needs the `[cli]` extra (or `[cli-ops]` on a server)"
Without either, `tempest` exits with code 2 and prints how to install it.
In development: `uv add --dev "tempest-fastapi-sdk[cli]"`. Details in
[Installation → CLI](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/installation.md#cli).
```bash
uv run python scripts/alembic_init.py
uv run tempest db revision -m "create users"
```
`metadata_module` is `src.db` because that is the package that re-exports
`BaseModel` and imports every model. The revision is required: with none,
the next step creates no table.
The lifespan from step 2 calls `run_migrations`, in the shape `tempest new`
generates:
```python
# src/db/configs/migrations.py
from pathlib import Path
from tempest_fastapi_sdk import AlembicHelper, SchemaSyncOutcomeEnum
ALEMBIC_INI_PATH: Path = Path(__file__).resolve().parents[3] / "alembic.ini"
async def run_migrations(database_url: str) -> SchemaSyncOutcomeEnum:
"""Bring the database schema to the Alembic head."""
return await AlembicHelper(
str(ALEMBIC_INI_PATH),
db_url=database_url,
).sync_schema_async()
```
```python
# src/db/configs/__init__.py
from .migrations import ALEMBIC_INI_PATH as ALEMBIC_INI_PATH
from .migrations import run_migrations as run_migrations
__all__: list[str] = ["ALEMBIC_INI_PATH", "run_migrations"]
```
`sync_schema_async()` covers an empty database (runs every revision), a
database created before Alembic (stamps the base revision and migrates the
rest) and an already-migrated one (applies only what is missing). The why of
each path is in [Migrations »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/migrations.md).
### 4. Schemas
!!! info "Installation"
The schemas below use `EmailStr`, which needs the `email-validator` package — pull it in with the `[email]` extra (`uv add "tempest-fastapi-sdk[email]"`) or via `pydantic[email]`. Further down the service uses `PasswordUtils` (bcrypt hashing), which needs the `[auth]` extra — `uv add "tempest-fastapi-sdk[auth]"`.
The recommended naming pattern: one `*Create`, `*Update`, `*Response` and `*Filter` schema per resource. Every field carries `title`, `description` and `examples` — it is what the `openapi.json` shows the client, and what `assert_schema_metadata` (and `tempest lint-schemas`) enforces.
```python
# src/schemas/user.py
from pydantic import EmailStr, Field
from tempest_fastapi_sdk import (
BasePaginationFilterSchema,
BaseResponseSchema,
BaseSchema,
)
class UserCreateSchema(BaseSchema):
"""Payload for POST /users."""
name: str = Field(
min_length=1,
max_length=64,
title="Name",
description="Display name.",
examples=["Ana"],
)
email: EmailStr = Field(
title="E-mail",
description="Login e-mail; unique.",
examples=["ana@example.com"],
)
password: str = Field(
min_length=8,
max_length=128,
title="Password",
description="Plain password, hashed before storage.",
examples=["s3cret-pass"],
)
class UserUpdateSchema(BaseSchema):
"""Partial payload for PATCH /users/{id}. Every field optional."""
name: str | None = Field(
default=None,
min_length=1,
max_length=64,
title="Name",
description="New display name.",
examples=["Ana Maria"],
)
email: EmailStr | None = Field(
default=None,
title="E-mail",
description="New login e-mail.",
examples=["ana.maria@example.com"],
)
class UserResponseSchema(BaseResponseSchema):
"""Outbound representation.
Inherits id/is_active/created_at/updated_at from BaseResponseSchema
(timestamps already normalized to UTC by the field validator).
"""
name: str = Field(title="Name", description="Display name.", examples=["Ana"])
email: EmailStr = Field(
title="E-mail",
description="Login e-mail.",
examples=["ana@example.com"],
)
class UserFilterSchema(BasePaginationFilterSchema):
"""Query-string filters for GET /users.
Inherits page/page_size/order_by/ascending/is_active from
BasePaginationFilterSchema. ``name`` is an ILIKE %name% search,
``email`` an exact match.
"""
name: str | None = Field(
default=None,
title="Name",
description="Part of the name to search for.",
examples=["an"],
)
email: EmailStr | None = Field(
default=None,
title="E-mail",
description="Exact e-mail to match.",
examples=["ana@example.com"],
)
```
```python
# src/schemas/__init__.py
from .user import UserCreateSchema as UserCreateSchema
from .user import UserFilterSchema as UserFilterSchema
from .user import UserResponseSchema as UserResponseSchema
from .user import UserUpdateSchema as UserUpdateSchema
__all__: list[str] = [
"UserCreateSchema",
"UserFilterSchema",
"UserResponseSchema",
"UserUpdateSchema",
]
```
### 5. Domain exceptions
The SDK ships generic `NotFoundException`, `ConflictException`, etc. Subclass them per domain so the `isinstance` / `except DomainError` matching stays explicit. Class-level `message` / `code` / `status_code` are defaults the constructor falls back to — you can also override any of them at the raise site without subclassing:
```python
# src/core/exceptions/not_found.py
from tempest_fastapi_sdk import NotFoundException
class UserNotFoundError(NotFoundException):
"""Subclass kept only for ``except UserNotFoundError`` matching."""
message: str = "Usuário não encontrado"
code: str = "USER_NOT_FOUND"
```
```python
# src/core/exceptions/conflict.py
from tempest_fastapi_sdk import ConflictException
class UserEmailAlreadyTakenError(ConflictException):
"""Raised when the e-mail is already taken by another user."""
message: str = "Já existe um usuário com esse e-mail"
code: str = "USER_EMAIL_TAKEN"
```
One module per status: whoever looks for "what returns 409" opens `conflict.py`. The `__init__.py` re-exports, so the import stays `from src.core.exceptions import ...` (the full standard lives in [Service standard](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/service-standard.md)):
```python
# src/core/exceptions/__init__.py
from .conflict import UserEmailAlreadyTakenError as UserEmailAlreadyTakenError
from .not_found import UserNotFoundError as UserNotFoundError
__all__: list[str] = ["UserEmailAlreadyTakenError", "UserNotFoundError"]
```
For one-off codes you don't need a subclass — pass them to the constructor:
```python
from uuid import UUID
from tempest_fastapi_sdk import NotFoundException
order_id = UUID("6f1c3d84-2a55-4d0b-9d7e-0c1a2b3c4d5e")
raise NotFoundException(
"Pedido não encontrado",
code="ORDER_NOT_FOUND",
details={"order_id": str(order_id)},
)
```
The SDK's exception handler ([`register_exception_handlers`](#2-settings-server-app-factory-entry-point)) serializes them to:
```json
{
"detail": "Usuário não encontrado",
"code": "USER_NOT_FOUND",
"details": {}
}
```
The frontend branches on `code`, not on the (potentially translated) message.
### 6. Repository
For plain CRUD you don't need a subclass at all — instantiate `BaseRepository` directly and bind the model via the constructor:
```python
# anywhere a session is in scope
import asyncio
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from tempest_fastapi_sdk import BaseRepository
from src.db.models import UserModel
# In a service the session comes from `db.get_session_context()`; here, SQLite.
session = AsyncSession(create_async_engine("sqlite+aiosqlite:///:memory:"))
repository = BaseRepository(session, model=UserModel)
async def main() -> None:
"""Run this example."""
await repository.add(
UserModel(
email="ana@example.com",
name="Ana",
password_hash="",
)
)
asyncio.run(main())
```
Subclass when you want to bake in domain-specific messages, swap the not-found exception, override the mapper methods or add custom queries. The constructor signature (not class attributes) is the contract:
```python
# src/db/repositories/users/user.py
from sqlalchemy.ext.asyncio import AsyncSession
from tempest_fastapi_sdk import BaseRepository
from src.core.exceptions import UserNotFoundError
from src.db.models import UserModel
from src.schemas import UserResponseSchema
class UserRepository(BaseRepository[UserModel, UserResponseSchema]):
"""Data-access layer for users."""
def __init__(self, session: AsyncSession) -> None:
super().__init__(
session,
model=UserModel,
not_found_exception=UserNotFoundError,
not_found_message="Usuário não encontrado",
create_conflict_message="Já existe um usuário com esse e-mail",
update_conflict_message="Conflito ao atualizar usuário",
)
def map_to_schema(self, instance: UserModel) -> UserResponseSchema:
return UserResponseSchema.model_validate(instance)
def map_to_response(self, instance: UserModel) -> UserResponseSchema:
return self.map_to_schema(instance)
```
Re-export it like the model — `src/db/repositories/users/__init__.py` with `from .user import UserRepository as UserRepository`, and `src/db/repositories/__init__.py` with `from .users import UserRepository as UserRepository`.
The base repo gives you 20+ methods for free — see the [reference table](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/reference/admin-data-api/db/#tempest_fastapi_sdk.db.repository.BaseRepository). Add custom queries on top of the same `UserRepository`:
```python
# src/db/repositories/users/user.py (continued)
from tempest_fastapi_sdk import BaseRepository
from src.db.models import UserModel
from src.schemas import UserResponseSchema
class UserRepository(BaseRepository[UserModel, UserResponseSchema]):
# ... __init__ and mappers above ...
# ──────── custom queries on top of the inherited bulk + read methods ────────
async def get_by_email(self, email: str) -> UserModel:
"""Look up a user by email. Raises ``UserNotFoundError`` on miss."""
return await self.get({"email": email})
```
The highlighted block (under the divider comment) is what you typically add per project — everything above it is the boilerplate the base class already takes care of.
### 7. Service
The service is where business rules live. It calls one or more repositories and never touches HTTP or SQLAlchemy types directly.
Inherit from `BaseService[RepositoryT, ResponseT]`. Doing so gives you `get_by_id`, `get_or_none`, `list`, `paginate`, `count`, `exists` and `delete` for free — every one is already wired to `repository.map_to_response` (sync or async). Override only the methods that need domain logic; add new ones for use cases the base doesn't cover (signup, password reset, etc.):
```python
# src/services/users/user.py
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from tempest_fastapi_sdk import BaseService, PasswordUtils
from src.core.exceptions import UserEmailAlreadyTakenError
from src.db.repositories import UserRepository
from src.schemas import UserCreateSchema, UserResponseSchema, UserUpdateSchema
class UserService(BaseService[UserRepository, UserResponseSchema]):
"""Business logic for the user domain.
Inherits the canonical read-path methods (``get_by_id`` / ``list`` /
``paginate`` / ``count`` / ``exists`` / ``delete``) from
:class:`BaseService` and adds the write-path methods that need
domain rules (uniqueness check, password hashing, mass-assignment
guard).
"""
def __init__(
self,
repository: UserRepository,
*,
passwords: PasswordUtils,
) -> None:
"""Initialize the service.
Args:
repository (UserRepository): User-domain repository.
passwords (PasswordUtils): Shared bcrypt helper.
"""
super().__init__(repository)
self.passwords: PasswordUtils = passwords
# ──────── overrides: domain rules live here ────────
async def signup(self, data: UserCreateSchema) -> UserResponseSchema:
"""Create a new user, enforcing email uniqueness + hashing the password."""
if await self.repository.exists({"email": data.email}):
raise UserEmailAlreadyTakenError()
instance = self.repository.map_to_model(
{
**data.to_dict(exclude=["password"]),
"password_hash": self.passwords.hash(data.password),
},
)
instance = await self.repository.add(instance)
return self.repository.map_to_response(instance)
async def update(
self,
user_id: UUID,
data: UserUpdateSchema,
) -> UserResponseSchema:
"""Apply a partial update, whitelisting the columns that may change."""
instance = await self.repository.get_by_id(user_id)
instance.update_from_dict(
data.to_dict(),
allowed_fields={"name", "email"}, # prevents mass-assignment
)
instance = await self.repository.update(instance)
return self.repository.map_to_response(instance)
async def soft_delete(self, user_id: UUID) -> None:
"""Flip ``is_active=False`` instead of hard-deleting."""
await self.repository.soft_delete(user_id)
```
The service receives the repository and the `PasswordUtils`, never the `AsyncSession` nor another service — the composition root of step 9 assembles the graph. Re-export it through `src/services/users/__init__.py` and `src/services/__init__.py`, as in the layers above (and step 8's controller through `src/controllers/users/__init__.py` and `src/controllers/__init__.py`).
The methods you do **not** write — `get_by_id(user_id)`, `get_or_none(filters)`, `list(filters=None, order_by=None, ascending=True)`, `paginate(filters=None, order_by=None, page=1, page_size=20, ascending=True)`, `count(filters)`, `exists(filters)`, `delete(user_id)` — already exist on the base, already await an async `map_to_response`, and already return the typed `UserResponseSchema` declared in the generic parameter.
When the use case needs a custom pipeline (joins, projections, transactional fan-out), override the inherited method. The signature stays the same so the controller doesn't notice:
```python
from typing import Any
from tempest_fastapi_sdk import BaseService
from src.db.repositories import UserRepository
from src.schemas import UserResponseSchema
class UserService(BaseService[UserRepository, UserResponseSchema]):
# ... __init__ and overrides above ...
async def list( # override the inherited pass-through
self,
filters: dict[str, Any] | None = None,
order_by: Any | None = None,
ascending: bool = True,
) -> list[UserResponseSchema]:
"""List active users only — domain rule baked into the base method."""
merged: dict[str, Any] = {**(filters or {}), "is_active": True}
return await super().list(filters=merged, order_by=order_by, ascending=ascending)
```
### 8. Controller
Even when there's no orchestration to do, `controllers/` exists as a **thin pass-through** so the import graph stays uniform across services. The day a use case needs to coordinate two services (or fan out to a queue), the controller is already there.
Inherit from `BaseController[ServiceT]` (the older `BaseController[ServiceT, ResponseT]` form stays accepted for compatibility, while pass-through methods derive both response and update types straight from the service). The base forwards `get_by_id`, `list`, `paginate`, `count`, `update` and `delete` to the service for you — you only declare methods that add cross-service coordination or that don't exist on the service (custom use cases like `signup`):
```python
# src/controllers/users/user.py
from uuid import UUID
from tempest_fastapi_sdk import BaseController
from src.schemas import UserCreateSchema, UserResponseSchema, UserUpdateSchema
from src.services import UserService
class UserController(BaseController[UserService]):
"""Orchestrate user use cases.
Today every method is a thin pass-through to ``UserService``. As
soon as a use case needs to coordinate more than one service —
e.g. signup also sends a welcome email and enqueues a CRM sync —
the orchestration lives here, not in the router and not in the
service.
"""
# ──────── new methods for use cases the base doesn't cover ────────
async def signup(self, data: UserCreateSchema) -> UserResponseSchema:
"""Create a user and (eventually) trigger downstream side effects."""
return await self.service.signup(data)
async def update(
self,
user_id: UUID,
data: UserUpdateSchema,
) -> UserResponseSchema:
"""Domain-specific partial update — distinct from the base ``delete``."""
return await self.service.update(user_id, data)
async def soft_delete(self, user_id: UUID) -> None:
"""Soft-delete instead of the inherited hard ``delete``."""
await self.service.soft_delete(user_id)
```
`get_by_id` / `list` / `paginate` / `count` are not redeclared — `BaseController` already exposes them. When the cross-service coordination day arrives, override the pass-through in place:
```python
from tempest_fastapi_sdk import BaseController
from src.schemas import UserCreateSchema, UserResponseSchema
from src.services import UserService
class UserController(BaseController[UserService]):
# ... methods above ...
async def signup(self, data: UserCreateSchema) -> UserResponseSchema:
"""Create the user, send a welcome email, enqueue the CRM sync."""
user = await self.service.signup(data)
await self.emails.send_welcome(user) # second dependency
await self.tasks.enqueue("crm.user.created", {"id": str(user.id)})
return user
```
The router signature never changes — only the controller's body grows.
### 9. Composition root and dependency providers
The `repository → service → controller` graph is assembled **in one place**, the composition root, with one `build_*` function per entry point. The request provider calls that function with what `Depends` resolved; a task, a script or a test call the same function. No class knows how to build itself — there is no `from_session`.
```python
# src/scripts/composition.py
from sqlalchemy.ext.asyncio import AsyncSession
from tempest_fastapi_sdk import PasswordUtils
from src.controllers import UserController
from src.db.repositories import UserRepository
from src.services import UserService
PASSWORDS: PasswordUtils = PasswordUtils()
"""Stateless bcrypt helper, built once per process."""
def build_user_controller(session: AsyncSession) -> UserController:
"""Wire repository → service → controller over one session.
Args:
session (AsyncSession): The session the repository reads through.
Returns:
UserController: The controller, fully wired.
"""
repository = UserRepository(session)
service = UserService(repository=repository, passwords=PASSWORDS)
return UserController(service=service)
```
```python
# src/scripts/__init__.py
from .composition import build_user_controller as build_user_controller
__all__: list[str] = ["build_user_controller"]
```
`api/dependencies/` is **always a package**. `auth.py` hosts the shared-secret / current-user dependencies; `resources.py` hosts the infra singletons (`db`, and — opt-in — storage/mail) with the `get_db` / `get_session` providers; `controllers.py` hosts the providers the routers depend on. Never construct controllers, services, or infra resources inline inside the router file (or in `app.py`).
```python
# src/api/dependencies/controllers.py
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
from src.api.dependencies.resources import get_session
from src.controllers import UserController
from src.scripts import build_user_controller
def get_user_controller(
session: AsyncSession = Depends(get_session),
) -> UserController:
"""Build the user controller for a single request."""
return build_user_controller(session)
```
```python
# src/api/dependencies/__init__.py
from .controllers import get_user_controller as get_user_controller
__all__: list[str] = ["get_user_controller"]
```
### 10. Router
Routers receive controllers via FastAPI `Depends` — no inline construction, no business logic, no DB calls. One router per file, declaring only its own prefix (`/users`); `/api` is set once, in `build_api_router`. Meta endpoints (`/health`, `/tool-spec`) stay at the root prefix.
The text Swagger shows does not stay in the router. It lives in
`src/api/docs/users.py`, one `EndpointDoc` per handler, and the router
spreads it into the decorator (`**user_docs.CREATE_USER`). `EndpointDoc` is
the `summary` + `description` `TypedDict` that `tempest new` already writes
in `src/api/docs/base.py` — the why is in
[Service standard › OpenAPI text out of the router](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/service-standard.md#openapi-text-out-of-the-router):
```python
# src/api/docs/users.py
from .base import EndpointDoc
CREATE_USER: EndpointDoc = {
"summary": "Create a user",
"description": (
"Creates the account and returns the user. Responds 409 (USER_EMAIL_TAKEN) when the e-mail is already in use."
),
}
GET_USER: EndpointDoc = {
"summary": "Get a user",
"description": (
"Returns the user by id. Responds 404 (USER_NOT_FOUND) when it does not exist."
),
}
UPDATE_USER: EndpointDoc = {
"summary": "Update a user",
"description": (
"Applies a partial update of name and e-mail."
),
}
DELETE_USER: EndpointDoc = {
"summary": "Deactivate a user",
"description": (
"Marks the user inactive, without deleting the row."
),
}
LIST_USERS: EndpointDoc = {
"summary": "List users",
"description": (
"Returns one page of users, filtered and ordered by the query string."
),
}
__all__: list[str] = ["CREATE_USER", "DELETE_USER", "GET_USER", "LIST_USERS", "UPDATE_USER"]
```
Re-export the module from `src/api/docs/__init__.py`
(`from . import users as users`).
The router is a `TempestAPIRouter`, not a `fastapi.APIRouter`: the
`@raises(...)` right **below** each route decorator lists the exceptions
the flow raises, and `TempestAPIRouter` turns them into the route's
`responses=` — one `ErrorResponseSchema` per status, with one example per
`code`. On a plain `APIRouter` the same tag does nothing
([Route errors](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/service-standard.md#route-errors-tempestapirouter-raises)):
```python
# src/api/routers/users.py
from uuid import UUID
from fastapi import Depends, status
from tempest_fastapi_sdk import BasePaginationSchema, TempestAPIRouter, raises
from src.api.dependencies import get_user_controller
from src.api.docs import users as user_docs
from src.controllers import UserController
from src.core.exceptions import UserEmailAlreadyTakenError, UserNotFoundError
from src.schemas import (
UserCreateSchema,
UserFilterSchema,
UserResponseSchema,
UserUpdateSchema,
)
router: TempestAPIRouter = TempestAPIRouter(prefix="/users", tags=["users"])
@router.post(
"",
response_model=UserResponseSchema,
status_code=status.HTTP_201_CREATED,
**user_docs.CREATE_USER,
)
@raises(UserEmailAlreadyTakenError)
async def create_user(
data: UserCreateSchema,
controller: UserController = Depends(get_user_controller),
) -> UserResponseSchema:
return await controller.signup(data)
@router.get("/{user_id}", response_model=UserResponseSchema, **user_docs.GET_USER)
@raises(UserNotFoundError)
async def get_user(
user_id: UUID,
controller: UserController = Depends(get_user_controller),
) -> UserResponseSchema:
return await controller.get_by_id(user_id)
@router.patch("/{user_id}", response_model=UserResponseSchema, **user_docs.UPDATE_USER)
@raises(UserNotFoundError)
async def update_user(
user_id: UUID,
data: UserUpdateSchema,
controller: UserController = Depends(get_user_controller),
) -> UserResponseSchema:
return await controller.update(user_id, data)
@router.delete(
"/{user_id}",
status_code=status.HTTP_204_NO_CONTENT,
**user_docs.DELETE_USER,
)
@raises(UserNotFoundError)
async def delete_user(
user_id: UUID,
controller: UserController = Depends(get_user_controller),
) -> None:
await controller.soft_delete(user_id)
@router.get(
"",
response_model=BasePaginationSchema[UserResponseSchema],
**user_docs.LIST_USERS,
)
async def list_users(
filters: UserFilterSchema = Depends(),
controller: UserController = Depends(get_user_controller),
) -> BasePaginationSchema[UserResponseSchema]:
result = await controller.paginate(
filters=filters.get_conditions(),
order_by=filters.order_by,
page=filters.page,
page_size=filters.page_size,
ascending=filters.ascending,
)
return BasePaginationSchema[UserResponseSchema](**result)
```
Mount it in `build_api_router`, the only place `/api` appears. The aggregator stays a plain `APIRouter`: the errors are built by the router the handler is registered on, and `include_router` carries them up unchanged:
```python
# src/api/routers/api.py
from fastapi import APIRouter
from .users import router as users_router
API_PREFIX: str = "/api"
"""Prefix every business route lives under."""
def build_api_router() -> APIRouter:
"""Assemble the router ``create_app`` includes.
Returns:
APIRouter: ``/api`` with every domain router included.
"""
api: APIRouter = APIRouter(prefix=API_PREFIX)
api.include_router(users_router)
return api
```
```python
# src/api/routers/__init__.py
from .api import build_api_router as build_api_router
__all__: list[str] = ["build_api_router"]
```
### 11. Pagination
The pagination contract is enforced end-to-end by SDK primitives:
- `UserFilterSchema(BasePaginationFilterSchema)` parses `?page=&page_size=&order_by=&ascending=&is_active=&name=` from the query string and exposes `.get_conditions()` returning only the domain-level filters (without pagination keys).
- `UserRepository.paginate(...)` runs the query with the filter dict + ordering + offset/limit + count, returning the dict `{items, total, page, page_size, pages}` that you wrap in `BasePaginationSchema[UserResponseSchema]`.
- `BasePaginationSchema[UserResponseSchema]` wraps the result so OpenAPI documents the response shape correctly.
```http
GET /api/users?page=2&page_size=20&order_by=name&ascending=true&is_active=true&name=ana
```
Returns:
```json
{
"items": [
{"id": "...", "name": "Ana ...", "email": "...", ...},
...
],
"total": 142,
"page": 2,
"page_size": 20,
"pages": 8
}
```
---
## Recap
You wired the **Users** feature end to end, one layer at a time, each backed by an SDK primitive:
- **Model** — `UserModel(BaseModel)` gets `id` / `is_active` / `created_at` / `updated_at` + helpers for free.
- **Schemas** — `UserCreateSchema` / `UserUpdateSchema` / `UserResponseSchema` / `UserFilterSchema` over `BaseSchema` / `BaseResponseSchema` / `BasePaginationFilterSchema`.
- **Exceptions** — domain subclasses (`UserNotFoundError`, `UserEmailAlreadyTakenError`) serialized by `register_exception_handlers`.
- **Repository** — `UserRepository(BaseRepository[UserModel])` — 20+ inherited methods + custom queries.
- **Service** — `UserService(BaseService[...])` — business rules (email uniqueness, password hashing) over the inherited read-path.
- **Controller** — `UserController(BaseController[...])` — orchestration (thin pass-through today, coordination tomorrow).
- **Composition root** — `build_user_controller` assembles the graph once; the request provider, a task and a test call the same function.
- **Router** — endpoints with `UserController` injected via `Depends`, one router per file, mounted under `/api/users` by `build_api_router`.
- **Layout** — each layer in a context package (`users/`), relative `__init__`, imports through the layer package; `tempest lint-layers` checks the shape, and [Recommended architecture](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recommended-architecture.md) explains why each rule exists.
- **Pagination** — `BasePaginationFilterSchema` → `paginate(...)` → `BasePaginationSchema[UserResponseSchema]` end to end.
### Next steps
- **[Auth flow »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow.md)** — swap the manual `signup` for `UserAuthService` + `make_auth_router` (signup + email activation + JWT login + password reset).
- **[Database »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database.md)** — Alembic migrations, bulk operations, and the `BaseRepository` audit/soft-delete mixins.
- **[Testing »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/testing.md)** — test the feature with `pytest` + in-memory SQLite.
- **[Server entry point »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http.md)** — middleware, CORS, health, tool-spec and `run_server`.
- **[Security »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/security.md)** — harden the service (rate limit, CSRF, idempotency, body-size limits).
- **[Frontend in Python »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/tempestweb-frontend.md)** — give this API a screen without writing JavaScript: **tempestweb** consumes the same schemas through a typed HTTP client, and the SDK serves the compiled build on the same origin.
---
Source: https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/index.md
# Recipes
Bite-sized "I want to wire X" walkthroughs. Each page starts with **what problem it solves**, **when to reach for it**, and a complete code example you can copy verbatim.
!!! tip "Start here"
- **Brand-new service?** Follow the **[Tutorial »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/tutorial.md)** — linear, builds the *Users* feature step by step.
- **Just need a signature?** Jump to the **[Reference »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/reference.md)**.
- **Wiring a specific piece?** You're in the right place — the [tour](#sdk-tour-one-example-per-block) below is the map, and the [index](#recipe-index) takes you to the full recipe.
- **Want to see it all working together?** Head to the **[complete examples](#complete-examples)**.
- **Prefer studying a guided project?** See the **[Learning projects »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/learning/index.md)**.
## SDK tour — one example per block
A walk through **everything** the `tempest-fastapi-sdk` offers: each block has the concept in one line, a minimal runnable example, and a link to the full recipe. Read top to bottom for the mental map, or jump to what you need — install only the extras you use (`uv add "tempest-fastapi-sdk[auth,cache,queue]>=0.171.0"`).
### Foundation
`BaseAppSettings` and `AsyncDatabaseManager` come from the SDK. The `create_app()` factory and `run()` belong to **your** service, not to the package: `tempest new` writes both (`src/api/app.py` and `src/server.py`, whose `run()` delegates to `run_server`).
```python
from tempest_fastapi_sdk import AsyncDatabaseManager, BaseAppSettings
class Settings(BaseAppSettings):
DATABASE_URL: str = "sqlite+aiosqlite:///./app.db"
settings = Settings()
db = AsyncDatabaseManager(settings.DATABASE_URL)
```
See the [Tutorial](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/tutorial.md) and the [Database](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database.md) recipe.
### Schemas and validated fields
`BaseSchema` + self-describing `Annotated` types (money, %, slug, lat/long,
and Brazilian ones: CPF/CNPJ/CEP/phone + **Pix key**).
```python
from tempest_fastapi_sdk import BaseSchema
from tempest_fastapi_sdk.utils import CentsField, PixKeyField, SlugField
class ProductSchema(BaseSchema):
slug: SlugField
price_cents: CentsField # int >= 0
pix_key: PixKeyField # CPF/CNPJ/email/phone/random
```
Recipes: [Validated fields](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/fields.md), [Brazilian helpers](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/br-helpers.md).
### Repository, Service, Controller
`BaseRepository[Model]` (CRUD + bulk ops), `BaseService`, `BaseController`
with `get_by_id`/`list`/`paginate`/`update`/`delete` ready.
```python
from sqlalchemy.ext.asyncio import AsyncSession
from tempest_fastapi_sdk import BaseRepository, BaseService
from src.db.models import UserModel
from src.schemas import UserResponseSchema
class UserRepository(BaseRepository[UserModel]):
def __init__(self, session: AsyncSession) -> None:
super().__init__(session, model=UserModel)
class UserService(BaseService[UserRepository, UserResponseSchema]):
...
```
Recipes: [Tutorial](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/tutorial.md), [Database](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database.md).
### Pagination
Offset and cursor, with a `Link` header.
```python
from tempest_fastapi_sdk import BasePaginationFilterSchema, CursorPaginationFilterSchema
```
### Standardized exceptions
`AppException` + subclasses → the right HTTP status;
`register_exception_handlers(app)`.
```python
from fastapi import FastAPI
from tempest_fastapi_sdk import NotFoundException, register_exception_handlers
app = FastAPI()
register_exception_handlers(app)
raise NotFoundException(message="user not found") # -> standardized 404
```
### Full authentication
Bundled flow: signup/activate/login/reset/**email change and recovery**/MFA
+ JWT deps (header/cookie/query).
```python
from fastapi import FastAPI
from tempest_fastapi_sdk import UserAuthService, make_auth_router
from src.api.dependencies.resources import db
from src.core.settings import settings
from src.db.models import UserModel, UserTokenModel
app = FastAPI()
auth = UserAuthService(user_model=UserModel, token_model=UserTokenModel,
auth_settings=settings, jwt_settings=settings)
app.include_router(make_auth_router(auth, session_factory=db.session_dependency))
```
Recipes: [Auth flow](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow.md), [MFA](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/mfa.md),
[Refresh tokens](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/refresh-tokens.md), [Sessions](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/sessions.md).
### Cache
`AsyncRedisManager` + `@cached` + `CacheInvalidator` (namespace/tag).
```python
from tempest_fastapi_sdk.cache import AsyncRedisManager, cached
from src.core.settings import settings
redis = AsyncRedisManager(settings.REDIS_URL)
@cached(redis, ttl=300, namespace="products", tags=lambda a, k: [f"p:{k['pid']}"])
async def get_product(*, pid: str) -> dict: ...
```
Recipe: [Cache](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cache.md).
### Queues and background tasks
`MessageBroker` (FastStream pub/sub), `TaskQueue` (TaskIQ) + cron via
enum/helpers, both hiding the underlying lib.
```python
from tempest_fastapi_sdk.queue import MessageBroker
from tempest_fastapi_sdk.tasks import CronEnum, CronOffsetEnum, TaskQueue
from src.core.settings import settings
from src.queue import OrderPaid
mq = MessageBroker.rabbitmq(settings.RABBITMQ_URL)
tq = TaskQueue.rabbitmq(settings.TASKIQ_BROKER_URL)
@mq.on("orders.paid")
async def on_paid(event: OrderPaid) -> None: ...
@tq.cron(CronEnum.EVERY_WEEKDAY_9AM, cron_offset=CronOffsetEnum.BRASILIA)
async def digest() -> None: ...
```
Recipes: [Queues and Tasks](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/queue-tasks.md), [Outbox](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/outbox.md).
### Real time
SSE (`EventStream`/`SSEBroker` with backpressure), WebSocket router, Web Push.
```python
import asyncio
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from tempest_fastapi_sdk import EventStream
app = FastAPI()
@app.get("/events")
async def events() -> StreamingResponse:
"""Stream one tick per second until the client disconnects.
Returns:
StreamingResponse: The SSE response. ``on_disconnect`` cancels the
publisher, so it never outlives the connection.
"""
stream = EventStream()
async def pump() -> None:
"""Publish a tick every second."""
while True:
await stream.publish({"tick": True}, event="tick")
await asyncio.sleep(1)
task = asyncio.create_task(pump())
return stream.response(on_disconnect=task.cancel)
```
Recipes: [SSE](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/sse.md), [WebSocket](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/websocket.md),
[Web Push](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/webpush.md), [Real time](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/realtime.md).
### Observability
Structured logging + `/logs`, CPU/RAM/GPU metrics + Prometheus `/metrics`,
request-id, OTel tracing, health + tool-spec.
```python
from fastapi import FastAPI
from tempest_fastapi_sdk import RequestIDMiddleware, make_health_router
from src.api.dependencies.resources import db
app = FastAPI()
app.add_middleware(RequestIDMiddleware)
app.include_router(make_health_router(checks={"db": db.health_check}))
```
Recipes: [Logging](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/logging.md), [Metrics](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/metrics.md),
[Observability](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/observability.md).
### HTTP hardening
Rate limit (sliding window), idempotency, CSRF, CORS, body-size limit,
hardened static files.
```python
from fastapi import FastAPI
from tempest_fastapi_sdk import IdempotencyMiddleware, RateLimitMiddleware
app = FastAPI()
app.add_middleware(RateLimitMiddleware, store=..., max_requests=100, window_seconds=60)
app.add_middleware(IdempotencyMiddleware, store=...)
```
Recipes: [HTTP layer](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http.md), [Idempotency](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/idempotency.md),
[Security](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/security.md).
### Files
`UploadUtils` (local/MinIO), `DownloadUtils`, `FileStoreUtils` (facade),
MinIO/S3 storage, presigned URLs.
```python
import asyncio
from fastapi import UploadFile
from tempest_fastapi_sdk import FileStoreUtils
upload_file: UploadFile = ... # comes from the endpoint signature
store = FileStoreUtils(source="./uploads") # or an AsyncMinIOClient
async def main() -> None:
"""Run this example."""
key = await store.save(upload_file)
asyncio.run(main())
```
Recipes: [File store](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/file-store.md), [Uploads](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/uploads.md),
[Downloads](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/downloads.md), [Storage](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/storage.md),
[Resumable uploads (tus)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/resumable-upload.md),
[Image metadata](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/image-metadata.md).
### Domain extras
Feature flags, audit trail, multi-tenant, offline-first sync, server-side
sessions, typed HTTP client, i18n error envelopes.
```python
from tempest_fastapi_sdk import FeatureFlags, make_flag_dependency
```
Recipes: [Feature flags](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/feature-flags.md), [Audit trail](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/audit-trail.md),
[Multi-tenant](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/multi-tenant.md), [Offline sync](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/offline-sync.md),
[HTTP client](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http-client.md).
### Self-hosted generative AI
Hardware check, local LLM, embeddings, RAG (web + PDF) — all on your own
hardware.
!!! info "Installation"
The core ships with `tempest-fastapi-sdk`. Self-hosted generative AI needs the `[genai]` extra — `uv add "tempest-fastapi-sdk[genai]"` (pulls in `torch`, `transformers`, `accelerate`, `safetensors` and `huggingface-hub`).
```python
import asyncio
from tempest_fastapi_sdk.genai import can_run, TextGenerator
from tempest_fastapi_sdk.genai.rag import PdfReader, build_context
async def main() -> None:
"""Run this example."""
if can_run(model_id="Qwen/Qwen2.5-7B-Instruct").fits:
gen = TextGenerator("Qwen/Qwen2.5-7B-Instruct", quantization="int4")
chunks = PdfReader().chunks("/kb/manual.pdf")
answer = await gen.generate(build_context("how to refund?", chunks))
asyncio.run(main())
```
Recipe: [Self-hosted generative AI](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai.md).
### Long work, with status and cancellable
`JobStore` gives the work a row the screen reads; `run_cancellable` actually
interrupts it when the user gives up. `StageMap` covers the case where the
stages decorate a record the screen already fetches.
```python
import asyncio
from uuid import UUID
from tempest_fastapi_sdk.db import AsyncDatabaseManager
from tempest_fastapi_sdk.tasks import (
BaseJobModel,
JobStore,
StageInterruptedError,
run_cancellable,
)
class JobModel(BaseJobModel):
"""A unit of long-running work."""
__tablename__ = "jobs"
db = AsyncDatabaseManager("sqlite+aiosqlite:///./app.db")
store: JobStore[JobModel] = JobStore(db, model=JobModel)
async def transcribe(path: str) -> str:
"""Long, cancellable work (async I/O).
Args:
path (str): The file to process.
Returns:
str: The text.
"""
await asyncio.sleep(0)
return path
async def run(job_id: UUID) -> None:
"""Run the job, giving up if it is cancelled midway.
Args:
job_id (UUID): The job to run.
"""
if await store.claim(job_id) is None:
return
try:
text: str = await run_cancellable(
transcribe("audio.wav"),
interrupted=store.cancellation_watch(job_id),
)
except StageInterruptedError:
return
await store.succeed(job_id)
print(text)
```
Recipe: [Jobs (long work with status)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/jobs.md).
### Hosted AI, and what it cost
`OpenAICompatGenerator` speaks any `/chat/completions` (DeepSeek, Groq,
OpenRouter, vLLM, Azure); `AIUsageStore` keeps one row per paid call, for
the "which account spent what" question.
```python
import asyncio
from uuid import uuid4
from tempest_fastapi_sdk.db import AsyncDatabaseManager
from tempest_fastapi_sdk.genai import (
AIUsageStore,
BaseAIUsageModel,
OpenAICompatGenerator,
TokenUsage,
)
class AIUsageModel(BaseAIUsageModel):
"""One billed AI call."""
__tablename__ = "ai_usage"
db = AsyncDatabaseManager("sqlite+aiosqlite:///./app.db")
gen = OpenAICompatGenerator(
"deepseek-flash",
api_key="sk-...",
base_url="https://api.deepseek.com",
)
store: AIUsageStore[AIUsageModel] = AIUsageStore(
db, model=AIUsageModel, price_input_per_1k=0.00014
)
async def main() -> None:
"""Run this example."""
text: str
usage: TokenUsage | None
text, usage = await gen.generate_with_usage("Summarize this.")
await store.record(subject_id=uuid4(), service="summary", usage=usage)
print(text)
asyncio.run(main())
```
Recipe: [Self-hosted generative AI](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai.md).
### Admin panel
`AdminSite` + `AdminModel` + `make_admin_router` (Jinja+HTMX, themes,
actions, upload, filters).
Recipe: [Admin panel](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin.md).
### SSR and vision
Typed SSR (`Page`/`html_response`) over `tempestweb`; computer vision
(`Detector`/`Classifier`/`Segmenter`) via `ort-vision-sdk`.
Recipes: [SSR](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/ssr.md), [Vision](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/vision.md).
### CLI and deploy
`tempest new` (scaffold), `tempest db` (migrations), `tempest user`,
`tempest secrets`, quality gates; safe deploy (migrations + graceful
shutdown).
!!! info "The `tempest` gates need the `[cli]` extra"
`lint`, `fix`, `format`, `fmt-check`, `type`, `test`, `check` and
`pr-prompt` come from `[cli]`; with only `[cli-ops]` (the server one),
they exit with code 2 pointing at `[cli]`. Install it with
`uv add --dev "tempest-fastapi-sdk[cli]"` — details in
[Installation → CLI](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/installation.md#cli).
```bash
tempest new my_service && cd my_service
tempest db init && tempest db upgrade
tempest check # ruff + mypy + tests
```
Recipes: [CLI](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli.md), [Safe deploy](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/deploy-safety.md).
### Recap
The SDK covers the whole lifecycle of a FastAPI service: typed foundation
→ persistence → auth → cache → background → real time → observability →
hardening → files → AI → admin → CLI/deploy. Each section above points at
the recipe with the full guide. Start from the [Tutorial](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/tutorial.md) and
come back here to plug in each capability as you need it.
## Recipe index
| Theme | Covers |
| --- | --- |
| **[Admin site »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin.md)** | `AdminSite`, `AdminModel`, `make_admin_router`, `BaseUserModel` |
| **[Admin SQL console »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin-sql-console.md)** | `SqlShellService` + `SqlShellPolicy` (capabilities, allowed/denied tables, row cap, `require_where`), real parsing via `sqlglot`, every attempt audited, opt-in admin page |
| **[AI agents »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents.md)** | `Agent` (goal → trace + artifacts), `AgentBudget` (steps/time/calls), `AgentTool` + ready-made tools over image/vision/audio/RAG, `InMemoryAgentRunSink` / `DbAgentRunSink`, `make_agent_router` |
| **[AI agents (advanced) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-advanced.md)** | typed structured output (`run_structured`), three memory layers (`scratchpad_tools` / `fact_tools` / `recall_prompt`), on-demand `Skill`, `agent_tool` delegation, `run_until` / `refine` |
| **[AI agents (architecture) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-architecture.md)** | how to lay out a service with agents: the `ai` layer beside `services`, `runtime` with one generator per process, `tools` apart from `agents`, `views` and `policy`, the controller that seeds identity, and when to trade one agent for skills |
| **[AI agents (concepts) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-concepts.md)** | the loop step by step, the transcript the model receives on each turn, the vocabulary (step, observation, artifact, budget, `stop_reason`), why the context grows and what that costs, and when to reach for a tool, a skill, delegation or a loop |
| **[AI agents (database) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-db.md)** | a tool that queries the database: `db.get_session_context()` per call, the `from_session` convention, one `AsyncDatabaseManager` per process, and what `AgentContext` carries (`state` with who is asking, `artifacts`, `deadline`) |
| **[AI agents (prompts) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-prompts.md)** | the `src/ai/prompts/` folder (one file per agent + `base.py`), what the model actually receives (system, goal and specs via `ScriptedBackend`), anatomy of a prompt, `DEFAULT_SYSTEM_PROMPT` / `skills_prompt` / `DEFAULT_CRITIC_PROMPT`, per-request prompts with `facts_prompt` (measured cost of building the `Agent`) and how to test the prompt |
| **[AI agents (testing) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-testing.md)** | `ScriptedBackend` / `replies` / `replies_with_tool` to script the model's decisions, `assert_completed` / `assert_used_tools` / `assert_artifact`, `FailingBackend`, and the separate `@model` layer |
| **[AI agents (tools) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-tools.md)** | a tool that calls an API (the process's `httpx.AsyncClient`, a timeout below the budget, 4xx/5xx/timeouts becoming `AgentToolError`, tests with `httpx.MockTransport`), a tool that structures text (`schema_of`, `final_answer_tool`, `ToolResult(final=True)`), `typed_tool` over a bound method and `text_tool` |
| **[Apify (actors and Instagram scraping) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/apify.md)** | async `ApifyClient` with `Authorization: Bearer` and `actor_id` path-traversal checks, `ApifySettings`, `ApifyRequestException`, `InstagramApifyScraper` (`scrape_profile_posts` / `validate_profile`), `extract_instagram_username` / `instagram_profile_url` helpers and `FakeApifyClient` |
| **[App error reports »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/app-errors.md)** | `make_app_error_model` (nullable user FK, `SET NULL`, indexed `created_at`), `AppErrorService` (truncate-never-refuse), opt-in admin listing, half-open date range |
| **[Audit trail »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/audit-trail.md)** | `BaseAuditLogModel`, `add_audited` / `update_audited` / `delete_audited`, `snapshot_model` / `diff_snapshots` |
| **[Auth flow (signup/reset) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow.md)** | `UserAuthService`, `make_auth_router` — signup / activation / login / password reset, token delivery (bearer/cookie/both), `BaseUserModel` |
| **[Brazilian helpers »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/br-helpers.md)** | CPF / CNPJ / CEP / phone validation + normalization, including mobile-only (`is_valid_mobile_phone_br`, `MobilePhoneBRField`) and `parse_phone_br` (area code, number, E.164) |
| **[Cache »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cache.md)** | `AsyncRedisManager` (+ `client_proxy`, for stores built at import time), `@cached` decorator, `CacheInvalidator` (tag/namespace) |
| **[Chat (conversations + messages) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/chat.md)** | `ChatService`, `make_chat_router`, base tables + real-time fan-out via `SSEBroker` |
| **[Choosing a model »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/models.md)** | `TextModelEnum` / `EmbeddingModelEnum` / `RerankerModelEnum` / `VisionModelEnum` / `ImageModelEnum` / `SpeechToTextModelEnum` / `TextToSpeechModelEnum` — named Hub ids and the use-case table behind each pick |
| **[CLI »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli.md)** | `tempest new` / `db` (+ `seed`) / `user` / `secrets rotate` / `lint` / `fix` / `format` / `type` / `test` / `check` |
| **[Comments + ratings »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/reviews.md)** | `ReviewService`, `make_reviews_router`, 0–5 star scores with aggregation, threaded comments |
| **[Complete service (settings, auth, upload, test) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/full-service.md)** | a minimal runnable project: settings composed from the mixins, `sync_schema_async()` in the lifespan, `UserAuthService` + `make_auth_router` (signup / login / `/auth/me`), an upload guarded by `current_user_dependency()` and an end-to-end test |
| **[Computer vision (ONNX) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/vision.md)** | `Detector` / `Classifier` / `Segmenter` + prediction schemas |
| **[Critical-failure alerts »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/alerts.md)** | `AlertNotifier` (one e-mail per defect per window, global ceiling, optional Redis), `make_server_error_alert` in `on_server_error`, `AppErrorService(notifier=)` from `fatal` up, recipients from `.env` or the active admins, redacted body |
| **[Data subject export and erasure (LGPD) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/subject-data.md)** | `SubjectGraph` (the tables a subject's `DELETE` reaches by cascade, derived from `MetaData`), `export` without secret columns, `violations` + `assert_subject_graph_valid` as a CI guard, `SubjectObjectStorage` (per-subject prefix, direct upload with `presign_put` + bounded `read`, batch `delete_all`) |
| **[Database »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database.md)** | `BaseModel`, `AsyncDatabaseManager`, `BaseRepository` (CRUD + filters + bulk), offset/cursor pagination, mixins, `AlembicHelper`, `SlowQueryLogger` |
| **[Downloads »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/downloads.md)** | `DownloadUtils` — `file_response`, `stream`, `build_content_disposition`, path-traversal safe |
| **[Enum columns (safe on both databases) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/enum-columns.md)** | `Mapped[MyEnum]` storing the `value`, native `ENUM` on PostgreSQL and a `CHECK` on SQLite, `enum_column()`, `op.replace_enum` + `sync_enum_types` for the migration autogenerate cannot see |
| **[Errors in OpenAPI (Swagger) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/openapi-errors.md)** | `error_responses`, `@raises`, `TempestAPIRouter`, `ErrorResponseSchema`, `tempest openapi-errors --fix` |
| **[Event sourcing (event store) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/event-sourcing.md)** | `EventStore` (append with `expected_version`, stream reads forwards and backwards, `$all` by position, subscription, snapshots) on SQL (`SqlEventStore`, no new dependency, outbox in the same transaction) or KurrentDB (`KurrentDBEventStore`, `[kurrentdb]` extra), `DomainEvent` + `EventRegistry`, `WrongExpectedVersionException`, `AggregateRepository`, `ProjectionRunner` |
| **[Face recognition »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/faces.md)** | `FaceRecognizer` (detect / embed / compare), `compare_faces`, 16 MB or 191 MB packs, no opencv and no torch |
| **[Fakes (no real provider) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/fakes.md)** | `FakePixProvider`, `FakeCardProvider`, `FakePayoutProvider`, `FakeTextBackend`, `FakeStructuredBackend`, `FakeModerationBackend`, `FakePushDispatcher`, `FakeEmailUtils`, `FakeGeocodingBackend`, `FakePlacesBackend`, `FakeRoutingBackend`, `FakeWebSearchBackend`, `FakeObjectStorageClient` — seams with no credential and no network, steerable (`advance`, `flag`, `fail_next`) and inspectable |
| **[Feature flags »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/feature-flags.md)** | `FeatureFlags`, env/Redis/composite backends, `make_flag_dependency` |
| **[File store (unified) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/file-store.md)** | `FileStoreUtils` — upload + download + presign over a single backend |
| **[Firebase auth (ID token) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/firebase-auth.md)** | `FirebaseAuth`, `FirebaseIdentity`, `FirebaseUserResolver` — verify the ID token a mobile app sends, idempotent initialization, one `code` per failure, `[firebase]` extra |
| **[Fleet traffic (anonymous GPS) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/fleet-traffic.md)** | `TrafficAggregator` (median speed per stretch, k-anonymity, start and end cut, rotating salt), `match_to_roads` (HMM, port of tempest-react-sdk), `RoadGraph` + `road_graph_from_overpass`/`load_road_graph`, `make_traffic_router` (by box + graph tile), matching quality on the real fleet, aggregate only (`MatchQualityOptions` + `make_match_quality_router`), `OffRoadDensity` + `infer_road_candidates` (roads OSM lacks, for review) |
| **[Forms from Pydantic schemas »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/ui-forms.md)** | `form_for` / `form_spec_for` / `render_form`, `parse_form` + `FormResult` (per-field errors, input preserved), `form_dependency` (no `Request` in the route), hidden fields, `UploadFile` uploads, type-to-control mapping, `json_schema_extra={"ui": ...}`, `form_stylesheet` |
| **[Fuzzy matching and cities in text »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/fuzzy-matching.md)** | `normalize_text`, `similarity`, `FuzzyIndex` (trigrams, no dependency), the 5571 IBGE municipalities with code and coordinate, `find_municipalities_in_text` (city and state in a sentence, typos and nicknames included), `search_municipalities`, `parse_trip_intent` (origin, destination, date and period of a trip phrase, transcribed speech included), search by meaning and combined (`SemanticNameIndex`, `HybridNameIndex`), agent tools (`municipality_search_tool`, `name_search_tool`) |
| **[Geolocation (distance + travel time) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/geo.md)** | `haversine_km`, `estimate_travel`, `OSRMBackend`, `NominatimBackend`, `GeoPointMixin` / `GeoRepositoryMixin`, `CachedGeocodingBackend` (pluggable geocoding cache) |
| **[Google Drive (uploads) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/google-drive.md)** | `GoogleDriveUploadStorage` as an `UploadUtils` backend through a service account (JWT bearer over `httpx` + `pyjwt`), resumable upload in 256 KiB pieces with retries, key in `appProperties`, a repeated key replaces the content, `GoogleDriveSettings` |
| **[Google Maps scraper (gosom sidecar) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/gmaps-scraper.md)** | `GmapsScraperClient` (implements `PlacesBackend`, hardened `build_job` with `fast_mode=True`/`email=False` and `max_time >= 180s`, guaranteed `DELETE` in `finally`, `job_id` traversal guard), `parse_gmaps_csv` (`place_id` dedup, all 27 Brazilian UFs and `+55` phones), `GmapsScraperSettings`, `GmapsScraperJobError`, `FakeGmapsScraperClient`, and hardened Docker/Compose |
| **[Host control (files, commands, power) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/hostbridge.md)** | `HostBridge` + `HostBridgeConfig` / `HostBridgeSettings` (power, files, PDFs, commands, native picker), `make_hostbridge_router` with required auth and an opt-in destructive side, sandboxed WSL/Windows paths, and from a container `RemoteHostBridge` + `tempest hostbridge serve` |
| **[Hosted generative AI (Anthropic, OpenAI, DeepSeek, Google) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai-hosted.md)** | `AnthropicGenerator` (Messages API) and `OpenAICompatGenerator` (OpenAI, DeepSeek, Gemini) behind the same protocols as Ollama — `generate`/`chat`/`stream`, `chat_with_tools`, `chat_structured`; `complete_structured` (output + usage + stop reason, images via `image_part`, PDFs via `document_part` + `supports_documents`); `hosted_generator` (provider from the model id, Gemini included); `OpenAICompatEmbedder`; remote transcription and synthesis with `OpenAICompatSpeech` ([Hosted speech](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai-hosted/speech.md): `/audio/transcriptions` and `/audio/speech`, drop-in for `SpeechToText` and `TextToSpeech`); `HostedGenAISettings` + `*_kwargs()` / `hosted_kwargs()`; typed errors (`HostedAuthenticationError`, `HostedRateLimitError`, `HostedServerError`) |
| **[HTTP client (outbound) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http-client.md)** | `HTTPClient` — typed httpx with retry/backoff, circuit-breaker, X-Request-ID; `RetryPolicy`, `CircuitOpenError` |
| **[HTTP layer »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http.md)** | `apply_cors`, `RequestIDMiddleware`, `RateLimitMiddleware` (429 in the SDK error envelope), `make_health_router`, JWT / role / permission dependencies, webhook signature verifier, pagination Link headers, tool-spec router |
| **[Idempotency »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/idempotency.md)** | `IdempotencyMiddleware`, `MemoryIdempotencyStore` / `IdempotencyStore` (Redis) — safe replay of POST/PUT/PATCH/DELETE |
| **[Image generation (local) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/image-generation.md)** | `ImageGenerator` (local diffusers — `generate` / `edit` img2img), `ImageGenerationConfig`, `GeneratedImage` carrying the reproducing seed, `make_genai_router(image_generator=...)` → `POST /image` |
| **[Image metadata »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/image-metadata.md)** | `strip_image_metadata` — re-encodes a user's photo in the same format without EXIF (GPS, device), XMP, IPTC, ICC and text chunks, applies the orientation first, pixel ceiling against decompression bombs, typed errors (`ImageDecodeException`, `ImageTypeMismatchException`, `ImageFormatUnsupportedException`, `ImageTooLargeException`) |
| **[Integration client (OpenAPI) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/openapi-client.md)** | `tempest openapi-client` — Pydantic schemas + a typed client from a third party's spec |
| **[Introspection auth (resource server) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/introspection-auth.md)** | `IntrospectionAuth` — validate an opaque bearer by asking the upstream identity provider |
| **[Jobs (long work with status) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/jobs.md)** | `BaseJobModel` + `JobStore` — one row per unit of work, `claim`/`succeed`/`fail`, `watch` for the screen, `reclaim_stale`; cooperative cancellation (`cancel` + `run_cancellable`); `StageMap` for several stages on the record itself |
| **[Kestra (workflow orchestrator) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/kestra.md)** | trigger a flow from the service (`HTTPClient` + webhook trigger or execution API, tenant path measured), a flow calling a route protected by `make_token_dependency`, and outbox (`OutboxRelay`) + `WebhookInbox` for guaranteed delivery; run against Kestra 2.0.6 |
| **[Layer observability »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/layer-observability.md)** | `@timed` (sync/async, `threshold_ms`, optional OTel spans), `@instrument_layer` (`BaseController`/`BaseService`/`BaseRepository` classes without double-wrapping), `trace_id`/`span_id` in `JSONFormatter`, `layers` summary in `AccessLogMiddleware` (opt-in: `include_layer_timings=True`) |
| **[LinkedIn (OAuth and Posts API) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/linkedin.md)** | `LinkedInOAuthClient` (separate personal vs organization scopes, `exchange_code`, `get_userinfo` with `person_urn`), `linkedin_http_client` (`LinkedIn-Version` + `X-Restli-Protocol-Version: 2.0.0`), `LinkedInClient` (`publish_post` text/article/image reading `x-restli-id`, 2-step `upload_image`, percent-encoded `delete_post`), `LinkedInSettings`, `LinkedInApiException` hierarchy and `FakeLinkedInClient` |
| **[Live location »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/live-location.md)** | `LivePositionSchema`, `LivePositionStore` (latest position in Redis with throttle, least movement, TTL and `clear`; SSE delivery to the `audience` only; per-recipient ETA) and `make_live_position_router` (mandatory `authorize` and `channel_active`) |
| **[Logging »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/logging.md)** | `LogUtils`, structured JSON logging, request-ID propagation |
| **[Management commands (tempest <cmd>) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/management-commands.md)** | register your own commands on the project's `tempest` CLI |
| **[MCP (Model Context Protocol) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/mcp.md)** | serve a `FastMCP` at `/mcp` behind `current_user` (`mount_mcp`), publish `AgentTool`s and picked FastAPI routes as MCP tools (`add_agent_tools`, `add_fastapi_routes`), and use another MCP server's tools in an `Agent` (`MCPToolset`, stdio and HTTP) |
| **[Mercado Pago (Pix, cards, boleto) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/mercado-pago.md)** | `MercadoPagoClient` (132 operations generated from the provider's own OpenAPI, without the discontinued Payments API), `MercadoPagoPixProvider` + `MercadoPagoCardProvider` (Pix and card through the Orders API, a card decline as a result, authorize and capture, partial refunds), `make_mercado_pago_webhook_delivery_dependency` (a webhook that re-reads the order), `AuthenticatedUser`, `to_cents` / `from_cents` (reais, not cents), `make_mercado_pago_webhook_dependency`, `MercadoPagoSettings`, `x_idempotency_key` per call |
| **[Mercado Pago (test accounts and credentials) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/mercado-pago-sandbox.md)** | step by step to create a test seller and find the right token (Checkout Transparente / Orders API), what the payer needs, test cards, and the table of errors each detour produces |
| **[Mercado Pago (testing webhooks) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/mercado-pago-webhooks.md)** | the Orders API and the notification simulated by the SDK (`FakeMercadoPagoOrdersAPI`, `tempest mercado-pago fake-api` / `simulate-webhook`, no network), a signed simulation re-reading a real sandbox order, the dashboard's simulation and a real delivery through a tunnel |
| **[Metrics »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/metrics.md)** | `MetricsUtils` — CPU / RAM / disk / GPU snapshots |
| **[MFA (TOTP / 2FA) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/mfa.md)** | `MFAMixin`, `TOTPHelper`, enroll/confirm/verify/disable endpoints on `make_auth_router`, recovery codes |
| **[Migrations »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/migrations.md)** | `AlembicHelper.sync_schema()` / `adopt()` / `base_revision()` / `has_existing_schema()` — how the schema comes into being, adopting a pre-Alembic database, and why `create_tables()` + `stamp("head")` breaks silently |
| **[Model weights (Hub lifecycle) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/model-weights.md)** | `ModelRef` (`revision` / `local_files_only` / `trust_remote_code`), `resolve_revision`, `download_model` with a disk preflight, `list_cached_models` / `remove_cached_model`, `tempest model pull` / `cache-list` / `cache-rm` |
| **[Modelops (export, bench, quantization) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/modelops.md)** | `benchmark_onnx` (latency/RAM/GPU/energy), `export_onnx_to_ort`, `quantize_onnx_dynamic`, `quantize_hf_onnx`, `rank` + Pareto frontier, `tempest model` |
| **[Multi-tenant »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/multi-tenant.md)** | `TenantScopedRepository` — `tenant_id` isolation on every query |
| **[n8n (workflow automation) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/n8n.md)** | call the Webhook node with `HTTPClient` + Header Auth (immediate response or Respond to Webhook, test vs production URL), the HTTP Request node calling a route protected by `make_token_dependency`, and outbox + `WebhookInbox`; run against n8n 2.43.7 |
| **[Object-level permissions »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/authz.md)** | `permission` (rule decorator), `has_perm` / `check_permission`, `PermissionRegistry`, `make_permission_checker`, `PermissionMixin` |
| **[Observability (tracing) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/observability.md)** | `setup_tracing` (OpenTelemetry), `SlowQueryLogger` |
| **[Offline-first sync (delta) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/offline-sync.md)** | `BaseRepository.changes_since`, `SyncFilterSchema`, `SyncPaginationSchema`, cursor deltas + soft-delete |
| **[Online game rooms (TCP) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/game-rooms-tcp.md)** | `serve_game_rooms_tcp`: the same room protocol on raw TCP, frames `[u32 length][u8 kind][payload]`, `TCP_NODELAY`, ping and drop on silence; same rooms as the WebSocket |
| **[Online game rooms (WebSocket) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/game-rooms-websocket.md)** | `RoomRegistry` + `RoomPolicy` + `make_game_room_router`: rooms by code for multiplayer games, elected host, JSON and binary relay with the sender stamped by the server, version, reconnection with `resume`, limits; `make_jwt_room_identity_resolver` |
| **[OpenPix (Pix via Woovi) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/openpix.md)** | Layered architecture, opening a charge, verified webhook + API read-back, reconciliation, refunds, `OpenPixEnvironmentEnum`, `to_cents` |
| **[OpenPix (subscriptions and plans) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/openpix-subscriptions.md)** | `SubscriptionPayload`, `RECURRENT` vs `PIX_RECURRING` (Pix Automático), lifecycle and instalments, the plan that lives in your database |
| **[PDFs »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/pdf.md)** | Generate: `PdfRenderer`, five bundled documents (receipt/quote/report/contract/voucher) with Pydantic schemas, `make_pdf_router`, `tempest pdf render`, asset policy. Read: `extract_pdf_text`, `read_pdf_pages` (upload through the API, page by page, tables) |
| **[Permission guards (@requires) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/permission-guards.md)** | `@requires` plus `(user) -> user` guards (with an optional `meta: dict[str, Any]` via `meta=` / `include_args=`), `TempestPermissionError`, `GuardContractWarning`, `tempest permissions --check` |
| **[Pix protocol (one contract, many providers) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/pix-protocol.md)** | `PixProvider` (Protocol: `create` / `get` / `cancel` / `parse_webhook`), `PixCharge` / `PixChargeRequest` / `PixPayer` field by field, canonical `PaymentStatusEnum` beside the raw `provider_status`, the six `PixEventTypeEnum`s, `OpenPixPixProvider` and `MercadoPagoPixProvider`, `PixProviderRouter` to migrate provider by slices of orders, `confirm_pix_payment` + `claim_once` to release an order only after reading the charge back, and only once — plus how to write your own adapter, with an in-memory fake for testing without a network |
| **[Pix refunds (idempotent) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/pix-refund.md)** | `PixRefundProvider` (`refund_pix_charge(..., refund_reference=)` + `get_refunded_cents`), `PixRefund`, a retry that is safe after a timeout with no lease of your own, partial refunds, `PixRefundExceedsBalanceException` / `PixRefundReferenceConflictException`, `PixProviderRouter.refund_pix_charge`, how idempotency is guaranteed at Mercado Pago, at OpenPix and in `FakePixProvider` |
| **[Places and POIs (Overpass and Google Places) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/places.md)** | `PlaceSchema`, `PlacesBackend`, `BoundingBoxPlacesBackend`, `OverpassPlacesBackend` (`search_nearby`, `search_bbox`, `fetch_tags` with QL injection guards and `429`/`502`–`504` retries), `GooglePlacesClient` (`search_nearby`, `get_place_details`, `get_place_website`, `google_places_http_client`, `GooglePlacesSettings`), offline parsers and `FakePlacesBackend` |
| **[Push (web + mobile) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/push.md)** | `DeviceService`, `PushDispatcher`, `WebPushTransport` / `FCMTransport`, `BaseDeviceTokenModel`, `make_push_router` — one call for browsers and phones, with unified pruning of dead devices |
| **[QR code with a logo and a frame (ride link) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/qr-logo.md)** | `render_qr` (level `H`, no Micro QR, logo ceiling measured with `zxing-cpp`: up to 35% of the side reads, 40% already fails), `ShareFrameRenderer` (vertical frame for the status and square for a chat: logo, round photo, name, route, QR code, link), routes pointing at the share page |
| **[Query plans (EXPLAIN) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/query-plans.md)** | `explain_queries()` captures the block and explains on exit, `EXPLAIN ANALYZE` on PostgreSQL / `EXPLAIN QUERY PLAN` on SQLite, writes never re-executed, `report.slowest` |
| **[Queue & Tasks »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/queue-tasks.md)** | FastStream (`AsyncBrokerManager`), TaskIQ (`AsyncTaskBrokerManager`), `AsyncTaskScheduler`, transactional outbox |
| **[React SPA on FastAPI »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/react-spa.md)** | `make_spa_router` — serve the Vite build from the same process, with history fallback |
| **[Real-time »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/realtime.md)** | Overview — when to choose SSE, WebSocket or Web Push |
| **[Receiving WhatsApp messages (zap-api) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/zap-inbound.md)** | `make_zap_webhook_dependency` — HMAC over the raw body, `ZapWebhookDelivery` with `inbound` / `status` already parsed by `event`, enums (`ZapWebhookEventEnum`, `ZapInboundMediaTypeEnum`, `ZapJidServerEnum`, `ZapOutboundKindEnum`) to dispatch without loose strings, a full model → repository → service → controller → router layer over `ZapInbox` + mixins (claim, status and send ready-made), `is_forward_transition` against out-of-order callbacks, media via `get_message_media` |
| **[Refresh tokens (rotation/revocation) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/refresh-tokens.md)** | `BaseUserRefreshTokenModel`, `make_user_refresh_token_model`, `issue_token_pair`, rotation + family reuse detection |
| **[Rename environment variables without breaking deploys »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/env-migration.md)** | `DEPRECATED_ENV_ALIASES` (1:1 fallback from process env and `.env` without `AliasChoices`), `DEPRECATED_ENV_CONVERTERS` (`EnvAliasConverter` for conversions such as days → seconds or Redis parts → `REDIS_URL`), conflict detection without leaking values, warning/structured boot log and `ENV_ALIASES_STRICT=true` |
| **[Resumable uploads (tus) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/resumable-upload.md)** | `make_tus_router` (tus 1.0.0 server for `tempest-react-sdk`'s `createResumableUpload`: `POST`/`HEAD`/`PATCH`/`DELETE`, per-owner `Idempotency-Key`, expiry, offset `409` under a per-upload lock), `LocalTusStore` and `S3TusStore` (state that survives a restart), `on_complete` |
| **[RevenueCat (in-app subscriptions) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/revenuecat.md)** | `make_revenuecat_webhook_router` (Authorization header + optional HMAC, empty secret refuses all, records once), `WebhookInbox` + `BaseWebhookEventModel` (idempotent inbox for any provider: claim, effect and mark in one transaction, `max_attempts` → `FAILED`), `normalize` → `SubscriptionSnapshot` over all 21 documented event types, `RevenueCatClient.get_subscriber`, `RevenueCatSettings`, `FakeRevenueCatClient` |
| **[Safe deploys »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/deploy-safety.md)** | `AlembicHelper.safe_upgrade` (blocks DROPs), `GracefulShutdownMiddleware` |
| **[Security »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/security.md)** | `AttemptThrottle`, opaque-token helpers, `HardenedStaticFiles`, security headers |
| **[Self-hosted generative AI »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai.md)** | `probe_hardware` / `can_run`, `TextGenerator`, `Embedder`, RAG (web + PDF), audio (STT/TTS + batching), `make_genai_router`; hosted backend (`OpenAICompatGenerator`, any `/chat/completions`) with `TokenUsage`, cached prefix included; list output (`parse_structured_list`, retry at a rising temperature) and object output (`extract_json_object`); per-user usage accounting (`AIUsageStore`) |
| **[Sentry (secrets out of the event) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/sentry.md)** | `make_sentry_before_send` (redacts JWT, `Bearer`, e-mail and `sk_...` by value, at any depth, in place, writing `[Filtered]`), `RedactionPolicy.redact_in_place` (redaction that keeps tuples, `bytes` and nesting), `SECRET_KEY_PATTERN` |
| **[Server-Sent Events (SSE) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/sse.md)** | `EventStream`, `sse_response`, `ServerSentEvent`, `SSEBroker` (per-channel fan-out, Redis bridge) |
| **[Server-side login and signup »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-pages.md)** | `make_auth_pages_router`, `make_session_user_dependency`, `redirect_to_login` — login, MFA, signup, activation and logout as HTML pages without JavaScript, `SessionAuth` session, per-form CSRF |
| **[Server-side sessions »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/sessions.md)** | `SessionMiddleware`, `SessionAuth`, `make_session_router`, `MemorySessionStore` / `RedisSessionStore` |
| **[Settings (mixins and composition order) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/settings.md)** | the 29 settings mixins with extra, variables and `*_kwargs()`, `BaseAppSettings` last, `.env.example`, `EnvironmentSettings` in production |
| **[Sharing with a preview (Open Graph) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/share-preview.md)** | `make_share_router` (page with escaped Open Graph tags, generic preview for an unavailable item, required absolute URL), `ShareCardRenderer` (1200×630 PNG card with your brand, `ETag`/`304` without redrawing, `?v=` per version), font in Docker |
| **[Slides, answer keys and Markdown to PDF »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/slides.md)** | `parse_slides` + `SlideRenderer` (HTML, PDF, PPTX with notes, DOCX handout, reveal.js Markdown), `SlideVocabulary` for text in another language, `parse_answer_key` + `AnswerKeyRenderer`, `MarkdownPdfRenderer` with the stylesheet as a parameter (`ABNT_MARKDOWN_CSS`), zip with images checked before extraction, Mermaid via `[slides-mermaid]` |
| **[Social login (OAuth2/OIDC) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/oauth.md)** | `AUTH_OAUTH_ENABLED` + `oauth_clients=` (four `/auth/oauth/*` routes), `OAuthSettings`, `make_user_oauth_account_model`, `NameMixin`, `GoogleOAuthClient`, `GitHubOAuthClient`, `OIDCProvider`, `OAuthUser`, `OAuthClient`, `generate_oauth_state` |
| **[Spreadsheets (.xlsx) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/spreadsheets.md)** | `SheetWriter` (row cursor), `Column` (width/mask/alignment), `SheetStyle` as plain data, `BR_*` formats pinned to pt-BR, `new_workbook` / `workbook_to_bytes`; reading `.xlsx` with typed cells (`read_xlsx_as`, `read_xlsx_sheets`) and a public Google Sheet validated into a schema (`read_google_sheet_as`, or the whole workbook with `read_google_sheet_xlsx`) |
| **[SSR (typed pages) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/ssr.md)** | `Page`, `html_response`, `make_htmx_router`, hosting a `tempestweb` build |
| **[SSR actions (confirmation, flash, redirect back) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/ssr-actions.md)** | `form_for(..., confirm=...)` / `confirm()` without inline JS, `FlashMiddleware` + `flash` / `get_flashes` + `FlashMessages` (signed read-once cookie), `redirect_back` against open redirects, `register_html_error_handlers` (error page on GET, flash + 303 on POST, JSON for the API) |
| **[Storage (MinIO/S3) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/storage.md)** | `AsyncMinIOClient`, `MinIOUploadStorage`, `presigned_get_url` / `presigned_put_url`, `list_objects` |
| **[Storage on local disk »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/local-storage.md)** | `LocalObjectStorageClient` (objects in a server directory, atomic writes, the same calls as `AsyncMinIOClient`), links signed to the app's own routes and served by `make_local_storage_router` (`GET` with `Range`, capped `PUT`), `STORAGE_BACKEND=local` + `build_storage_client()` |
| **[Stored file (service mixin) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/stored-files.md)** | `StoredFileServiceMixin` — `set_file` / `replace` / `clear_file` over `UploadUtils` |
| **[Stripe (cards + subscriptions) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/stripe.md)** | `StripeClient`, `stripe_http_client`, `to_minor_units` / `from_minor_units`, `make_stripe_webhook_dependency`, `StripeEvent` — form-encoded writes, idempotency by default, zero-decimal currencies |
| **[System checks (check-config) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/system-checks.md)** | `run_system_checks`, `@check`, `CheckMessage`, `tempest check-config` — validate settings before serving |
| **[tempestweb frontend + SDK »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/tempestweb-frontend.md)** | tempestweb frontend calling the SDK backend: `tempestweb.native.http`, `Idempotency-Key` + `IdempotencyMiddleware`, retry, same origin vs CORS |
| **[Testing »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/testing.md)** | `conftest.py` with the lifespan (`lifespan_context`), signup → login → `/auth/me`, the LLM swapped for a fake, `make_test_session`, `make_test_database`, pytest fixtures |
| **[Text search (LIKE + full-text) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/text-search.md)** | portable `search()` (escaped ILIKE, `AND` across words), `full_text_search()` with `websearch_to_tsquery` + `ts_rank` on PostgreSQL, `TextSearchLanguageEnum` / `TextSearchWeightEnum` / `TokenMatchEnum`, conditions that feed `where=` |
| **[Transactional email »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/email.md)** | `EmailUtils` — SMTP, text/HTML body, attachments, Jinja2 templates |
| **[Transactional outbox »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/outbox.md)** | `BaseOutboxModel`, `OutboxRelay`, `save_with_outbox` — reliable events |
| **[Transactions (commit and savepoint) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/transactions.md)** | session-shared `transaction()`, `commit()` / `flush()` / `rollback()` on the repository, `autocommit=False`, `savepoint()` for the recoverable step |
| **[Transcription pipeline (audio → summary) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/transcription-pipeline.md)** | the three stages stitched together: `StageMap` on the record itself, cancelling a running transcription from inside `on_progress`, `generate_with_usage` + `AIUsageStore` to know who paid, `generate_structured_list` for the stage that returns a list |
| **[Typed CSS (stylesheet and tokens) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/ui-css.md)** | `StyleSheet` / `Rule` / `Media`, `ThemeTokens` (`tempest_core` tokens as CSS variables, light and dark), `make_css_router` with ETag/304 and a versioned URL (`sheet.url()`, `immutable` cache), the font family as a token, `app_stylesheet`, a `cls()` that rejects an unknown class |
| **[Typing (static + runtime) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/typing.md)** | `strict_types` / `typed` / `require_annotations`, `[tool.tempest] typing_strictness` knob, ruff `ANN` |
| **[UI layer (pages and components) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/ui.md)** | the `src/ui/` layer (pages, layout, components, styles), `Page` + inherited `shell()`, `Card` / `Alert` / `DataTable` (with `TableColumn` for a link/form in a cell) / `Pagination` / `EmptyState` / `NavBar`, `Shell` (including `width="full"`) / `Grid`, scaffolding with `tempest new --extras "ssr"` |
| **[Uploads (backends) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/uploads.md)** | `UploadUtils`, extension/MIME validation (`sniff_mime`), local / MinIO backends |
| **[Utilities »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/utilities.md)** | `utcnow`/`to_utc`, `modify_dict`, `get_client_ip`, opaque tokens, `generate_password`, signed URLs (`sign_path`), `form_encode`, `is_light` |
| **[Validated fields (ready-made types) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/fields.md)** | Annotated Pydantic types — `PositiveIntField` / `CentsField` / `PriceField` / `SlugField` / `HexColorField` / `CPFField` / `UFField` |
| **[Versioned artifacts (models) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/artifact-registry.md)** | `ArtifactRegistry`, `ArtifactVersionMixin`, `build_manifest_entries`, `file_digest` — swap the active version without a redeploy |
| **[Wallet and Pix payouts »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/wallet.md)** | `WalletLedger` (credit, debit and reversal in a single `UPDATE`, hold inside the debit, in the caller's transaction), `WalletService` (Pix withdrawal), `WalletBalanceMixin`, `BaseWalletEntryModel`, `claim_once`, `split_net` / `openpix_fee_cents` in basis points, `OpenPixPayoutProvider`, `make_wallet_router` |
| **[Web Push »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/webpush.md)** | `WebPushDispatcher`, VAPID schemas, broadcast with pruning |
| **[WebAuthn / passkeys »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/webauthn.md)** | `WebAuthnService`, `make_web_authn_credential_model`, registration + passwordless login, memory/Redis challenge store |
| **[WebSocket client (AsyncAPI) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/asyncapi-client.md)** | `tempest asyncapi-client` — a typed socket client from an AsyncAPI 3 document |
| **[WebSocket router »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/websocket.md)** | `WebSocketHub`, `make_websocket_router`, `broadcast` / `send_to`, heartbeat, bearer auth |
| **[WhatsApp (zap-api) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/zap.md)** | `ZapClient` over the in-house gateway — 27 generated operations, asynchronous send (`202` + enqueued row), one `idempotency_key` per message, session and pairing QR |
## Complete examples
The recipes show one piece at a time. These pages combine **several** into a flow that runs end to end — read them when you want the integration decisions, not the isolated API.
| Example | What it combines |
| --- | --- |
| **[Full store admin »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/admin-showcase.md)** | audit history + FK autocomplete + inlines + business cards + CSV import + granular RBAC + lenses |
| **[Fullstack web (SSR, WASM, server) »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/fullstack-web.md)** | the three ways to talk to `tempestweb`: SSR + HTMX, WASM SPA and server-mode |
| **[GenAI flows »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/genai-examples.md)** | hardware capacity → local LLM → embeddings/RAG → audio, self-hosted end to end |
| **[Neighborhood marketplace »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/marketplace-local.md)** | geo (nearby sellers, distance/time) + real-time chat + live notifications + star ratings |
| **[Pix checkout »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/integrated.md)** | JWT auth + validated fields (`PixKeyField`) + cache + transactional outbox + `MessageBroker` + `TaskQueue` + SSE + Web Push |
## Anatomy of a recipe
Every recipe follows the same four-section shape so you can skim:
1. **What it solves** — one paragraph in plain language.
2. **When to use it** — bullet list of situations + when *not* to.
3. **The code** — complete, runnable, with `# 1. setup` / `# 2. wire` / `# 3. test` annotations.
4. **Gotchas** — production caveats, security defaults, scaling notes.
If you spot a recipe that doesn't follow this shape, [open an issue](https://github.com/mauriciobenjamin700/tempest-fastapi-sdk/issues/new) — we treat docs regressions like code regressions.
---
# Recipe index
- [Recipes](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/index.md): Recipes index: an SDK tour with one example per building block (auth, cache, queue, AI, admin, CLI) plus the full list of recipes and complete examples.
- [Admin site](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin.md): Use to get a Django-style admin panel under `/admin`; covers what it provides, installation and the index of per-task subpages.
- [Audit history](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin/audit.md): Use to show in the admin who changed what via `audit_model`, recent activity on the dashboard and restoring a version from history.
- [Custom actions](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin/actions.md): Use to add buttons that run your code via `@admin_action`: reveal a secret once, ask for input before running and create through a service.
- [Customize the look — `AdminTheme`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin/theme.md): Use to change the admin colors, logo, favicon, font, radius, footer and dark mode through typed `AdminTheme` parameters.
- [Dashboard: cards, indicators and map](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin/dashboard.md): Use to put business metrics on the admin dashboard: `dashboard_cards`, metric areas with thresholds and a geographic distribution map.
- [Form fields](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin/forms.md): Use to tune the admin form: `choices`, uploads, FK autocomplete, inlines, many-to-many, widgets, password fields and `exclude_fields`.
- [Global search](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin/search.md): Use for admin global search over `search_fields`; covers the per-model limit, what the search respects and the query limits.
- [List view: counts, import and bulk edits](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin/list.md): Use to boost the admin list view: related counts, CSV/XLSX import, duplicate, bulk edit, lenses and counting on large tables.
- [Mount the admin site](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin/setup.md): Use to stand up the admin panel: a `BaseUserModel` user model, registering admin classes or `automap`, the router, session defaults and a custom auth backend.
- [Permissions: RBAC, row scope and impersonation](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin/permissions.md): Use to control who sees and does what in the admin: `access_policy` per model and action, `row_scope` on reads and writes, and `impersonate`.
- [Storage browser — view, preview and edit files](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin/storage.md): Use to view, preview, upload, edit, rename and delete object-storage files from the admin with `StorageBrowserService`.
- [Task panel — what is scheduled and what ran](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin/tasks.md): Use to see the broker schedule and the runs a `JobStore` persisted from the admin, with `TaskPanelService`.
- [Timezone, concurrent edits and language](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin/operator.md): Use to show dates in the operator time zone, block concurrent edits with optimistic locking and switch the admin UI to Portuguese.
- [SQL console in the admin](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/admin-sql-console.md): Use to enable a SQL console in the admin with guardrails: capability policy, deny over allow, auditing, rolled-back reads and a production checklist.
- [AI agents](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents.md): Use to build an AI agent over local models; covers extra per backend, `stop_reason`, budget, typed tools, tool failures, HTTP serving and CPU cost.
- [AI agents (advanced)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-advanced.md): Use when the basic agent is not enough: structured output, three-layer memory, on-demand skills, delegation, criterion and critique loops, and moderation.
- [AI agents (architecture)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-architecture.md): Use once you outgrow one agent: folder layout with `runtime.py`, tools, schemas, views, `policy.py` and prompts, import direction, endpoint and auditing.
- [Agents: how they work inside](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-concepts.md): Use before designing an agent: the loop internals, what the model sees, context cost, budgets, when to use a tool, skill or delegation, and failure modes.
- [AI agents (database)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-db.md): Use when an agent tool queries the app database: a session per call, commit in the context manager, one manager per process and the `context` parameter.
- [AI agents (prompts)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-prompts.md): Use to organize agent system prompts: the `prompts/` folder, anatomy, what the SDK already injects, per-request prompts, what to avoid and how to test.
- [Testing and validating an agent](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-testing.md): Use to test an agent without relying on the model: minimal test, error recovery, budget, skills, memory, backend outage and when to use the real model.
- [AI agents (tools)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/agents-tools.md): Use to write agent tools that call an external API or structure free text; covers `@tool`, `typed_tool`, `text_tool`, `schema_of` and `final_answer_tool`.
- [Apify (actors and Instagram scraping)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/apify.md): Use to run Apify actors asynchronously and scrape Instagram profiles and posts; covers ApifyClient, ApifySettings, InstagramApifyScraper and FakeApifyClient.
- [App errors: when the client breaks in the user's hand](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/app-errors.md): Use to collect error reports from the client app (mobile/web); covers the table, the public endpoint, truncation, `user_id` from the token, filtered listing and rate limit.
- [Audit trail](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/audit-trail.md): Use to record an append-only create/update/delete history in the same transaction; covers `BaseAuditLogModel`, `add_audited`, `update_audited`, actor, origin and `columns=`.
- [Bundled auth flow (signup / activate / login / reset)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow.md): Index of the local-account flow (signup, activation, login, reset) with `UserAuthService` and `make_auth_router`; maps each task to its subpage, plus security and recap.
- [Backend only: from signup to a protected route](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/backend-only.md): Use to test signup, activation, login and a protected route without a frontend (curl, Swagger, mobile); covers a one-file app, dev `.env` and the cycle in a test.
- [Change and recover an email](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/email-change.md): Use to change the email while logged in, re-verify the current one, recover an account with a lost inbox and renew the session with the refresh token.
- [Email disabled and SMTP down](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/email-failures.md): Use to know what each auth route answers with `EMAIL_ENABLED=false` or SMTP down, and when to use `AUTH_SEND_EMAILS_IN_BACKGROUND`.
- [Emails: anatomy, brand and templates](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/emails.md): Use to understand token, link and template in account emails, apply your brand and override the Jinja2 templates; covers the context variables and an example.
- [Endpoints](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/endpoints.md): Look up every auth-flow endpoint with payload and behaviour; covers closed systems, admin-created accounts, extra signup fields and attempt limits.
- [Five operating modes and local SMTP](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/modes.md): Use to pick among the five flow modes (production, local SMTP, no SMTP, CI, backend-only) and run Mailhog or smtp4dev with docker-compose.
- [Get the `current_user` from the request](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/current-user.md): Use to inject the authenticated user into your routes via `current_user_dependency()`; covers header/cookie/query order, `soft=True` and guards in the service.
- [Language of emails, pages and `/docs`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/i18n.md): Use to set the language (pt-BR/en-US) of auth emails and pages, store the user's preference, translate templates and choose the `/docs` language.
- [Minimum setup and `UserTokenModel`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/setup.md): Use to wire the auth flow from scratch: `[auth]`/`[email]` extras, `AsyncDatabaseManager`, `EmailUtils`, `UserAuthService`, `make_auth_router` and `UserTokenModel`.
- [Re-send activation and recover a password](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/recovery.md): Use when the activation email never arrived, the user forgot the password or wants to change it while logged in; covers re-send, password reset and logged-in change.
- [Settings: environment variables](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/settings.md): Look up the auth flow's environment variables by typed group: JWT, password, email, TTL, URLs, pages, language, token delivery, OAuth and deactivated accounts.
- [Token delivery: bearer, cookie or both](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/token-delivery.md): Use to decide whether the JWT pair goes in the body (bearer), in a cookie or both with `AUTH_TOKEN_DELIVERY`; covers cookie mode and both mode.
- [Your product's error codes](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-flow/errors.md): Use to replace the auth flow's error codes with the ones your clients already handle, via `AuthExceptions`, without overriding methods.
- [Brazilian helpers](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/br-helpers.md): Use to validate and normalize Brazilian data: CPF, CNPJ, phone, CEP, state and city, money in reais, plus `utcnow`, `to_utc` and `modify_dict`.
- [Cache](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cache.md): Use to cache expensive data in Redis; covers `AsyncRedisManager`, the `@cached` decorator, tag/namespace invalidation, cache-aside and negative caching.
- [Chat (conversations + messages)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/chat.md): Use to add chat with conversations and messages; covers the base tables, `ChatService` (replies, receipts, attachments, reactions, groups), `make_chat_router` and SSE.
- [Choosing a model](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/models.md): Use to pick an AI model through an enum instead of a string id; covers `TextModelEnum`, `EmbeddingModelEnum`, rerank, vision, image and audio, plus e5 role prefixes.
- [CLI](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli.md): Index of the `tempest` CLI (`[cli]` and `[cli-ops]` extras): scaffold a service and run quality gates; maps each command-line task to its subpage.
- [Docker: compose and Dockerfile](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/docker.md): Use to generate `docker-compose.yaml` from the extras (with a `prod` profile and migrations), regenerate it in an existing project and generate the app Dockerfile.
- [Install and scaffold a service](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/new-service.md): Use to choose between `[cli-ops]` and `[cli]`, scaffold a new service with `tempest new` and bring layers or an old project to the standard with `tempest generate`.
- [Integrations, agents and the OpenAPI contract](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/integrations.md): Use to generate integrations and OpenAPI clients, simulate Mercado Pago, operate agents, export the OpenAPI contract and draft a PR description with `tempest pr-prompt`.
- [Layer rules: `tempest lint-layers`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/lint-layers.md): Look up every architecture rule `tempest lint-layers` enforces (router, service, imports, file size, test suite), with its code, warning or error, and the fix.
- [Quality gates and `tempest check`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/quality.md): Use to run the quality gates (ruff, mypy, pytest) from the CLI and know which SDK steps `tempest check` runs, including `lint-schemas`.
- [Queue, email, storage, flags, cache, models and doctor](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/ops.md): Use to operate infrastructure from the CLI: queue and tasks, email test, object store, feature flags, cache, models and diagnostics with `tempest doctor`.
- [Routes, OpenAPI errors and permissions](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/routes-openapi.md): Use to list routes, bundle a route for an AI (`tempest bundle-route`), document errors in OpenAPI and audit permission guards.
- [Schema metadata: `tempest lint-schemas`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/lint-schemas.md): Use to require `title`, `description` and `examples` on schema fields that reach `openapi.json`, with the `tempest lint-schemas` command.
- [Serve, console and database](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/run.md): Use to run the service (`tempest serve`), open the console (`tempest shell`) and operate the database with `tempest db`: squash, backup, restore, drift and seed.
- [Users and secrets](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/users-secrets.md): Use to create and manage users from the CLI (password, MFA reset, deactivate) and generate, fill in and rotate `.env` secrets, including VAPID keys.
- [Comments + ratings](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/reviews.md): Use to add threaded comments and 0-to-5-star ratings to any entity without a table per type; covers `BaseCommentModel`, `BaseRatingModel`, the service and the router.
- [Fullstack web — SSR, WASM and server](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/fullstack-web.md): Use to build a fullstack tempestweb app in typed Python; three complete projects: SSR + HTMX, a Pyodide WASM SPA and WebSocket/SSE server mode.
- [GenAI examples — complete flows](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/genai-examples.md): Use to see complete self-hosted GenAI flows: load a model only if it fits, RAG over PDFs, SearXNG web grounding, a local voice assistant and a transcription endpoint.
- [Integrated example — a complete shop admin](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/admin-showcase.md): Use to see the admin panel features combined in one store app: audit history, FK autocomplete, inlines, cards, CSV import and SSE + Web Push alerts.
- [Integrated example — neighbourhood marketplace](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/marketplace-local.md): Use to see a neighborhood marketplace with the newer modules: nearby sellers via geo, real-time chat, star ratings and live notifications.
- [Integrated example — Pix checkout](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/integrated.md): Use to see an end-to-end Pix checkout: JWT auth, `@cached` pricing, outbox in the same transaction, background email and SSE + Web Push notification.
- [Complete service: settings, migrations, auth, upload and a test](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/full-service.md): Use to build a whole running service: settings from mixins, migration at startup, signup and login, a protected upload and an end-to-end test.
- [Computer vision (ONNX)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/vision.md): Use to expose ONNX detection, classification and segmentation as an API; covers response schemas and mappers, a combined graph, accepted inputs and `make_vision_router` with limits.
- [Critical-failure alerts: the admin knows before the user complains](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/alerts.md): Use to e-mail the admins when the API answers 5xx or the app crashes; covers settings, deduplication, the per-window ceiling, recipients from .env or the database, and redaction.
- [Data subject export and erasure (LGPD)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/subject-data.md): Use to fulfil LGPD/GDPR data-subject export and erasure requests; covers a schema built for deletion, a CI guard, exporting and erasing rows and files, and uploads under the subject prefix.
- [Database](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database.md): Index of the database layer (SQLAlchemy 2.0 async, PostgreSQL/SQLite): model, connection, repository, filters, bulk, mixins, pagination, migrations and slow queries.
- [1. The base model](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database/models.md): Use to declare tables with `BaseModel`: free columns, centralized table names, the constraint naming convention, composite uniques and `get_table_name()`.
- [2. Connect to the database](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database/connection.md): Use to open the engine and sessions with `AsyncDatabaseManager`: per-request session, lifespan, health check, use outside a request and SQLite with WAL and foreign keys.
- [3. The repository](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database/repository.md): Use for async CRUD with `BaseRepository`: direct or subclass mode, constraint errors, eager-loading, signals and `F`/`Q` expressions.
- [4. Convention-based filters](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database/filters.md): Use to filter in the repository with `field__operator`; covers when a key or value is refused, how pagination inherits operators and the page-size wire name.
- [5. Bulk operations](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database/bulk.md): Use to write many rows at once through the repository, keeping or bypassing the unit of work, including idempotent inserts with ON CONFLICT DO NOTHING.
- [6. Soft-delete and auditing (mixins)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database/mixins.md): Use to add soft-delete (`SoftDeleteMixin`), `created_by`/`updated_by` and the user's preferred language to a model with opt-in mixins.
- [7. Pagination](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database/pagination.md): Use to paginate in the repository by offset (page 3 of 12) or by cursor (large tables) and restrict sortable columns and page size.
- [8. Alembic migrations](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database/migrations.md): Use for migrations with `AlembicHelper`: bootstrap, generate and apply revisions at startup, block schema drift in CI and migrate constraints from the old convention.
- [9. Detect slow queries](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database/slow-queries.md): Use to log every query above a threshold with `SlowQueryLogger`, a listener attached to the engine at boot.
- [Adopt an existing schema](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database/existing-schema.md): Use to adopt the SDK on a database already in production: integer keys, naive UTC timestamps, tables without is_active, and integer-keyed CRUD layers.
- [Downloads](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/downloads.md): Use to serve files with `DownloadUtils` from local disk or MinIO/S3; covers path traversal, streaming bytes, `Content-Type` and `Content-Disposition`.
- [Enum columns (safe on both databases)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/enum-columns.md): Use when mapping an enum to a column: what the SDK changes in SQLAlchemy defaults, `CHECK`, Postgres ENUM type and how to migrate, rename and downgrade.
- [Errors in OpenAPI (Swagger / ReDoc)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/openapi-errors.md): Use to document each route's error `code` values in Swagger; covers `code` on the exception, `error_responses`, `@raises` with `TempestAPIRouter` and `tempest openapi-errors --check`.
- [Event sourcing (event store)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/event-sourcing.md): Use to store facts instead of state; covers `SqlEventStore` and `KurrentDBEventStore`, optimistic concurrency, outbox, projections and aggregates.
- [Face recognition](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/faces.md): Use to detect faces and compare whether two photos show the same person with `FaceRecognizer`; includes the LGPD warning, model packs and measured margin.
- [Fakes: run the whole flow with no provider at all](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/fakes.md): Use to run and test the service with no real provider: fakes for Pix, card, email, text model, structured output, geo and files, and how to wire them.
- [Feature flags](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/feature-flags.md): Use to toggle features without redeploying with `FeatureFlags`; covers memory, env and Redis backends and the dependency that gates routes.
- [File on the service — `StoredFileServiceMixin`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/stored-files.md): Use when an entity holds one storage key (avatar, attachment); covers `StoredFileServiceMixin` with `set_file`, `file_url`, `file_urls` and `clear_file`, and multiple fields.
- [Firebase auth (ID token)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/firebase-auth.md): Use to verify the Firebase ID token sent by the app with `FirebaseAuth`; covers credentials, per-`code` errors, the soft variant, `check_revoked` and tests.
- [Fleet traffic (anonymous GPS)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/fleet-traffic.md): Use to derive per-segment traffic and roads missing from the map out of fleet GPS positions; covers `match_to_roads`, `TrafficAggregator` and privacy rules.
- [Forms from Pydantic schemas](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/ui-forms.md): Use to generate an accessible HTML form from a Pydantic schema; covers per-type mapping, per-field tweaks, reading submissions, `form_dependency` and file uploads.
- [Fuzzy matching and cities in text](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/fuzzy-matching.md): Use to match typed text against known names and find cities in text; covers `FuzzyIndex`, `parse_trip_intent`, semantic search and an agent tool.
- [Geolocation (distance + time)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/geo.md): Use for distance, travel time, routes and geocoding without a paid API; covers Haversine, OSRM, radius search in the database, geofencing and Brazil CEP/UF.
- [Google Drive (uploads)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/google-drive.md): Use to store uploads in a Google Drive folder or Shared Drive via a service account with `GoogleDriveUploadStorage`, from Cloud Console setup to errors.
- [Google Maps scraper (gosom sidecar)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/gmaps-scraper.md): Use to run a hardened gosom/google-maps-scraper Docker sidecar and fetch POIs via GmapsScraperClient, GmapsScraperSettings, PlacesBackend and FakeGmapsScraperClient.
- [Host control (files, commands, power)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/hostbridge.md): Use when a service in WSL must act on its host: read files, run commands and control power, exposed through `make_hostbridge_router`.
- [Hosted generative AI (Anthropic, OpenAI, DeepSeek, Google)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai-hosted.md): Use to generate with Anthropic, OpenAI, DeepSeek or Google over their APIs: keys, tools, structured output, PDF, embeddings and provider failures.
- [Hosted speech: remote transcription and synthesis](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai-hosted/speech.md): Use to transcribe and speak on an OpenAI-wire server (tempest-ai, OpenAI): OpenAICompatSpeech with transcribe and synthesize, voice cloning and errors.
- [HTTP client (outbound)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http-client.md): Use to call external services with `HTTPClient` over httpx: retry with backoff, circuit breaker, timeouts, `X-Request-ID` and `async_retry`.
- [HTTP layer](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http.md): Index of the inbound HTTP layer: points to the subpage for bootstrap, JWT, auth, rate limiting, body and cache, webhooks, upload and extras.
- [App bootstrap and the error envelope](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http/bootstrap.md): Use to create the app with `create_app`, get liveness/readiness, put every 4xx and the 422 in the error envelope, notify failures and localize messages.
- [Body size limit and HTTP cache (ETag / 304)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http/body-cache.md): Use to refuse a large body with 413 before parsing and answer 304 with ETag without mixing authenticated requests.
- [End-to-end authentication](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http/auth.md): Use to see signup, login and a protected route with `PasswordUtils` and `JWTUtils` in one example.
- [File upload and transactional email](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http/upload-email.md): Use for an avatar endpoint with validation and cleanup and a password-reset flow with `EmailUtils`.
- [JWT bearer, current user and role dependencies](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http/jwt.md): Use to guard routes by token, role and permission, with the `JWTUtils` built in `create_app`.
- [Pagination links, tool-spec, server and settings](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http/extras.md): Use to emit the pagination `Link` header, expose `/tool-spec`, start uvicorn with `run_server` and compose settings from mixins.
- [Rate limiting (middleware and per route)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http/rate-limit.md): Use to limit requests by IP, user, tenant or plan, with state in Redis, token bucket, `RateLimit-*` headers and a limit on a single route.
- [Webhooks: verify and send](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/http/webhooks.md): Use to validate incoming signed webhooks (HMAC or RSA) and deliver outgoing webhooks with `WebhookSender`.
- [Idempotency](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/idempotency.md): Use to make POST retries safe with `Idempotency-Key`; covers `IdempotencyMiddleware`, per-caller scoping, in-memory and Redis setups, the client and a custom backend.
- [Image generation (local)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/image-generation.md): Use to generate images locally with diffusion via `ImageGenerator`; covers turbo vs full config, seeds, img2img, an HTTP route, freeing the GPU, `pipeline_kwargs` and the scheduler.
- [Image metadata — cleaning a user's photo](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/image-metadata.md): Use to strip GPS, device and EXIF thumbnail data from uploaded photos before storing; covers a clean upload route, what is kept, errors, the pixel cap and re-encode quality.
- [Integration client from an OpenAPI spec](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/openapi-client.md): Use to generate a typed client and Pydantic schemas from a third party's OpenAPI; covers the output, options, authenticated or YAML specs, coverage and gate-clean code.
- [Introspection auth (resource server)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/introspection-auth.md): Use when your service is a resource server validating opaque bearers upstream; covers `IntrospectionAuth`, `get_claims`, `audiences`, caching, custom claims and testing.
- [Jobs — long work with a status](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/jobs.md): Use to give queued long-running work a visible status; covers the job table, worker, polling, recovering jobs from dead workers, listing, cancelling, progress and stages.
- [Kestra (workflow orchestrator)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/kestra.md): Use to integrate a service with Kestra in both directions; covers running Kestra, service routes, YAML flows, triggering via `HTTPClient` and guaranteed delivery with outbox and inbox.
- [Layer observability](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/layer-observability.md): Use to measure time per layer (controller, service, repository); covers @timed, @instrument_layer, trace_id/span_id in JSONFormatter, and the opt-in layers summary in AccessLogMiddleware.
- [LinkedIn (OAuth and Posts API)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/linkedin.md): Use to automate LinkedIn publishing: OAuth 2.0 with separate personal vs organization scopes, Posts API, image uploads, typed exceptions and FakeLinkedInClient.
- [Live location](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/live-location.md): Use for live driver or courier positions; covers a ride-sharing example, `LivePositionSchema`, `LivePositionStore`, `audience`, ETA and `make_live_position_router`.
- [Logging](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/logging.md): Use to set up JSON logs carrying the request ID; covers `configure_logging`, per-level files, rotation, data redaction, `make_logs_router` and `AccessLogMiddleware`.
- [Management commands (project `tempest `)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/management-commands.md): Use to register your own commands in the `tempest` CLI, like Django's `manage.py`; covers the `src/commands.py` convention, custom location, collisions and nested groups.
- [MCP (Model Context Protocol)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/mcp.md): Use to expose service tools over MCP or consume another MCP server in an `Agent`; covers `mount_mcp`, auth, sessions, `add_agent_tools`, `add_fastapi_routes`, tools over a controller and stdio.
- [Mercado Pago: charging on Brazil's most-used gateway](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/mercado-pago.md): Use to charge through Mercado Pago (Pix, card, Checkout Pro and Transparent); covers `MercadoPagoClient`, amounts in reais, webhook verification and re-reading the order.
- [Mercado Pago: test accounts and credentials](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/mercado-pago-sandbox.md): Use to get Mercado Pago test credentials that actually work; covers the step-by-step seller account, application, Access Token, test cards, Pix and common errors.
- [Mercado Pago: testing webhooks](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/mercado-pago-webhooks.md): Use to test Mercado Pago webhooks at four levels, from offline simulation to real delivery; covers `make_mercado_pago_router`, `MercadoPagoSimulator` and manual payouts.
- [Metrics](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/metrics.md): Use to expose Prometheus HTTP and business metrics or inspect host CPU, RAM, disk and GPU; covers `PrometheusMiddleware`, `BusinessMetrics` and `MetricsUtils`.
- [MFA / 2FA with TOTP (Authenticator)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/mfa.md): Use to enable TOTP 2FA in the SDK auth flow; covers `MFAMixin`, recovery codes, the four endpoints, two-step login, MFA-gated routes, attempt limits and reset.
- [Migrations](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/migrations.md): Use to create and evolve the schema with Alembic; covers `AlembicHelper.sync_schema`, readiness probes, adopting or repairing a database, SQLite FKs and why to avoid `create_tables()`.
- [Model weights (Hub lifecycle)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/model-weights.md): Use to manage model weights on the HuggingFace Hub; covers the cache, pinning a revision, downloading before serving, disk checks, offline mode, cache cleanup and `ModelRef`.
- [Modelops (export, bench, quantization)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/modelops.md): Index of the `modelops` module to quantize, measure and export models; covers extras installation and the table pointing to each task subpage.
- [Export scikit-learn and `.pkl`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/modelops/sklearn.md): Use to export scikit-learn, including from a `.pkl`, to ONNX or the runtime-free compact format; covers GPU, pinning the release hash and what the format refuses.
- [Fuse, `.ort`, inspect, API and CLI](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/modelops/formats.md): Use to fuse a detector and a classifier into one `.onnx`, convert to `.ort`, optimize the graph and inspect without running; covers the report via an API and the CLI.
- [Know whether the model still works](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/modelops/monitoring.md): Use to detect model drift in production without labels; covers the three signals, a training baseline, PSI, constant memory and exposure over HTTP and Prometheus.
- [Measure: time, CPU, GPU, RAM, energy and comparison](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/modelops/measure.md): Use to measure before optimizing with `tempest model bench`; covers timing any callable, sampling CPU, GPU, RAM and energy and ranking models by score and Pareto.
- [Playbook: where time and bytes go](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/modelops/playbook.md): Look up to decide where to optimize a model from measurements; covers estimator choice, transport cost, monitoring cost, cold start and the order of attack.
- [Quantize (dynamic, static and HuggingFace)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/modelops/quantize.md): Use to quantize an ONNX model dynamically or statically with calibration; covers optimizing and quantizing a HuggingFace export without depending on `optimum`.
- [Serve at the edge and publish the bundle](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/modelops/edge.md): Use to serve the model at the edge on GPU or over HTTP and swap it without a redeploy; covers the edge bundle with its manifest and what is worth optimizing, measured.
- [Start here](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/modelops/start.md): Use on first contact with `modelops`; covers a runnable example on a bundled scikit-learn dataset, a guide to finding your case and the module's basic vocabulary.
- [Multi-tenant (TenantScopedRepository)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/multi-tenant.md): Use to isolate tenants in a shared schema without forgetting the filter; covers `TenantScopedRepository`, the tenant column and blocked cross-tenant reads and writes.
- [n8n (workflow automation)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/n8n.md): Use to integrate a service with n8n in both directions; covers running n8n, credentials, workflows, Webhook node auth, test vs production URLs and guaranteed delivery via outbox.
- [Object-level permissions](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/authz.md): Use for object-level authorization (may this user edit this order?); covers rule registration, route protection, async handlers, bypass, fallback and `user.has_perm`.
- [Observability (tracing + slow queries)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/observability.md): Use to find where a request spends its time; covers distributed tracing with OpenTelemetry, sampling, collector-less mode and `SlowQueryLogger` with EXPLAIN in dev.
- [Offline-first sync (delta)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/offline-sync.md): Use to sync offline-first mobile apps or PWAs by delta, deletions included; covers `BaseRepository.changes_since`, idempotent push, pull, the endpoint and the watermark protocol.
- [Online game rooms (TCP)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/game-rooms-tcp.md): Use when the game client speaks raw TCP instead of WebSocket; shows the room server over TCP frames next to the WebSocket one and the Android client.
- [Online game rooms (WebSocket)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/game-rooms-websocket.md): Use to build a WebSocket multiplayer game room server with `tempest_fastapi_sdk.rooms`; covers the protocol, lockstep, host authority, reconnection and latency.
- [OpenPix (Pix via Woovi)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/openpix.md): Use to charge one-off Pix via OpenPix and release the paid order; covers checkout with a BR Code, verified webhooks, reconciliation, refunds, cents and offline testing.
- [OpenPix (subscriptions and plans)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/openpix-subscriptions.md): Use for recurring billing on OpenPix; covers creating a subscription, `RECURRENT` vs `PIX_RECURRING`, receiving each cycle, lifecycle, changing the amount and your local state.
- [PDFs](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/pdf.md): Use to issue and read PDFs; covers typed payloads, five ready documents, an HTTP route, the CLI, custom templates, security, system libraries, reproducible output and page reading.
- [Permission guards (`@requires`)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/permission-guards.md): Use to enforce authorization invariants before a function runs with `@requires`; covers writing guards, type narrowing, `code`, metadata, `include_args` and `tempest permissions`.
- [Pix protocol: one contract, many providers](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/pix-protocol.md): Use to charge Pix without coupling the service to a provider (OpenPix, Mercado Pago); covers `PixChargeRequest`, `PixCharge`, swapping providers, architecture, states, webhooks and adapters.
- [Pix refunds (idempotent)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/pix-refund.md): Use to refund Pix with safe retries and no double refunds; covers `PixRefundProvider`, partial refunds, the provider router and how each provider guarantees idempotency.
- [Places and POIs (Overpass and Google Places)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/places.md): Use to query POIs with OverpassPlacesBackend (OSM) or GooglePlacesClient (Google Places v1) over PlacesBackend; covers PlaceSchema, Place Details, settings and FakePlacesBackend.
- [Push (web + mobile in one flow)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/push.md): Use to notify web and mobile in a single flow; covers the device table, Web Push and FCM transports, pruning rejected tokens, fan-out, testing and FCM disabled.
- [QR code with a logo and a frame (ride link)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/qr-logo.md): Use to generate a QR code with a logo and a shareable frame; covers how much logo fits at level `H`, the frame with photo and route and the routes for a ride link.
- [Query plans (EXPLAIN)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/query-plans.md): Use to understand why an endpoint is slow via EXPLAIN; covers `explain_queries`, what each database returns, writes never re-run and how to read the report.
- [Queues and Tasks](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/queue-tasks.md): Index of queues and background tasks over FastStream and TaskIQ; covers when to use `MessageBroker`, `TaskQueue`, scheduling or outbox and the subpage table.
- [Background tasks with `TaskQueue`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/queue-tasks/tasks.md): Use to move slow work out of the request with `TaskQueue`; covers enqueueing, `enqueue_by_name`, worker resources via `on_startup`/`on_shutdown` and class-based tasks.
- [Event-path reliability](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/queue-tasks/events-reliability.md): Use to stop losing events that fail in the consumer; covers dead-letter, broker-delayed retry, metrics, prefetch, idempotency and tracing through the queue.
- [Messaging with `MessageBroker`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/queue-tasks/broker.md): Use to publish and consume events by channel with `MessageBroker`; covers class-based consumers and publishers and Kafka with key, group, commit and `KafkaSettings`.
- [Periodic tasks: `cron` and `interval`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/queue-tasks/periodic.md): Use to schedule periodic tasks on the same `TaskQueue`; covers `cron`, `interval` and the `CronEnum`, `CronOffsetEnum` and `WeekdayEnum` helpers so you skip raw cron.
- [Queue topology with `QueueSpec`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/queue-tasks/topology.md): Use when the RabbitMQ queue needs declared topology via `QueueSpec`; covers the required exchange, per-consumer fan-out, replaying the dead-letter queue and rejected fields.
- [Task reliability and observability](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/queue-tasks/tasks-reliability.md): Use to add reliability to background tasks; covers typed `RetryPolicy`, dead-letter for terminal failures, per-task Prometheus metrics and the admin dead-letter panel.
- [Transport from settings and the outbox](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/queue-tasks/from-settings.md): Use to pick the queue transport in one line with `TaskQueue.from_settings` and publish atomically with the `INSERT` through the transactional outbox.
- [Workers, healthcheck and scheduler in production](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/queue-tasks/production.md): Use to run the TaskIQ worker and scheduler in production; covers file-based healthcheck, the checker, `docker-compose.yml` and lifespan scheduling with a single-replica lease.
- [A React SPA inside FastAPI](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/react-spa.md): Use to serve a React (Vite) SPA from the FastAPI process in one deployment; covers the dev proxy, `make_spa_router` with CSP, auth with `tempest-react-sdk` and a multi-stage Dockerfile.
- [Real-time](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/realtime.md): Real-time index: use to choose how to push data to clients without polling; points to the SSE recipe (page open) and the Web Push recipe (page closed).
- [Receiving WhatsApp messages (zap-api)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/zap-inbound.md): Use to receive WhatsApp messages and status updates from the zap-api gateway; covers `make_zap_webhook_router`, `make_zap_inbox_router` with `ZapInbox` in the background and tests without the gateway.
- [DB-backed refresh tokens (rotation + revocation)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/refresh-tokens.md): Use to swap the stateless JWT refresh token for an opaque DB-backed one; covers setup with `refresh_token_model`, rotation, reuse detection, revoking logout and the service directly.
- [Rename environment variables without breaking deploys](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/env-migration.md): Use to rename or convert environment variables without breaking deploys; covers DEPRECATED_ENV_ALIASES, DEPRECATED_ENV_CONVERTERS, conflict detection and ENV_ALIASES_STRICT.
- [Resumable uploads (tus)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/resumable-upload.md): Use to accept uploads that resume where they stopped (tus protocol) with `make_tus_router`; covers `on_complete`, ownership, `Idempotency-Key`, `S3TusStore`, expiry, limits and CORS.
- [RevenueCat (in-app subscriptions)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/revenuecat.md): Use to receive RevenueCat in-app subscription webhooks; covers header and HMAC authentication, an idempotent inbox, `normalize` into state and reconciliation through the API.
- [Safe deploys (migrations + graceful shutdown)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/deploy-safety.md): Use before deploying: `safe_upgrade` blocks destructive migrations, `DatabaseBackup` runs pg_dump and graceful shutdown drains requests on `SIGTERM`.
- [Security](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/security.md): Use to harden the service; covers `AttemptThrottle` against brute force, JWT `typ`, opaque tokens, hardened static files, `CSRFMiddleware`, cookies, client IP and `HoneypotBanMiddleware`.
- [Self-hosted generative AI](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai.md): Index of self-hosted generative AI on your own hardware: points to the subpage for each task (hardware, text, audio, RAG, chat, memory, operations).
- [AI chat pipeline](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/chat.md): Use to assemble the full chat (history, memory, tools) with `AIChatPipeline`, the ready `make_ai_chat_router` endpoint and streaming.
- [Audio: STT and TTS](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/audio.md): Use to transcribe audio (STT) and generate speech (TTS), and to pick the language and voice model by licence and where it runs.
- [Can the machine handle it? Hardware and estimates](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/hardware.md): Use before downloading weights: probe CPU, RAM and GPU (containers included) and estimate whether the model fits.
- [Embeddings and scale](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/embeddings.md): Use to generate embeddings (torch or ONNX), batch concurrent inference and share and inspect the loaded models.
- [Generate text (local and hosted)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/text.md): Use to generate text with a local LLM (`TextGenerator`) or an OpenAI-compatible backend (DeepSeek, Groq, OpenRouter, vLLM), with per-call cost and `extra_body`.
- [Long-term memory](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/memory.md): Use when the assistant must remember facts across conversations (`ChatMemory`), in memory or in Postgres with pgvector.
- [Moderation, usage, metrics and cache](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/operations.md): Use in production: moderate content, account usage per user, expose metrics and tracing, count tokens and cache generations.
- [Multimodal vision (local VLM)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/vision.md): Use to ask a locally running vision-language model about an image with `VisionTextGenerator`.
- [Ollama backend](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/ollama.md): Use to run LLMs and embeddings through Ollama, without torch: generation, RAG, hybrid search, reranking and the same router swapping torch for Ollama.
- [RAG context](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/rag.md): Use to inject context into the LLM: web search (SearXNG), page-body extraction, PDF reading and RAG over your own corpus.
- [Ready endpoints and Redis cache](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/router.md): Use to expose the module over HTTP with `make_genai_router` and share the embedding cache across workers with `RedisEmbeddingCache`.
- [Sound effects and music](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/sound.md): Use to generate sound effects and music (MusicGen) with `AudioGenerator` and serve the result over HTTP at `/audio`.
- [Typed config and structured output](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/structured.md): Use when the model must return a filled-in Pydantic object, and to pin generation parameters with `GenerationConfig`.
- [Who said what: diarization](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/diarization.md): Use to split audio by speaker (sherpa-onnx), recognise who it is from a voice profile and serve it over HTTP or the CLI.
- [Sentry (secrets out of the event)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/sentry.md): Use to keep Bearer, JWT and secret keys out of Sentry events; covers make_sentry_before_send, the leak the EventScrubber misses, and redact_in_place.
- [Server-Sent Events (SSE)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/sse.md): Use to push server-to-browser events over SSE; covers the endpoint, heartbeat, backpressure, broadcast with `SSEBroker`, multi-worker Redis/RabbitMQ bridges and stream authentication.
- [Server-side login and signup](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/auth-pages.md): Use when the service serves its own HTML and needs login, signup and activation without an SPA; covers `make_auth_pages_router`, `SessionAuth`, MFA, templates and tests.
- [Server-side sessions](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/sessions.md): Use when you want server-side session auth instead of JWT; covers the comparison, `SessionAuth` setup, endpoints, settings, Memory/Redis stores, middleware and login without a user table.
- [Settings: composing the configuration mixins](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/settings.md): Use to build the service `Settings` class from the SDK mixins; covers base ordering, `BaseAppSettings` last, `*_kwargs()` for clients and a table of environment variables per mixin.
- [Sharing with a preview (Open Graph)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/share-preview.md): Use so links shared on WhatsApp or social networks show a preview; covers the per-item Open Graph page, unavailable items, the PNG card, cache and versioning, public link and Docker fonts.
- [Slides, answer keys and Markdown to PDF](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/slides.md): Use to turn lesson text into slides, answer keys or PDF; covers the first deck, vocabulary in the service language, output formats, Markdown to PDF with images and Mermaid, and HTTP serving.
- [Social login (OAuth2 / OIDC)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/oauth.md): Use for social login with Google, GitHub or OIDC that issues your own session; covers `make_auth_router`, the token-in-hand flow, email linking, linked accounts and `OIDCProvider`.
- [Spreadsheets (.xlsx)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/spreadsheets.md): Use to generate or read `.xlsx` spreadsheets; covers declared columns, Brazilian formats, live formulas, theming, download, reading Google Sheets and `.xlsx` files, and zip-bomb limits.
- [SSR: typed Python pages rendered to HTML](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/ssr.md): Use to render HTML pages from typed Python components; covers `Page`, `html_response`, `shell()`, widgets, `Style`, forms, local HTMX and serving a tempestweb build.
- [SSR actions: confirmation, flash and redirect back](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/ssr-actions.md): Use for SSR panel actions that confirm, notify and return to the originating screen; covers confirm-before-remove, read-once flash, redirect back without open redirect and exceptions.
- [Object storage — MinIO / S3](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/storage.md): Use to store objects in MinIO/S3 with `AsyncMinIOClient`; covers settings, upload, streaming, `X-Accel-Redirect`, signed and presigned URLs, batch operations and a private bucket over HTTPS.
- [Storage on local disk — `LocalObjectStorageClient`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/local-storage.md): Use to store files on local disk without an S3 server; covers `LocalObjectStorageClient`, links via the API, capped uploads, picking the backend by settings and encryption at rest.
- [Stripe (cards, subscriptions, Checkout)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/stripe.md): Use to charge cards, subscriptions or Checkout through Stripe with no extra; covers the minimal path, form-encoded bodies, currency, webhook verification, idempotency, pagination, errors and tests.
- [System checks (`tempest check-config`)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/system-checks.md): Use to validate configuration before serving traffic with `tempest check-config`; covers built-in checks, writing your own, failing at startup and the `EnvironmentSettings` production guard.
- [tempestweb frontend + tempest-fastapi-sdk backend](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/tempestweb-frontend.md): Use to connect a Python frontend (tempestweb) to an SDK backend over typed HTTP; covers the backend, the frontend, end-to-end idempotency, typed retry and CORS per origin.
- [Testing](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/testing.md): Use to build a test suite for an SDK service; covers `conftest.py` with lifespan, real login, a fake LLM, in-memory repositories, `testing` helpers, `ModelFactory` and the parallel suite.
- [Text search (LIKE + full-text)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/text-search.md): Use to search text over models; covers portable `search()` (LIKE) on PostgreSQL and SQLite, request-chosen fields, pagination and `full_text_search()` with per-field weights.
- [Transactional email](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/email.md): Use to send SMTP email with `EmailUtils`; covers `EmailSettings`, TLS vs SSL, attachments, `send_many`, Jinja2 templates and the disabled mode.
- [Transactional outbox (reliable events)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/outbox.md): Use to publish events atomically with the database write and avoid dual-write; covers the outbox table, same-transaction writes, the relay, retries and a one-shot drain.
- [Transactions (commit and savepoint)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/transactions.md): Use when a business rule does several writes that must commit together; covers `transaction()`, explicit `commit()`, `autocommit=False`, `savepoint()` and nesting.
- [Transcription pipeline — from audio to summary, in stages](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/transcription-pipeline.md): Use to stitch audio, transcription, summary and suggestions into a staged pipeline; covers state columns, cancelling a running job, per-user usage accounting and the screen.
- [Typed CSS (stylesheet and tokens)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/ui-css.md): Use to write CSS in Python checked by the type checker; covers rules as objects, design tokens from `tempest_core`, serving the sheet, the bundled sheet and failing on wrong class names.
- [Enforce typing (static + runtime)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/typing.md): Use to enforce static and runtime typing; covers linters, the pydantic plugin and `tempest_fastapi_sdk.mypy`, `[tool.tempest]`, `strict_types`, `typed` and `require_annotations`.
- [UI layer (pages and components)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/ui.md): Use when the service must return HTML through the `src/ui/` layer; covers the folder tree, a minimal example, ready-made components, layout, custom components and the scaffold.
- [Unified file store — `FileStoreUtils`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/file-store.md): Use when the service stores and serves the same file: `FileStoreUtils` unifies upload, download and presigned URLs over local disk or MinIO/S3.
- [Uploads — local disk + S3 / MinIO](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/uploads.md): Use to validate and store `UploadFile` on disk or MinIO/S3 with `UploadUtils`; covers extension allowlists, `ImageMediaTypeEnum`, magic bytes, `replace`, `write_stream` and migration.
- [Utilities](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/utilities.md): Use to find small base-SDK helpers; covers `utcnow`/`to_utc`, `get_client_ip`, opaque tokens, `generate_password`, `sign_path`, `form_encode` and color contrast.
- [Validated fields (ready-made types)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/fields.md): Use to declare pre-validated schema fields (`*Field` types for int, float, decimal, string, locale and Pix key) and compose your own.
- [Versioned artifact registry](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/artifact-registry.md): Use to version binaries swapped at runtime (ONNX models, bundles) with one current version per name; covers `ArtifactRegistry`, digest, manifest and admin action.
- [Wallet and Pix payouts](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/wallet.md): Use to keep a balance per person and pay Pix payouts without lost credits or double payouts; covers models, held credits, OpenPix or manual payouts, fees, `WalletLedger` and the router.
- [Web Push](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/webpush.md): Use to send VAPID Web Push notifications to browsers with `WebPushDispatcher`; covers VAPID config, model-to-router layers, the service worker payload and broadcast.
- [WebAuthn / passkeys](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/webauthn.md): Use to add phishing-resistant passkey login; covers the credentials table, settings, the router, the frontend, the multi-worker challenge store, account recovery and MFA interplay.
- [WebSocket client (AsyncAPI)](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/asyncapi-client.md): Use to generate a typed WebSocket client from an AsyncAPI spec; covers generation, usage, the two per-direction unions, validation and keeping it up to date.
- [WebSocket router](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/websocket.md): Use for a bidirectional channel with `make_websocket_router` and `WebSocketHub`; covers the required extra, handshake bearer auth, a JS client, per-user and topic broadcast, and heartbeat.
- [WhatsApp through zap-api](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/zap.md): Use to send WhatsApp messages through the zap-api gateway with the generated client; covers send versus delivery, idempotent retry, three media modes, `bytes` bodies and regeneration.