# 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.** ![Python](https://img.shields.io/badge/python-3.12%20%7C%203.13%20%7C%203.14-blue) ![License](https://img.shields.io/badge/license-MIT-green) ![PyPI](https://img.shields.io/pypi/v/tempest-fastapi-sdk) !!! 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
- **[Starting from zero »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/getting-started/uv.md)** The beginner track: install `uv`, pick a Python version, build your first project, and where the official docs live. - **[Installation »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/installation.md)** The per-extra walkthrough: what each one pulls in, what `[all]` leaves out, and how to pin the version. - **[Architecture »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/architecture.md)** The layering (router → controller → service → repository) and why it is not optional. - **[Tutorial »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/tutorial.md)** Linear, from scratch: builds the whole *Users* feature step by step. - **[Frontend in Python »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/tempestweb-frontend.md)** The UI is Python too: **tempestweb** writes the screen (WASM in the browser, or server-mode) and the SDK serves the compiled build through `make_web_app_router` / `build_web_app`, on the same origin as the API. For server-rendered pages, the `ui` layer from the `[ssr]` extra. - **[Recipes »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/index.md)** The heart of the docs: the **SDK tour** (one minimal example per block), the index of **93 recipes**, the **complete examples** (Pix checkout, marketplace, admin, fullstack web, GenAI) and **typed SSR**. - **[Reference »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/reference.md)** The full API generated from the docstrings — signature, parameters, return type, raised exceptions and a link to the source. - **[Learning projects »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/learning/index.md)** A guided project (marketplace) with business rules, domain model, critical flows and an endpoint map — to study the decisions, not just the APIs. - **[Roadmap »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/roadmap.md)** What shipped in which version and what is queued. Honest, not aspirational. - **[Migration guide »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/migration.md)** · **[Changelog »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/changelog.md)** Breaking changes and the version-by-version history.
!!! tip "Something missing or wrong in the docs?" [Open an issue](https://github.com/mauriciobenjamin700/tempest-fastapi-sdk/issues/new/choose) — we treat a docs regression like a code regression. See **[Contributing »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/contributing.md)**. ## Status | Surface | State | | --- | --- | | Python | 3.12 / 3.13 / 3.14 (matrix-tested with `make test-matrix`) | | Tests | 10,400+ pytest cases and 90 % coverage (lines + branches) at v0.302.0 (measured; CI has no coverage gate) | | Type-checking | `mypy --strict`, `py.typed` shipped (PEP 561) | | Lint / format | `ruff` (check + fix + format) | | Release pipeline | PyPI trusted-publishing on every `vX.Y.Z` tag | --- Source: https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/installation.md # Installation ## TL;DR ```bash pip install tempest-fastapi-sdk ``` Requires **Python 3.12+** (3.12, 3.13 and 3.14). !!! tip "Use `uv` instead" `uv add tempest-fastapi-sdk` is faster and writes to `pyproject.toml` for you. !!! info "The `tempest` command is the `[cli]` extra (or `[cli-ops]` on a server)" Since 0.308.0 the CLI (`tempest new`, `tempest check`, `tempest db`, …) is not part of the base package — the quality gate brings `ruff`, which has no place in a production image. In development, install it as a tool: `uv tool install "tempest-fastapi-sdk[cli]"`, or in the project's dev group: `uv add --dev "tempest-fastapi-sdk[cli]"`. To have `tempest` on a server (`doctor`, `db`, `shell` and the project's commands), use `[cli-ops]`, which brings neither `tempest-cli` nor `ruff`: `uv add "tempest-fastapi-sdk[cli-ops]"`. !!! info "First time with modern Python?" This page assumes you already have a working environment. If you do not, follow the beginner track, which starts from absolute zero: **[Install uv »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/getting-started/uv.md)** → **[Pick your Python version »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/getting-started/python-versions.md)** → **[Your first project »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/getting-started/first-project.md)** → **[Official reference docs »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/getting-started/references.md)**. ## Optional extras Feature-rich helpers pull in third-party dependencies that you only need when you actually use the helper. Pick the extras your service consumes: | Extra | Pulls in | Unlocks | | --- | --- | --- | | `[admin]` | `jinja2`, `itsdangerous` | `AdminSite`, `AdminModel`, `make_admin_router` | | `[admin-sql]` | `sqlglot` | admin SQL console: `SqlShellService` + `SqlShellPolicy` (capabilities, allowed/denied tables, row cap), real statement parsing, every attempt audited | | `[auth]` | `bcrypt`, `PyJWT` | `PasswordUtils`, `JWTUtils`, bundled `UserAuthService` + `make_auth_router` flow | | `[cache]` | `redis` | `AsyncRedisManager` + `@cached` + `RedisIdempotencyStore` | | `[cli]` | `tempest-cli` (which requires `ruff`), `typer`, `click` | the whole `tempest` command (`new`, `check`, `db`, …), quality gate included. Dev tooling: `uv add --dev "tempest-fastapi-sdk[cli]"` or `uv tool install "tempest-fastapi-sdk[cli]"`. Without it or `[cli-ops]`, `tempest` prints the install line and exits with code 2. Included in `[all]`. [Recipe](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli.md) | | `[cli-ops]` | `typer`, `click` | the `tempest` command without the gate, for a server: `doctor`, `db`, `shell`, `user`, `routes` and `[tool.tempest] commands` run; `tempest lint` and the other gate commands exit 2 naming `[cli]`. No `tempest-cli`, no `ruff`. `[cli]` contains it. [Recipe](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/new-service.md#server-vs-development-cli-ops-and-cli) | | `[genai-onnx]` | `onnxruntime`, `tokenizers` | Local-model inference from an ONNX export, with no PyTorch at runtime | | `[genai-structured]` | `lm-format-enforcer` | Grammar-enforced structured output: the local model can only emit JSON matching the schema | | `[genai-vlm]` | `pillow`, `torchvision` | Local vision-language model: describe an image, answer a question about one | | `[openapi]` | `pyyaml` | Read a YAML OpenAPI spec for `tempest openapi-client` / `tempest openapi-errors` | | `[pdf-read]` | `pypdf` | **Read** PDFs (extract text/pages); `[pdf]` is for **generating** them | | `[pdf-layout]` | `pdfplumber` | Read PDFs **with layout and tables** (columns recovered, tables as grids); slower than `[pdf-read]` | | `[spreadsheet]` | `openpyxl` | `.xlsx` spreadsheets: typed reading, writing and bulk import | | `[websocket]` | `websockets` | Protocol driver for `make_websocket_router` — without it the handshake 404s | | `[email]` | `aiosmtplib`, `jinja2`, `email-validator` | `EmailUtils` (with `render_template` + Jinja2 templates) | | `[faces]` | `onnxruntime`, `pillow`, `numpy` | Face recognition on ONNX Runtime, no opencv and no torch: `FaceRecognizer` (detect/embed/compare), `compare_faces`. 16 MB models fetched by `ensure_models()`. **No system libraries** | | `[fastmcp]` | `fastmcp` | MCP in both directions: `mount_mcp` (a `FastMCP` server at `/mcp` behind `current_user`), `add_agent_tools`, `add_fastapi_routes`, `MCPToolset` (another MCP server's tools in an `Agent`, stdio and HTTP). Adds 47 packages to the base install (fastmcp 4.1.8), `httpx2` among them — and therefore **out of `[all]`** | | `[firebase]` | `firebase-admin` | Firebase ID token verification: `FirebaseAuth` (idempotent init, `get_identity` / `get_uid` / `get_optional_identity`), `FirebaseIdentity`, `FirebaseUserResolver`, `FirebaseSettings`. Heavy — 33 packages, 52 MB measured on `firebase-admin` 7.5.0 — and therefore **out of `[all]`** | | `[genai]` | `transformers`, `torch`, `accelerate`, `safetensors`, `huggingface-hub` | local (heavy) GenAI: `TextGenerator`, `Embedder`, `MusicGenerator`, `BarkSpeech`, `AIChatPipeline`, `make_genai_router` via HuggingFace/torch | | `[genai-audio]` | `faster-whisper`, `torch` | STT (Whisper). Since 0.349.0 it no longer brings Coqui: its `torchaudio` broke Bark on a GPU ([details](#genai-audio-coqui-split)) | | `[genai-tts-coqui]` | `coqui-tts`, `torch`, `torchaudio`, `torchcodec`, `six` | TTS (Coqui XTTS v2) — the Coqui runtime ships with it; no `transformers<5` cap since 0.342.0 ([details](#genai-audio-transformers-bound)) | | `[genai-chroma]` | `chromadb` | Chroma vector store for RAG | | `[genai-diarization]` | `sherpa-onnx` | Speaker diarization (who spoke when) via `sherpa-onnx` on ONNX Runtime, no PyTorch: `SpeakerDiarizer`, `ConversationTranscriber`. Models (46 MB) fetched by `ensure_models()` | | `[genai-hosted]` | `httpx` (already in the base package) | hosted providers: `AnthropicGenerator`, `OpenAICompatGenerator` (OpenAI, DeepSeek), `OpenAICompatEmbedder`, `OpenAICompatSpeech` (remote transcription and synthesis), `HostedGenAISettings`. No vendor SDK | | `[genai-hub]` | `huggingface-hub` | weight lifecycle: `resolve_revision` (pin a sha), `download_model` (fetch before serving, with a disk preflight), `list_cached_models`/`remove_cached_model`, `tempest model pull`/`cache-list`/`cache-rm` | | `[genai-image]` | `diffusers`, `pillow` | local image generation: `ImageGenerator` (`generate` text→image, `edit` image→image), `ImageGenerationConfig`, `POST /image` route | | `[genai-sound]` | `diffusers` | local sound effects and music (with `[genai]`): `AudioGenerator`, `AudioGenerationConfig`, `GeneratedAudio`, `POST /audio` route | | `[genai-ollama]` | `httpx` | Ollama backend: `OllamaGenerator`, `OllamaEmbedder`, `OllamaSpeech` (speech and transcription) | | `[genai-quant]` | `bitsandbytes` | 4/8-bit quantization for the local `[genai]` models | | `[genai-rag]` | `trafilatura`, `pymupdf`, `pgvector`, `httpx` | RAG ingestion: web scraping, PDF extraction, and pgvector embeddings | | `[geo]` | `httpx` | geospatial helpers: `haversine_km`, `estimate_travel`, `NominatimBackend`/`OSRMBackend` (geocoding + routing), `GeoPointMixin` | | `[google-drive]` | `httpx`, `pyjwt`, `cryptography` | Google Drive upload backend through a service account: `GoogleDriveUploadStorage` (for `UploadUtils(backend=...)`), `GoogleDriveClient`, `ServiceAccountTokenProvider`, `GoogleDriveSettings` — [recipe](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/google-drive.md) | | `[http]` | `httpx` (already in the base package) | `HTTPClient` + `RetryPolicy` + circuit-breaker. The extra is optional: `HTTPClient` works on the base install, and declaring the extra only records the intent in the service's `pyproject.toml` | | `[image]` | `pillow`, `segno` | `strip_image_metadata`: re-encodes a user's photo in the same format without EXIF (GPS, device), XMP, IPTC, ICC and text chunks, with a pixel ceiling against decompression bombs; `ShareCardRenderer`: the 1200×630 PNG card of a link preview; `render_qr` and `ShareFrameRenderer`: a QR code with a logo and the frame to share (brings `segno`; card and frame need a TrueType font on the machine, `fonts-dejavu-core`) | | `[kurrentdb]` | `kurrentdbclient` (+ `grpcio`, `grpcio-tools`, `setuptools`, `protobuf`) | KurrentDB (formerly EventStoreDB) backend of the event store: `KurrentDBEventStore`. The SQL backend (`SqlEventStore`) needs no extra. Included in `[all]`. Weighs 34 MB in a clean venv (`kurrentdbclient` 1.3.6: `grpc` 18 MB, `grpc_tools` 7.9 MB, `setuptools` 3.9 MB), because the client asks for `grpcio[protobuf]`; `pip-audit` found no advisory in the 2026-11-12 resolution. [Recipe](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/event-sourcing.md) | | `[metrics]` | `psutil`, `nvidia-ml-py` | `MetricsUtils` | | `[mfa]` | `pyotp`, `segno` | `TOTPHelper` + MFA/2FA (TOTP) endpoints on the bundled auth flow + enrollment QR code (`provisioning_qr_terminal`, `provisioning_qr_data_uri`) | | `[minio]` | `minio` | `AsyncMinIOClient`, `MinIOUploadStorage` | | `[modelops]` | `psutil`, `nvidia-ml-py`, `numpy` | benchmark any callable: latency, RAM, GPU and energy (`benchmark`, `NvmlPowerSampler`, `RaplEnergySampler`); drift monitoring (`baseline_from_samples`, `PredictionMonitor`) and reading the compact format (`read_compact`, `predict_compact`) | | `[modelops-compose]` | `ort-vision-sdk[compose]` | fuse a detector and a classifier into one `.onnx`: `fuse_detect_classify`. Running the fused graph is `[vision]` (`DetectClassify`), which pulls no `onnx` | | `[modelops-onnx]` | `onnx`, `onnxruntime` | static analysis, ONNX benchmarking, `.onnx` → `.ort`, graph optimization and quantization — of raw graphs (`analyze_onnx`, `benchmark_onnx`, `export_onnx_to_ort`, `quantize_onnx_dynamic`) and of transformers exports (`optimize_hf_onnx`, `quantize_hf_onnx`) | | `[modelops-sklearn]` | `skl2onnx` | export scikit-learn models to ONNX for the edge: `export_sklearn_to_onnx`, `verify_sklearn_onnx`, `edge_bundle` | | `[oidc]` | `PyJWT`, `cryptography` | offline verification of OIDC realm access tokens (Keycloak, Auth0, Okta …): `OIDCTokenVerifier`, and `OIDCProvider(token_verifier=...)` for social login | | `[otel]` | `opentelemetry-sdk`, OTLP exporter + FastAPI/SQLAlchemy/httpx instrumentations | OpenTelemetry instrumentation via `setup_tracing` | | `[pdf]` | `weasyprint`, `jinja2`, `segno` | PDF generation from HTML templates: `PdfRenderer`, five bundled typed documents, `make_pdf_router`, `tempest pdf`. **Needs Pango + fontconfig on the system** — see the recipe | | `[postgres]` | `asyncpg` | PostgreSQL async driver for `postgresql+asyncpg://` URLs (production) | | `[prometheus]` | `prometheus-client` | `PrometheusMiddleware`, `make_prometheus_router`, `make_prometheus_registry` | | `[queue]` | `faststream[rabbit]` | `MessageBroker.rabbitmq`, `AsyncBrokerManager` | | `[queue-kafka]` | `faststream[kafka]`, `aiokafka>=0.10.0` | `MessageBroker.kafka` and `MessageBroker.kafka_from_settings` (with `KafkaSettings`): topic, partition `key`, `group_id`, `auto_offset_reset`, SASL and TLS. Inherits `aiokafka<0.15` from FastStream. [Recipe](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/queue-tasks/broker.md#kafka-key-group-and-commit) | | `[queue-nats]` | `faststream[nats]` | `MessageBroker.nats` | | `[queue-redis]` | `faststream[redis]` | `MessageBroker.redis` | | `[slides]` | `weasyprint`, `jinja2`, `python-pptx`, `python-docx`, `markdown` | Slides and answer keys from structured text (HTML, PDF, PPTX, DOCX, Markdown) and Markdown to PDF with your own or the ABNT stylesheet: `parse_slides`, `SlideRenderer`, `AnswerKeyRenderer`, `MarkdownPdfRenderer`. **Needs Pango + fontconfig on the system**, like `[pdf]`. [Recipe](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/slides.md) | | `[slides-mermaid]` | `playwright` | Drawing `` ```mermaid `` blocks in `MarkdownPdfRenderer` (`render_mermaid=True`). Needs `playwright install chromium`; that is why it stays **out of `[all]`** | | `[sqlite]` | `aiosqlite` | SQLite async driver for `sqlite+aiosqlite://` URLs (dev default) | | `[ssr]` | `tempestweb` | HTMX-based SSR: `build_web_app`, `make_htmx_router`, `Page`, the `htmx` helper | | `[storage-encryption]` | `cryptography` | Encryption at rest of `LocalObjectStorageClient` (`encryption_keys`, `STORAGE_LOCAL_ENCRYPTION_KEYS`) and the `tempest storage encrypt-local` / `reencrypt-local` commands. [Recipe](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/local-storage.md#encryption-at-rest) | | `[tasks]` | `taskiq`, `taskiq-aio-pika` | `AsyncTaskBrokerManager`, `AsyncTaskScheduler` | | `[tasks-redis]` | `taskiq`, `taskiq-redis` | `TaskQueue.redis` / `TaskQueue.from_settings` over Redis Streams, the result backend and the scheduler lease | | `[tests]` | `pytest`, `pytest-asyncio`, `pytest-xdist` | the service's suite and `tempest test` in parallel (the default since `tempest-cli` 0.6.0). No bound of its own; inherits `pytest<10` from `pytest-asyncio` and `pluggy<2` from `pytest`. Test tooling, not a helper — kept **out of `[all]`**. [Recipe](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/testing.md#the-suite-in-parallel-the-tempest-test-default) | | `[upload]` | `aiofiles`, `python-multipart` | `UploadUtils`, `DownloadUtils`, `LocalUploadStorage` | | `[vision]` | `ort-vision-sdk` | vision helpers (`Detector`, `Classifier`, `Segmenter` + `to_detection_schemas`/`to_classification_schema`/`to_segmentation_schemas`) | | `[webauthn]` | `fido2` | Passkeys / security keys: `WebAuthnService`, `make_web_authn_credential_model`, the `/auth/webauthn/*` routes — passwordless, phishing-resistant login | | `[webpush]` | `pywebpush`, `cryptography` | `WebPushDispatcher` | | `[all]` | everything above **except** the 19 extras that pull a heavy stack or a native binary: `[genai]`, `[genai-audio]`, `[genai-tts-coqui]`, `[genai-diarization]`, `[genai-hub]`, `[genai-image]`, `[genai-onnx]`, `[genai-sound]`, `[genai-quant]`, `[genai-rag]`, `[genai-structured]`, `[genai-vlm]`, `[faces]`, `[modelops-onnx]`, `[modelops-sklearn]`, `[admin-sql]`, `[fastmcp]`, `[firebase]`, `[slides-mermaid]` | the application helpers — install the 19 above separately (and `[tests]`, which is test tooling, in the dev group). Brings the four `MessageBroker` transports (`faststream[rabbit,kafka,nats,redis]`) and, with them, the caps FastStream declares on its own extras: `aio-pika<11`, `aiokafka<0.15`, `nats-py<=3.0.0` and `redis<9.0.0` (the same in FastStream 0.7.5 and 0.7.8). Together with `redis>=8.1.0` from `[cache]`, `[all]` stays on `redis` 8.x; `aiokafka` 0.15.0 is already out and is held back | === "Subset (recommended)" ```bash pip install "tempest-fastapi-sdk[auth,upload,cache]" ``` === "Everything" ```bash pip install "tempest-fastapi-sdk[all]" ``` === "uv add" ```bash uv add "tempest-fastapi-sdk[auth,upload,postgres]>=0.171.0" ``` === "pyproject.toml" ```toml dependencies = [ "tempest-fastapi-sdk[auth,upload,postgres]>=0.171.0", ] ``` !!! warning "Since 0.349.0 Coqui (XTTS) lives in `[genai-tts-coqui]`" `[genai-audio]` used to bring `coqui-tts` and, with it, `torchaudio`. Bark does not use `torchaudio`, but `transformers` imports it when it is installed, while building the `AutoProcessor`. On a GPU the PyPI `torchaudio` 2.11.1 is a CUDA 13 build that does not load next to a CUDA 12 `torch`, so `POST /audio/speech` answered 500 (measured on tempest-ai, RTX 4070 Ti SUPER, SDK 0.348.0 — issue #723). Now `[genai-audio]` is speech-to-text only (`faster-whisper` + `torch`) and Coqui has an extra of its own. Resolved with `uv pip compile` (Python 3.12) on 2026-11-10: | Extra | brings | does not bring | | --- | --- | --- | | `[genai-audio]` | faster-whisper 1.2.1, ctranslate2 4.8.5, torch 2.15.0 | `torchaudio`, `transformers`, `coqui-tts` | | `[genai-tts-coqui]` | coqui-tts 0.28.0, torchaudio 2.11.1, transformers 5.22.2, torch 2.15.0 | — | **If you use `TextToSpeech` (XTTS)**, replace `[genai-audio]` with `[genai-audio,genai-tts-coqui]` (or just `[genai-tts-coqui]`, without STT). !!! check "Since 0.342.0 the Coqui extra no longer caps `transformers<5`" Up to 0.341.0 the extra carried `transformers<5`: `coqui-tts` 0.27.5 imported `isin_mps_friendly`, a symbol transformers 5.1 removed. That held anyone installing the extra on transformers 4.57.6, and with it `huggingface-hub`, `tokenizers` and, next to `[genai-image]`, `diffusers`. `coqui-tts` 0.28.0 no longer imports the symbol, and the extra now requires that version. Resolved with `uv pip compile` (Python 3.12) on 2026-11-01, while Coqui was still in `[genai-audio]` (it is in `[genai-tts-coqui]` today, see above), the extra held nothing back any more: | Extras | `transformers` | `huggingface-hub` | `tokenizers` | `diffusers` | | --- | --- | --- | --- | --- | | `[genai-audio]` | 5.22.1 | 2.4.0 | 0.23.3 | — | | `[genai-audio,genai-image]` | 5.22.1 | 2.4.0 | 0.23.3 | 0.42.1 | | `[genai-image]` without `[genai-audio]` | — | 2.4.0 | — | 0.42.1 | The extra declares `six` because `coqui-tts` 0.28.0 imports it without declaring it: in a clean venv without it, `import TTS.api` dies with `ModuleNotFoundError: No module named 'six'`. !!! warning "The SDK ships no database driver by default" `sqlalchemy[asyncio]` is core, but the async DBAPI is your deploy choice: install `[sqlite]` (`aiosqlite`, dev default) or `[postgres]` (`asyncpg`, production). Without one, the engine raises `ModuleNotFoundError` for the driver on first connection. Services scaffolded with `tempest new` already pin both `aiosqlite` and `asyncpg` in `pyproject.toml` — the latter is what the generated `docker-compose.yaml`'s `prod` profile uses. !!! info "Lazy imports" Since 0.7.1 every optional dependency is imported lazily at first instantiation, so `import tempest_fastapi_sdk` works even when only a subset of extras is installed. Instantiating a helper whose extra is missing raises `ImportError` with a clear hint pointing at the right extra. Since 0.326.0 the SDK's own modules load on demand too: `import tempest_fastapi_sdk` loads one module instead of 269 plus SQLAlchemy, FastAPI, Alembic, Jinja2 and bcrypt, and `tempest --help` went from 0.94 s to 0.14 s (best of 5, measured on this repository). `from tempest_fastapi_sdk import X` and strict type checking work as before. ### GPU with `[genai-audio]` `[genai-audio]` transcribes with **faster-whisper**, which runs on **CTranslate2**. The `ctranslate2` 4.x wheels are linked against **CUDA 12** and, on the first transcription with `device="cuda"`, look up `libcublas.so.12`. The `torch` PyPI ships since 2.14 is a **CUDA 13** build: it installs the `.so.13` libraries, not the `.so.12` ones. With the default resolution, then, the first GPU transcription dies like this: ```text RuntimeError: Library libcublas.so.12 is not found or cannot be loaded ``` The way out is to install `torch` from PyTorch's **CUDA 12** index, which brings CUDA 12 cuBLAS and cuDNN as `nvidia-*-cu12` packages. #### Step 1: `torch` from the cu126 index In your service's `pyproject.toml`, declare the index as `explicit` (only the packages you point at it come from it) and point `torch` there: ```toml [project] name = "my-service" version = "0.1.0" requires-python = ">=3.12" dependencies = [ "tempest-fastapi-sdk[genai-audio]>=0.349.0", "torch>=2.14.0", ] [[tool.uv.index]] name = "pytorch-cu126" url = "https://download.pytorch.org/whl/cu126" explicit = true [tool.uv.sources] torch = { index = "pytorch-cu126" } ``` `torch` is listed in `dependencies` even though the extra already brings it: `[tool.uv.sources]` only applies to a **direct** dependency. Then `uv sync`. !!! note "Also using Coqui (`[genai-tts-coqui]`)?" PyPI's `torchaudio` is a CUDA 13 build too, and it does not load next to a CUDA 12 `torch` (`libcudart.so.13: cannot open shared object file`). Point it at the same index — and, again, as a direct dependency: ```toml [project] name = "my-service" version = "0.1.0" requires-python = ">=3.12" dependencies = [ "tempest-fastapi-sdk[genai-audio,genai-tts-coqui]>=0.349.0", "torch>=2.14.0", "torchaudio>=2.11.0", ] [[tool.uv.index]] name = "pytorch-cu126" url = "https://download.pytorch.org/whl/cu126" explicit = true [tool.uv.sources] torch = { index = "pytorch-cu126" } torchaudio = { index = "pytorch-cu126" } ``` STT-only users do not need these lines: since 0.349.0 `[genai-audio]` brings no `torchaudio` ([why](#genai-audio-coqui-split)). Up to 0.348.0 it did, so on those versions declare `torchaudio` as above even without Coqui. #### Step 2: CTranslate2's `LD_LIBRARY_PATH` The `nvidia-cublas-cu12` and `nvidia-cudnn-cu12` packages live inside `site-packages`, outside the dynamic loader's search path. `torch` finds them on its own; CTranslate2 does not. Point `LD_LIBRARY_PATH` at them before starting the process: ```bash SITE_PACKAGES="$(python -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])')" export LD_LIBRARY_PATH="$SITE_PACKAGES/nvidia/cublas/lib:$SITE_PACKAGES/nvidia/cudnn/lib:${LD_LIBRARY_PATH:-}" ``` In a `Dockerfile`, write the image's venv path, for example `ENV LD_LIBRARY_PATH=/app/.venv/lib/python3.12/site-packages/nvidia/cublas/lib:/app/.venv/lib/python3.12/site-packages/nvidia/cudnn/lib`. !!! info "Why it sometimes works without `LD_LIBRARY_PATH`" When the process imports `torch` before loading Whisper, `torch` leaves CUDA 12 cuBLAS and cuDNN loaded, and CTranslate2 reuses them. That is what happens with `SpeechToText(device="auto")`, which imports `torch` to detect the GPU, or after a `probe_hardware()`. With an explicit `device="cuda"`, nothing imports `torch` first, and without the variable the transcription fails. Export the variable anyway: relying on import order is fragile. On a host with CUDA 12 installed system-wide (`libcublas.so.12` in `ldconfig`), neither failure in this section shows up — the loader finds the system library. A `python:3.12-slim` container has none. #### Step 3: check it Generate a short WAV (here with `espeak-ng`) and transcribe it on the GPU: ```bash espeak-ng -v en -w hello.wav "The quick brown fox jumps over the lazy dog." ``` ```python import asyncio from tempest_fastapi_sdk.genai.audio import SpeechToText async def main() -> None: """Transcribe a short WAV on the GPU.""" stt = SpeechToText("small", device="cuda") with open("hello.wav", "rb") as handle: result = await stt.transcribe(handle.read()) print(stt.device, result.text) asyncio.run(main()) ``` ```text cuda The quick brown fox jumps over the lazy dog. ``` `probe_hardware()` also flags the wrong pair before the first transcription: with a CUDA 13 `torch` and `ctranslate2` installed, `HardwareInfo.warnings` says what will fail and points to this section (see [Probing the hardware](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/genai/hardware.md#probing-the-hardware)). !!! check "What was measured" **In this repository**, on 2026-11-10, in a `python:3.12-slim` container with `--gpus all` on an RTX 4070 Ti SUPER (WSL2, Windows driver 591.86), Python 3.12, `faster-whisper` 1.2.1 and `ctranslate2` 4.8.5, model `small` in `float16`, transcribing the WAV above: | `torch` | `LD_LIBRARY_PATH` | `torch` imported first | result | | --- | --- | --- | --- | | 2.15.0+cu132 (PyPI) | no | no | `libcublas.so.12 is not found` | | 2.15.0+cu132 (PyPI) | no | yes | `libcublas.so.12 is not found` | | 2.15.0+cu132 (PyPI) | `nvidia/{cublas,cudnn}/lib` | no | `libcublas.so.12 is not found` | | 2.14.1+cu126 (cu126 index) | no | no | `libcublas.so.12 is not found` | | 2.14.1+cu126 (cu126 index) | no | yes | transcribes | | 2.14.1+cu126 (cu126 index) | `nvidia/{cublas,cudnn}/lib` | no | transcribes | The rows above call `WhisperModel` directly; with the SDK installed on top, `SpeechToText(device="cuda")` gave the same pair (fails without the variable, transcribes with it) and `SpeechToText(device="auto")` transcribed without it. The venv was built from the step 1 `pyproject.toml` with `tempest-fastapi-sdk[genai-audio]` swapped for `faster-whisper`, which is what the extra brings, and the branch's SDK installed on top. The audio was the WAV above converted to 16 kHz with `ffmpeg`; the original WAV (22,050 Hz) gave the same text through `SpeechToText` on the CPU. On the WSL2 host outside the container, which has the system `libcublas.so.12` in `ldconfig`, the cu126 venv transcribed without the variable and without importing `torch` — which is why the table comes from the container. **In tempest-ai** (issue #723; `python:3.12-slim`, RTX 4070 Ti SUPER, SDK 0.348.0) the same fix was applied to the service, with `torch==2.14.1+cu126` and `torchaudio==2.11.0+cu126` from the cu126 index: `BarkSpeech` (`suno/bark-small`) synthesized Portuguese — 5.95 s of audio in 9.6 s and 16.76 s in 23.6 s, with the model already loaded. **Not measured:** Coqui (`[genai-tts-coqui]`) on the GPU with the cu126 `torchaudio` in this repository, and other GPUs, drivers or CUDA 12.x besides 12.6. **Recap:** faster-whisper needs CUDA 12; PyPI's `torch` is CUDA 13. Take `torch` (and `torchaudio`, if you use Coqui) from the cu126 index, as a direct dependency, and export `LD_LIBRARY_PATH` to `nvidia/{cublas,cudnn}/lib`. ## CLI Use this when you are going to run the `tempest` command. It does not come with the base install: it is the `[cli]` extra in development, or `[cli-ops]` on a server. | Extra | Install with | Commands | | --- | --- | --- | | `[cli]` | `uv add --dev "tempest-fastapi-sdk[cli]"` or `uv tool install "tempest-fastapi-sdk[cli]"` | all of them, gates included (`lint`, `fix`, `format`, `fmt-check`, `type`, `test`, `check`, `pr-prompt`) | | `[cli-ops]` | `uv add "tempest-fastapi-sdk[cli-ops]"` | all but the gates, which exit with code 2 pointing at `[cli]` | Without either, `tempest` prints `error: missing typer, click. The tempest CLI needs the optional [cli-ops] or [cli] extra.` along with the three install commands and exits with code 2 (measured on 0.374.0). ```bash tempest --version # show installed SDK version tempest new # scaffold a layered service in cwd tempest new myproject # scaffold inside ./myproject tempest generate --docker # regenerate docker-compose.yaml from chosen extras tempest db init # bootstrap alembic dir (alembic.ini with no credentials) tempest db revision -m "msg" # autogenerate revision with the reorder hook applied tempest db upgrade # run upgrade to head (reads DATABASE_URL from .env) tempest db downgrade -1 # roll back one revision tempest db current # show current revision tempest db history # revision log tempest user create --email admin@local --admin # `--email` required; password prompted interactively tempest user list --admin # list admins only (drop `--admin` to list everyone) tempest fix # ruff check --fix-only . + ruff format . + ruff check . tempest check # lint + fmt-check + mypy + pytest ``` See **[Recipes → CLI »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli.md)** for the full breakdown. ## Verify the install ```bash python -c "import tempest_fastapi_sdk; print(tempest_fastapi_sdk.__version__)" ``` ## Python version policy | Python | Status | | --- | --- | | 3.14 | Supported | | 3.13 | Supported — the version the repository's `.python-version` pins | | 3.12 | Supported (minimum) | | 3.11 | Not supported since 0.314.0 — stays on 0.313.x ([migration](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/migration.md)) | | 3.10 and older | Not supported (uses ``X | None`` PEP 604 syntax) | --- Source: https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/architecture.md # Architecture The SDK enforces a strict **router → controller → service → repository** layering. Every Tempest project follows the same shape, so a developer dropped into a new repo finds the file they need on the first try. ## The four layers ```mermaid flowchart LR subgraph HTTP Router["📡 Router\n(api/routers/)"] end subgraph Coordination Controller["🎼 Controller\n(controllers/)"] end subgraph Domain Service["📐 Service\n(services/)"] end subgraph Data Repository["🗄️ Repository\n(db/repositories/)"] Model["🧱 SQLAlchemy Model\n(db/models/)"] end subgraph Interface UI["🖼️ UI\n(ui/)"] end DB[(PostgreSQL / SQLite)] Router -->|"Depends()"| Controller Router -->|"loaded data"| UI Controller -->|orchestrates| Service Service -->|domain rules| Repository Repository -->|"SELECT/INSERT/UPDATE"| Model Model -->|async SQLAlchemy| DB ``` ## What lives where !!! abstract "Layer responsibilities" | Layer | Owns | NEVER touches | | --- | --- | --- | | **Router** | HTTP verbs, status codes, request/response schemas, `Depends()` | DB, business logic | | **Controller** | Coordination across multiple services, cross-cutting policy (audit log, outbox emit, downstream notify) | DB, request/response shape | | **Service** | Domain rules (uniqueness, derived state, transactional flow) | HTTP, SQLAlchemy types | | **Repository** | Raw async SQLAlchemy queries, CRUD + filter + pagination | Domain rules, HTTP | | **UI** (when the service serves HTML) | Pages, components, forms and the stylesheet — *what it looks like* | DB, controllers, services, HTTP | The repository **MUST** be a [`BaseRepository[ModelType, ResponseT]`][tempest_fastapi_sdk.BaseRepository] subclass (or instance; `ResponseT` is optional). The service **MUST** be a [`BaseService[RepositoryT, ResponseT]`][tempest_fastapi_sdk.BaseService] subclass. The controller **MUST** be a [`BaseController[ServiceT]`][tempest_fastapi_sdk.BaseController] subclass — even when every method is a pass-through, because the controller is the seam to add cross-service coordination later — or, when it orchestrates several services with no single-resource CRUD, a [`Controller`][tempest_fastapi_sdk.Controller] subclass (see [A controller that orchestrates](#a-controller-that-orchestrates-controller)). ## Mandatory project layout ```text / ├── main.py # ONE-LINER: from src.server import run; run() └── src/ (or app/) ├── __init__.py # re-exports run from src.server ├── server.py # programmatic uvicorn.run() + module-level FastAPI app ├── api/ │ ├── app.py # create_app() factory — middleware + handlers + wiring (thin) │ ├── routers/ # HTTP endpoints, no business logic │ ├── dependencies/ # PACKAGE (auth.py + resources.py + controllers.py / services.py) │ └── docs/ # OpenAPI text: one EndpointDoc per handler (.py) ├── controllers// # Orchestrate between services — one class per module ├── services// # Business logic layer ├── schemas/ # Pydantic v2 request/response DTOs ├── scripts/ # composition.py (build_*) + the work tasks run ├── core/ # settings.py + packages constants/, enums/, types/, exceptions/ (one module per status) ├── db/ (optional) │ ├── configs/ # names.py + connection.py (make_db_manager) + migrations.py (run_migrations) │ ├── models// # SQLAlchemy ORM models │ └── repositories// # Data access layer ├── ui/ (optional) # interface layer — only with the [ssr] extra │ ├── pages/ # one class per screen │ ├── layout/ # the chrome every page inherits │ ├── components/ # reusable pieces │ └── styles.py # the service's typed stylesheet ├── utils/ (optional) # Shared stateless helpers ├── queue/ (optional) # FastStream consumers/publishers └── tasks/ (optional) # TaskIQ: queue, names, dispatch, worker + registration modules ``` Each `` is a subpackage per domain (`products/`, `orders/`), with one class per module, and every `__init__.py` re-exports with a relative import. Why each of these shapes, with the wrong and the right example and the `tempest check` code that enforces it, is in [Recommended architecture](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recommended-architecture.md). In `api/`, every domain router is a `TempestAPIRouter` with `@raises(...)` below the route decorator, and the text Swagger shows lives in `api/docs/.py`, one `EndpointDoc` per handler — never `summary=` in the decorator. The why, with the measured OpenAPI, is in the 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) and [Route errors](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/service-standard.md#route-errors-tempestapirouter-raises). !!! tip "`db/configs/names.py` rules out a class of error" Holding each table name in a constant makes `__tablename__` and the `ForeignKey` string come from the same symbol — renaming becomes one line instead of a hunt for scattered strings. Missing one side does not fail on the spot: SQLAlchemy resolves the FK target only when it configures the mappers, so the error arrives at application startup, or inside a migration pointing at a table that no longer exists. As of **v0.291.0** `tempest new` writes the file with the user table's name already in it, and the project's `CLAUDE.md` teaches the recipe from there. See [Database › Centralizing table names](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/database/models.md#centralizing-table-names). !!! warning "Rules that are not negotiable" - `main.py` at the service root is a **one-liner** that imports `run` from `src.server`. Never `subprocess.run(["uvicorn", ...])`. - `src/server.py` exposes both a `run()` function and the importable `app` instance. - `api/dependencies/` is **always a package**, never a flat file. Auth lives in `auth.py`; factory providers live in `controllers.py` (or `services.py` when there is no controller layer yet). - **Infra singletons (db / storage / mail) live in `dependencies/resources.py`**, built once (`db = AsyncDatabaseManager(**settings.database_kwargs())`) and reached through `get_db` / `get_session` / `get_storage` / `get_mailer` providers. `app.py` **imports** those resources for the lifespan and router wiring — it never builds them inline. This keeps `app.py` thin and gives a single owner of resource lifecycle. - Routers receive controllers (and sessions/resources) via `Depends`, never constructed inline. - Meta endpoints (`/health`, `/tool-spec`) live at the **root prefix**; business endpoints live under `/api/`. ## The interface layer (`ui/`) When the service serves HTML — not only JSON — it gains a fifth layer, **beside** `controllers` and `services`. It exists only with the `[ssr]` extra; without it, do not create the empty package. | Layer | May import | Never imports | | --- | --- | --- | | `api/routers` | `controllers`, `ui`, `schemas` | `db` | | `ui` | `schemas`, other parts of `ui` | `controllers`, `services`, `db` | | `controllers` | `services`, `schemas` | `ui` | | `services` | `db/repositories`, `schemas` | `ui` | !!! warning "A page receives loaded data" A page fetches **nothing**: the router loads through a controller and passes the materialised result. An `await` inside `body()` means a responsibility slipped a layer. `tempest new --extras "ssr"` writes the whole layer, working (and `tempest generate --src` adds it to a project that already exists). Details in [UI layer](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/ui.md), [Forms from Pydantic schemas](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/ui-forms.md) and [Typed CSS](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/ui-css.md). !!! tip "And when the frontend is an app, not a page" The `ui` layer renders HTML **on the server**. When the screen needs client-side state — a SPA — the path is still Python: **[tempestweb](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/tempestweb-frontend.md)** writes the interface and compiles it to WASM (or runs it in server-mode), and the SDK serves the build through `make_web_app_router` / `build_web_app`, on the same origin as the API. The two live together: [Fullstack web](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/fullstack-web.md) compares when to use which. ## Request lifecycle ```mermaid sequenceDiagram autonumber participant C as Client participant M as RequestIDMiddleware participant L as RateLimitMiddleware participant R as Router participant Ctl as Controller participant S as Service participant Repo as Repository participant DB as PostgreSQL C->>M: HTTP request M->>M: bind X-Request-ID into contextvar M->>L: forward L->>L: check sliding-window quota L->>R: forward R->>R: validate Pydantic schema R->>Ctl: Depends(get_user_controller) Ctl->>S: orchestrate S->>Repo: filter / paginate / add Repo->>DB: SELECT/INSERT/UPDATE DB-->>Repo: rows Repo-->>S: ORM instances S-->>Ctl: ResponseSchema Ctl-->>R: ResponseSchema R->>M: serialize Pydantic → JSON M-->>C: HTTP response + X-Request-ID header ``` Every step has a clear owner — the **router never talks to SQLAlchemy**, the **repository never raises HTTP exceptions** (it raises the `not_found_exception` configured on `__init__`, and the exception handler turns it into the JSON envelope). ## Exception envelope The SDK ships [`AppException`][tempest_fastapi_sdk.AppException] + [`register_exception_handlers`][tempest_fastapi_sdk.register_exception_handlers] so every error in your service serializes to the same JSON shape: ```json { "detail": "Usuário não encontrado", "code": "USER_NOT_FOUND", "details": {"user_id": "01923..."} } ``` The frontend branches on `code` (stable, machine-readable), never on the (potentially translated) `detail`. ### The 500 goes through CORS too An exception no handler catches becomes a `500` with `code: "INTERNAL_SERVER_ERROR"`. Starlette runs the `Exception` handler inside `ServerErrorMiddleware`, the **outermost** layer of the stack, so on its own that envelope would leave without passing through `CORSMiddleware`: with no `Access-Control-Allow-Origin` the browser discards the response and `fetch` rejects with `TypeError: Failed to fetch` — no status, no `code`, no `X-Request-ID`. That is why `register_exception_handlers` also installs [`ErrorEnvelopeMiddleware`][tempest_fastapi_sdk.ErrorEnvelopeMiddleware] as the **innermost** middleware. From there the 500 passes through every middleware you added, and the order of the calls stops mattering: ```python from fastapi import FastAPI from fastapi.testclient import TestClient from tempest_fastapi_sdk import ( RequestIDMiddleware, apply_cors, register_exception_handlers, ) app: FastAPI = FastAPI() app.add_middleware(RequestIDMiddleware) apply_cors(app, origins=["https://front.example"]) register_exception_handlers(app) @app.get("/boom") async def boom() -> None: raise RuntimeError("unhandled failure") client: TestClient = TestClient(app, raise_server_exceptions=False) response = client.get("/boom", headers={"Origin": "https://front.example"}) print(response.status_code, response.headers["access-control-allow-origin"]) print(response.json()["details"]["request_id"] == response.headers["x-request-id"]) ``` ```text 500 https://front.example True ``` !!! note "What stays the same" - The layer **does not decide CORS**. An origin outside the allow-list still gets no header, on the 500 too. - After sending the envelope the exception is **re-raised**, as Starlette already did: the ASGI server still logs it, and a `TestClient` with the default `raise_server_exceptions=True` still raises it in your test. - A failure after the response started (a stream that breaks mid-body) is re-raised with no second response, because the status is already on the wire. It is logged and reaches `on_server_error` once, like a plain 500. - `register_exception_handlers` must run **before** the application starts; after that the stack is built and it raises `RuntimeError`. ## Where to go next | You want to… | Read | | --- | --- | | Build a feature step by step | **[Tutorial »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/tutorial.md)** | | Wire a specific helper | **[Recipes »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/index.md)** | | Look up a class signature | **[Reference »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/reference.md)** | | Upgrade from an older version | **[Migration guide »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/migration.md)** | ## Controllers & services layering `BaseService[RepositoryT, ResponseT]` and `BaseController[ServiceT]` are generic skeletons matching the SDK layering (router → controller → service → repository). They expose pass-through CRUD methods so simple endpoints can subclass them without overriding anything; you override only methods that need orchestration. What you inherit by subclassing `BaseService[RepositoryT, ResponseT]`: | Method | Returns | Notes | | --- | --- | --- | | `get_by_id(id)` | `ResponseT` | Awaits `repository.get_by_id` + `repository.map_to_response`. Raises `repository.not_found_exception` on miss. | | `get_or_none(filters)` | ``ResponseT | None`` | Same shape, returns `None` instead of raising. | | `list(filters=None, order_by=None, ascending=True)` | `list[ResponseT]` | Returns `[]` on empty match (never raises). | | `paginate(filters=None, order_by=None, page=1, page_size=20, ascending=True)` | `dict` with mapped `items` + `total`/`page`/`page_size`/`pages`. | Offset pagination via `repository.paginate`. | | `count(filters=None)` | `int` | Pass-through to `repository.count`. | | `exists(filters)` | `bool` | Pass-through to `repository.exists`. | | `update(id, data)` | `ResponseT` | Fetch by id, copy the fields present in `data` (typed by `UpdateT`, the optional 3rd generic param — defaults to `BaseSchema`) onto the row, persist, map. `to_dict()` drops unset/`None`, so it serves PUT and PATCH. | | `delete(id)` | `None` | Hard delete via `repository.delete`. | `map_to_response` is `await`-ed when it returns a coroutine, so async mappers work transparently — no method override needed. When the repository declares its optional 2nd generic parameter (`BaseRepository[ModelType, ResponseT]`), `map_to_response` is typed with `ResponseT` and `BaseService` ties its response type to the repository's (`basedpyright` rejects a mismatch at the call site). What you inherit by subclassing `BaseController[ServiceT]` (the older `BaseController[ServiceT, ResponseT]` and `BaseController[ServiceT, ResponseT, UpdateT]` forms remain accepted for compatibility, while pass-through methods read both response and update types straight from `ServiceT`): | Method | Forwards to | Notes | | --- | --- | --- | | `get_by_id(id)` | `service.get_by_id` | Same return type as the service. | | `list(filters, order_by, ascending)` | `service.list` | Same. | | `paginate(filters, order_by, page, page_size, ascending)` | `service.paginate` | Same. | | `count(filters)` | `service.count` | Same. | | `update(id, data)` | `service.update` | Accepts the service's `UpdateT` and returns its `ResponseT`. | | `delete(id)` | `service.delete` | Same. | !!! tip "Typing the `update` payload end to end" The 3rd generic parameter of `BaseService` is the update schema (`BaseService[Repo, Resp, MyUpdateSchema]`). Because `BaseController[MyService]` derives both the return type and `update`'s `data` type directly from the service, you only need to pass the service once — there is no need to repeat the response or update schema on the controller (repeating them in `BaseController[MyService, Resp, MyUpdateSchema]` stays accepted for compatibility). ```python from tempest_fastapi_sdk import BaseController, BaseService from src.db.repositories import CoinPackRepository from src.schemas import CoinPackResponseSchema, CoinPackUpdateSchema class CoinPackService( BaseService[CoinPackRepository, CoinPackResponseSchema, CoinPackUpdateSchema] ): """Service typed over the concrete update schema.""" class CoinPackController(BaseController[CoinPackService]): """Controller derives both response and update types from the service.""" ``` !!! warning "Requires 0.167.1+" On earlier versions this pair failed type checking with `Type parameter "UpdateT@BaseService" is invariant, but "CoinPackUpdateSchema" is not the same as "BaseSchema"` — `ServiceT`'s bound pinned that invariant parameter to `BaseSchema`. Fixed in 0.167.1; nothing changes at runtime. When a use case needs domain rules, override the inherited method in the service. When a use case needs to coordinate more than one service, override the inherited method (or add a new one) in the controller. The router never grows — it only depends on the controller. ```python # src/services/user_service.py from uuid import UUID from tempest_fastapi_sdk import BaseService from src.db.repositories import UserRepository from src.schemas.user import UserCreate, UserResponse, UserUpdate from src.utils.security import password_utils class UserService(BaseService[UserRepository, UserResponse]): """Business logic for the user feature.""" async def signup(self, data: UserCreate) -> UserResponse: # Business logic — hash the password, then delegate to the repo. instance = self.repository.map_to_model( { "name": data.name, "email": data.email, "password_hash": password_utils.hash(data.password), }, ) created = await self.repository.add(instance) return self.repository.map_to_response(created) # src/controllers/user_controller.py from tempest_fastapi_sdk import BaseController from src.schemas.user import UserCreate, UserResponse from src.services.user_service import UserService class UserController(BaseController[UserService]): """Thin orchestration over UserService.""" async def signup(self, data: UserCreate) -> UserResponse: # Pass-through today; the controller is the seam to add # cross-service coordination later (audit log, outbox event, # downstream notification, etc.) without touching the router. return await self.service.signup(data) # src/api/dependencies/controllers.py from fastapi import Depends from sqlalchemy.ext.asyncio import AsyncSession from src.api.dependencies.resources import db from src.controllers.user_controller import UserController from src.db.repositories import UserRepository from src.services.user_service import UserService def get_user_controller( session: AsyncSession = Depends(db.session_dependency), ) -> UserController: # UserRepository is a subclass of BaseRepository[UserModel] whose # __init__ injects `model=UserModel` via super().__init__(session, model=UserModel). # See the tutorial for the full skeleton: # https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/tutorial/#6-repository return UserController(UserService(UserRepository(session))) # src/api/routers/users.py from fastapi import Depends, status from tempest_fastapi_sdk import TempestAPIRouter from src.api.dependencies.controllers import get_user_controller from src.controllers.user_controller import UserController from src.schemas.user import UserCreate, UserResponse router: TempestAPIRouter = TempestAPIRouter(prefix="/users", tags=["users"]) @router.post( "/", response_model=UserResponse, status_code=status.HTTP_201_CREATED, ) async def create_user( data: UserCreate, controller: UserController = Depends(get_user_controller), ) -> UserResponse: return await controller.signup(data) ``` Keep controllers present even when they only pass through — the import graph stays uniform across services, so adding cross-cutting policy later doesn't change the router signature. ### A controller that orchestrates — `Controller` `BaseController` takes **one** service and passes its CRUD through. A controller that coordinates several services — issue the invoice, post to the ledger, notify — has no `get_by_id` or `delete` of a single resource; inheriting `BaseController` there would hand the router methods that mean nothing. For that case there is [`Controller`][tempest_fastapi_sdk.Controller], the root of the layer: no methods at all, only the convention — services **injected** through `__init__`, no database access (no session, no repository). `BaseController` is its CRUD specialization, so `isinstance(controller, Controller)` holds for both. | Your controller… | Inherit | | --- | --- | | passes one resource's CRUD through, via one service | `BaseController[ServiceT]` | | coordinates several services, with no single-resource CRUD | `Controller` | ```python # src/controllers/billing_controller.py from uuid import UUID from tempest_fastapi_sdk import Controller from src.schemas import ChargeResponse from src.services import InvoiceService, LedgerService, NotificationService class BillingController(Controller): """Charge = invoice + ledger posting + notification.""" def __init__( self, invoices: InvoiceService, ledger: LedgerService, notifications: NotificationService, ) -> None: self.invoices: InvoiceService = invoices self.ledger: LedgerService = ledger self.notifications: NotificationService = notifications async def charge(self, customer_id: UUID, amount_cents: int) -> ChargeResponse: invoice = await self.invoices.issue(customer_id, amount_cents) await self.ledger.post(invoice.id, amount_cents) await self.notifications.invoice_issued(customer_id, invoice.id) return ChargeResponse(invoice_id=invoice.id, amount_cents=amount_cents) # src/api/dependencies/controllers.py from fastapi import Depends from sqlalchemy.ext.asyncio import AsyncSession from src.api.dependencies.resources import db from src.controllers.billing_controller import BillingController from src.db.repositories import InvoiceRepository, LedgerRepository from src.services import InvoiceService, LedgerService, NotificationService def get_billing_controller( session: AsyncSession = Depends(db.session_dependency), ) -> BillingController: return BillingController( InvoiceService(InvoiceRepository(session)), LedgerService(LedgerRepository(session)), NotificationService(), ) ``` The provider builds the services, the controller only receives them — the session lives in the provider and the repositories, never in the controller. !!! note "The convention is not checked at runtime" `__init__` belongs to the subclass, and telling a service from a repository by annotation would need its forward references resolved. Review is what enforces the rule. ## Service, repository and controller patterns The sections above say **what** each layer inherits. This one answers the questions the first real service raises: where the mapper lives, what to do when a service needs **two** repositories, how the `session`, the settings and the mailer reach the controller, where the permission check runs, and what the router returns. All of it in one complete example — copy it into a file and run `uv run python app.py`. In a project each class lives in its own layer (`db/models/`, `schemas/`, `core/exceptions/`, `db/repositories/`, `services/`, `controllers/`, `api/dependencies/controllers.py`, `api/routers/`); here they sit together so the example runs on its own. ```python from collections.abc import AsyncIterator from contextlib import asynccontextmanager from uuid import UUID from fastapi import Depends, FastAPI, status from fastapi.testclient import TestClient from pydantic import Field from sqlalchemy import ForeignKey, String from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import Mapped, mapped_column from tempest_fastapi_sdk import ( AsyncDatabaseManager, BaseAppSettings, BaseController, BaseModel, BaseRepository, BaseResponseSchema, BaseSchema, BaseService, NotFoundException, TempestAPIRouter, ValidationException, raises, register_exception_handlers, ) class Settings(BaseAppSettings): """Service configuration.""" MAX_PRICE_CENTS: int = 100_000 class CategoryModel(BaseModel): """A catalogue category.""" name: Mapped[str] = mapped_column(String(64)) class ProductModel(BaseModel): """A product, always inside a category.""" name: Mapped[str] = mapped_column(String(64)) price_cents: Mapped[int] category_id: Mapped[UUID] = mapped_column(ForeignKey("category.id")) class ProductCreateSchema(BaseSchema): """Product creation payload.""" name: str = Field(min_length=1, max_length=64) price_cents: int = Field(gt=0) category_id: UUID class ProductResponseSchema(BaseResponseSchema): """A product as the API returns it.""" name: str price_cents: int category_id: UUID class CategoryNotFoundError(NotFoundException): """The given category does not exist.""" code: str = "CATEGORY_NOT_FOUND" class ProductNotFoundError(NotFoundException): """The given product does not exist.""" code: str = "PRODUCT_NOT_FOUND" class ProductPriceAboveLimitError(ValidationException): """The price is above the configured ceiling.""" code: str = "PRODUCT_PRICE_ABOVE_LIMIT" class CategoryRepository(BaseRepository[CategoryModel]): """Data access for categories.""" def __init__(self, session: AsyncSession) -> None: """Bind the repository to the session. Args: session (AsyncSession): The request-scoped session. """ super().__init__( session, model=CategoryModel, not_found_exception=CategoryNotFoundError, ) class ProductRepository(BaseRepository[ProductModel, ProductResponseSchema]): """Data access for products; owns the response mapper.""" def __init__(self, session: AsyncSession) -> None: """Bind the repository to the session. Args: session (AsyncSession): The request-scoped session. """ super().__init__( session, model=ProductModel, not_found_exception=ProductNotFoundError, ) def map_to_response(self, instance: ProductModel) -> ProductResponseSchema: """Map a row to the response schema. Args: instance (ProductModel): The ORM row. Returns: ProductResponseSchema: The product, ready for the API. """ return ProductResponseSchema.model_validate(instance) class ProductService(BaseService[ProductRepository, ProductResponseSchema]): """Business rules for products.""" def __init__( self, repository: ProductRepository, *, categories: CategoryRepository, max_price_cents: int, ) -> None: """Take the main repository plus what the creation rule reads. Args: repository (ProductRepository): The resource's own repository. categories (CategoryRepository): Read to validate the category. max_price_cents (int): Price ceiling, taken from the settings. """ super().__init__(repository) self.categories: CategoryRepository = categories self.max_price_cents: int = max_price_cents async def create(self, data: ProductCreateSchema) -> ProductResponseSchema: """Create a product in an existing category, under the price ceiling. Args: data (ProductCreateSchema): The creation payload. Returns: ProductResponseSchema: The created product. Raises: CategoryNotFoundError: When the category does not exist. ProductPriceAboveLimitError: When the price is above the ceiling. """ await self.categories.get_by_id(data.category_id) if data.price_cents > self.max_price_cents: raise ProductPriceAboveLimitError( details={"max_price_cents": self.max_price_cents}, ) instance = self.repository.map_to_model(data.to_dict()) instance = await self.repository.add(instance) return self.repository.map_to_response(instance) class ProductController(BaseController[ProductService]): """Product use cases; a pass-through for now.""" async def create(self, data: ProductCreateSchema) -> ProductResponseSchema: """Create a product. Args: data (ProductCreateSchema): The creation payload. Returns: ProductResponseSchema: The created product. """ return await self.service.create(data) settings: Settings = Settings() db: AsyncDatabaseManager = AsyncDatabaseManager("sqlite+aiosqlite:///:memory:") def get_settings() -> Settings: """Return the process settings. Returns: Settings: The single instance, replaceable through ``dependency_overrides``. """ return settings def get_product_controller( session: AsyncSession = Depends(db.session_dependency), app_settings: Settings = Depends(get_settings), ) -> ProductController: """Build repository, service and controller for one request. Args: session (AsyncSession): The request-scoped session. app_settings (Settings): The process settings. Returns: ProductController: The controller bound to that session. """ service = ProductService( ProductRepository(session), categories=CategoryRepository(session), max_price_cents=app_settings.MAX_PRICE_CENTS, ) return ProductController(service) router: TempestAPIRouter = TempestAPIRouter(prefix="/api/products", tags=["products"]) @router.post("", status_code=status.HTTP_201_CREATED) @raises(CategoryNotFoundError, ProductPriceAboveLimitError) async def create_product( data: ProductCreateSchema, controller: ProductController = Depends(get_product_controller), ) -> ProductResponseSchema: """Create a product. Args: data (ProductCreateSchema): The creation payload. controller (ProductController): Injected by the provider. Returns: ProductResponseSchema: The created product. """ return await controller.create(data) @router.get("/{product_id}") @raises(ProductNotFoundError) async def get_product( product_id: UUID, controller: ProductController = Depends(get_product_controller), ) -> ProductResponseSchema: """Fetch a product by id. Args: product_id (UUID): The product id. controller (ProductController): Injected by the provider. Returns: ProductResponseSchema: The product. """ return await controller.get_by_id(product_id) @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncIterator[None]: """Create the tables and one sample category. Args: app (FastAPI): The application. Yields: None: While the application runs. """ await db.create_tables() async with db.get_session_context() as session: session.add(CategoryModel(id=UUID(int=1), name="Books")) await session.commit() yield await db.disconnect() app: FastAPI = FastAPI(lifespan=lifespan) register_exception_handlers(app) app.include_router(router) with TestClient(app) as client: created = client.post( "/api/products", json={"name": "Dune", "price_cents": 5990, "category_id": str(UUID(int=1))}, ) print(created.status_code, created.json()["name"]) fetched = client.get(f"/api/products/{created.json()['id']}") print(fetched.status_code, fetched.json()["price_cents"]) missing = client.post( "/api/products", json={"name": "Dune", "price_cents": 5990, "category_id": str(UUID(int=2))}, ) print(missing.status_code, missing.json()["code"]) too_high = client.post( "/api/products", json={"name": "Rare", "price_cents": 500_000, "category_id": str(UUID(int=1))}, ) print(too_high.status_code, too_high.json()["code"], too_high.json()["details"]) app.dependency_overrides[get_settings] = lambda: Settings(MAX_PRICE_CENTS=1_000) capped = client.post( "/api/products", json={"name": "Dune", "price_cents": 5990, "category_id": str(UUID(int=1))}, ) print(capped.status_code, capped.json()["details"]) ``` !!! note "`create_tables()` here is a demo shortcut" The example fits in a single file, so it creates the tables straight in the lifespan. In a service, the lifespan calls `sync_schema_async()` over the Alembic migrations: `create_tables()` adds no column to a table that already exists. See [Migrations »](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/migrations.md#3-sync-the-schema-in-the-lifespan). ```text 201 Dune 200 5990 404 CATEGORY_NOT_FOUND 422 PRODUCT_PRICE_ABOVE_LIMIT {'max_price_cents': 100000} 422 {'max_price_cents': 1000} ``` Let's take it piece by piece. ### The mapper lives in the repository `ProductRepository.map_to_response` is the resource's **only** translation from ORM row to response schema. `BaseService` calls it on every path that returns mapped data — `get_by_id`, `get_or_none`, `list`, `paginate` and `update` — so the example's `get_product` works without a line of service code: the inherited `get_by_id` loads the row and runs it through the mapper. The contract, as the code stands today: | `BaseRepository` method | Base default | Who calls it | | --- | --- | --- | | `map_to_response(instance)` | raises `NotImplementedError("Subclasses must implement map_to_response")` | `BaseService.get_by_id` / `get_or_none` / `list` / `paginate` / `update` | | `map_to_model(data)` | `self.model(**data)` | your service, when creating (`self.repository.map_to_model(data.to_dict())`) | | `map_to_schema(instance)` | raises `NotImplementedError` | nothing in the SDK; it exists for your code | It is not abstract in the `abc` sense: a repository without the mapper instantiates fine, and `count`, `exists` and `delete` work. The failure shows up on the first call that maps — over HTTP, a `500`. So every repository handed to a `BaseService` implements `map_to_response`; the example's `CategoryRepository` does not, because no `BaseService` receives it — the `ProductService` only calls `get_by_id` on it, which returns the row unmapped. !!! tip "`async` mapper" When mapping needs an `await` (loading a relationship, say), declare `async def map_to_response`. `BaseService` awaits the result when it is awaitable — nothing to override in the service. Why the repository and not a service helper: the mapper sits next to the query that loaded the row, and `BaseService` can only hand you the inherited CRUD because it knows where to find it. A service that rewrites `list` as `[self.repository.map_to_response(x) for x in ...]` is reimplementing the base. ### One repository per service — and when there are several `BaseService[RepositoryT, ResponseT, UpdateT]` takes **one** repository in `__init__`: the one for the resource whose CRUD it inherits. The third generic parameter is optional (see [the tip above](#controllers-services-layering)). When a use case needs more data, the question is *whose rule it is*: | Situation | Where the second repository goes | | --- | --- | | The rule belongs to this resource and only **reads** or **writes alongside** other data — checking the category exists, writing an order and its items | a keyword-only parameter of the service's `__init__`, after `super().__init__(repository)` — like `categories` in the example | | The other data has rules of its own and already has a service | the **controller** receives both services and orchestrates (see [`Controller`](#a-controller-that-orchestrates-controller)) | | The service has no repository at all (a static catalogue, a facade over an external API) | no `BaseService`; mark the class with `# tempest: no-base-service` | `ProductService.__init__` adds dependencies, so it is not the redundant `__init__` that `SVC003` flags — that rule only flags one that stores the repository and nothing else. !!! warning "Two writes, one transaction" Every `BaseRepository` write method `COMMIT`s on its own. When the rule writes through two repositories, wrap both writes in `async with self.repository.transaction():`. The block covers every repository on the **same** `AsyncSession` — and the provider is what guarantees that, by building both on the request's session. Details in [Transactions](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/transactions.md). ### Controllers arrive through `Depends` providers `get_product_controller` is the only place that knows how to build the graph: it opens the request's session, reads the settings, builds both repositories, the service and the controller. The router only declares `controller: ProductController = Depends(get_product_controller)`. In a project the providers live in `src/api/dependencies/controllers.py`, and the process-wide resources (`db`, storage, mailer) in `src/api/dependencies/resources.py`. Each of the provider's inputs is another `Depends`, never a module import read in the middle of the body — that is what makes the example's last request work: a `dependency_overrides[get_settings]` changed the price ceiling without touching the router, the controller or the service. The mailer works the same way: ```python from fastapi import Depends from sqlalchemy.ext.asyncio import AsyncSession from tempest_fastapi_sdk import EmailUtils from src.api.dependencies.resources import get_mailer, get_session from src.controllers import InviteController from src.core.settings import Settings, get_settings from src.db.repositories import InviteRepository from src.services import InviteService def get_invite_controller( session: AsyncSession = Depends(get_session), mailer: EmailUtils = Depends(get_mailer), settings: Settings = Depends(get_settings), ) -> InviteController: """Build the invite controller for one request. Args: session (AsyncSession): The request-scoped session. mailer (EmailUtils): The process-wide mailer. settings (Settings): The process settings. Returns: InviteController: The controller wired to those resources. """ service = InviteService( InviteRepository(session), mailer=mailer, code_secret=settings.INVITE_CODE_SECRET, ) return InviteController(service) ``` What the provider prevents is the router building the controller — `InviteController(session, mailer=mailer, code_secret=settings.X)` inside the handler. There the router learns about the session, the settings and three class signatures, and every endpoint that uses the controller repeats the wiring. !!! note "What `tempest new` generates" The scaffold already ships this shape. `src/api/dependencies/controllers.py` holds `get_service_info_controller`, the factory behind the placeholder `GET /api/`, which receives `Settings` through `Depends(get_settings)` and builds the controller with `build_service_info_controller` from `src/scripts/composition.py`, the composition root a task, a script and a test call too; the router (`src/api/routers/service_info.py`) declares `controller: ServiceInfoController = Depends(get_service_info_controller)`. `src/core/settings.py` exposes `get_settings()` with `@lru_cache` — the module-level `settings` stays, as the same instance, for what runs outside a request (resources, logging, the lifespan, `server.py`, Alembic). `src/api/dependencies/resources.py` always holds `db`, `get_db` and `get_session`, `get_mailer` only with `[email]` and `get_storage` only with `[minio]` — along with `EmailSettings` / `StorageSettings` on `Settings`. The generated `tests/integration/system/test_service_info.py` swaps `TITLE` through `dependency_overrides[get_settings]` and checks that `GET /api/` answers the new value. ### Guards: route dependency or `@requires` on the method The SDK gives you two places to check permissions, and they answer different questions: | Tool | Question | Where it runs | | --- | --- | --- | | `make_token_dependency`, `make_jwt_user_dependency`, `make_role_dependency`, `make_permission_dependency` | "who is calling?" / "does the token carry this role or permission?" | route dependency, before the handler | | `@requires(guard, ...)` with `require_authenticated`, `require_active`, `require_admin`, `make_flag_guard`, `make_value_guard` or a guard of your own | "does this already-loaded user satisfy this invariant?" | any function that receives the user — handler, controller or service | The path that keeps rules out of the router: **authentication in the dependency, the invariant on the use-case method**. The dependency resolves the user and the router passes it along; `@requires` sits on the controller method, so whoever calls the use case — an HTTP route, a queue consumer, a CLI command — goes through the same check. ```python import asyncio from uuid import UUID from sqlalchemy import String from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import Mapped, mapped_column from tempest_fastapi_sdk import ( AppException, AsyncDatabaseManager, BaseController, BaseModel, BaseRepository, BaseResponseSchema, BaseService, BaseUserModel, requires, ) from tempest_fastapi_sdk.auth import require_admin class AccountModel(BaseUserModel): """An account that calls the API.""" class ProductModel(BaseModel): """A catalogue product.""" name: Mapped[str] = mapped_column(String(64)) class ProductResponseSchema(BaseResponseSchema): """A product as the API returns it.""" name: str class ProductRepository(BaseRepository[ProductModel, ProductResponseSchema]): """Data access for products.""" def __init__(self, session: AsyncSession) -> None: """Bind the repository to the session. Args: session (AsyncSession): The active session. """ super().__init__(session, model=ProductModel) def map_to_response(self, instance: ProductModel) -> ProductResponseSchema: """Map a row to the response schema. Args: instance (ProductModel): The ORM row. Returns: ProductResponseSchema: The product, ready for the API. """ return ProductResponseSchema.model_validate(instance) class ProductService(BaseService[ProductRepository, ProductResponseSchema]): """Business rules for products.""" class ProductController(BaseController[ProductService]): """Product use cases.""" @requires(require_admin) async def remove(self, product_id: UUID, user: AccountModel) -> None: """Delete a product; administrators only. Args: product_id (UUID): The product to delete. user (AccountModel): The caller, already authenticated. """ await self.service.delete(product_id) async def main() -> None: """Call the use case as a regular account, then as an administrator.""" db: AsyncDatabaseManager = AsyncDatabaseManager("sqlite+aiosqlite:///:memory:") await db.create_tables() admin = AccountModel(email="ana@example.com", hashed_password="x", is_admin=True) member = AccountModel(email="bia@example.com", hashed_password="x", is_admin=False) async with db.get_session_context() as session: repository = ProductRepository(session) product = await repository.add(ProductModel(name="Dune")) controller = ProductController(ProductService(repository)) try: await controller.remove(product.id, member) except AppException as exc: print(exc.status_code, exc.code) await controller.remove(product.id, admin) print("left:", await controller.count()) await db.disconnect() asyncio.run(main()) ``` ```text 403 FORBIDDEN left: 0 ``` The guard found the user by annotation (`AccountModel` inherits `BaseUserModel`), refused the regular account by raising `ForbiddenException` — which `register_exception_handlers` turns into the `403` envelope — and let the administrator through. The full guard contract, `meta=` and the `tempest permissions` linter are in [Permission guards](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/permission-guards.md). ### The router returns a schema Every handler in the example annotates its return with the response schema (`-> ProductResponseSchema`) and returns what the controller handed back. With the mapper in the repository, the schema leaves the service ready — the router imports nothing from `db/` and never sees an ORM row. FastAPI uses the return annotation as the `response_model`, so OpenAPI documents the schema without a repeated `response_model=` on the decorator. ### What `tempest lint-layers` checks Some of these rules have a gate; some do not. `tempest lint-layers` (and the `lint-layers` step of `tempest check`) reads the code with `ast` and flags, as an **error**: | Code | What it flags | | --- | --- | | `SVC001` | a public class in `services/` that does not inherit `BaseService` | | `SVC002` | a second public class or a module-level function in a `services/` file | | `SVC003` | a service `__init__` that only stores the repository | | `REPO001` | a repository method that only forwards to a `BaseRepository` method | | `ENUM001` | a `BaseStrEnum` whose name does not end in `Enum` | | `RTR001` | a `*Controller` / `*Service` class called inside `routers/` instead of arriving through `Depends` | | `RTR002` | a route whose return annotation or `response_model=` names an ORM model | The file-shape rules — context package, import through the layer, what services and controllers receive, one router per file, the suite — enter as **warnings** (`LAY*`, `IMP*`, `DI*`, `REPO002`, `RTR003`–`RTR006`, `STR*`, `TST*`) and are in [Recommended architecture](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recommended-architecture.md). Run over a `src/` with a `FamilyService` whose `__init__` only calls `super().__init__(repository)`, a `ProductService` like the example's and a `class UserRole(BaseStrEnum)`, the result is this (paths shortened): ```text src/core/enums.py:4: ENUM001 `UserRole` inherits BaseStrEnum; rename it to `UserRoleEnum`. The database type name does not change (enum_type_name drops one trailing `Enum`), so no migration is needed. src/services/family.py:5: SVC003 `FamilyService.__init__` only stores the repository, which BaseService already does; delete it. ``` `ProductService`, which adds `categories` and `max_price_cents`, passes clean. About `ENUM001`: from v0.313.0 `enum_type_name` drops one trailing `Enum` from the class name before appending `_enum`, so `UserRole` and `UserRoleEnum` map to the same `user_role_enum` type — renaming the class to the suffix needs no `TempestEnum(UserRoleEnum, name="user_role_enum")` on every column. A database created earlier, with the doubled name, is covered in [Enum columns › Renaming the type](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/enum-columns.md#renaming-the-type). Replace the router's `Depends(get_product_controller)` with `ProductController(ProductService(ProductRepository(session)))` and the same run reports `RTR001` on that line, once per class built; annotate the route with `-> ProductModel` and it reports `RTR002`. **No gate**, on purpose, for one rule: where the guard sits. `@requires` is valid on the route handler and on the controller method alike — the [permission guards](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/permission-guards.md) recipe uses the route as its first form — so a check that flagged the route would flag correct code. Choosing the controller method, as above, is review. Full table, the `# tempest: router-builds` opt-out and what the router rules cannot see in [CLI › Layer rules](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/lint-layers.md). ### Recap - **Mapper in the repository.** `map_to_response` is required on every repository handed to a `BaseService`; it may be `async`. - **One repository per `BaseService`.** Extra data this resource's rule reads or writes alongside comes in as a keyword-only `__init__` parameter; a resource with rules of its own has its own service, and the controller orchestrates. - **Writes through two repositories** go inside `self.repository.transaction()`, on the same session. - **The controller comes from a provider** in `api/dependencies/controllers.py`, which receives session, settings and mailer through `Depends`. - **Authentication in the route dependency; the invariant with `@requires`** on the use-case method. - **The router returns a schema**, annotated on the return. - `tempest lint-layers` checks `SVC001`–`SVC003`, `REPO001`, `ENUM001`, `RTR001` and `RTR002` as errors, and the file-shape rules of [Recommended architecture](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recommended-architecture.md) as warnings; where the guard sits is review. --- Source: https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recommended-architecture.md # Recommended architecture The [Architecture](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/architecture.md) page says **which layers exist**. This one says **how each file inside them is shaped**, in a way that works the same for someone joining the project and for an AI writing code in it: a file's name says what it holds, the dependency graph is predictable, and the suite explains what each test proves. Every rule here has **a code** that `tempest check` enforces. That is the point: in a real service (`transport-backend`, recorded in [#616](https://github.com/mauriciobenjamin700/tempest-fastapi-sdk/issues/616)), the rules that lived only in `CLAUDE.md` were broken in hundreds of places when the first guard was written. Prose is not a gate. !!! tip "`tempest new` already ships this way" The project `tempest new` writes passes every rule on this page, errors and warnings, and turns `layers_strict = true` on. Why each directory it generates exists, and the gate of each item, is in the [Service standard](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/service-standard.md). If you are starting out, this page explains what is already on your disk. If you have an older service, jump to [Migrating an existing service](#migrating-an-existing-service). ## How the gate enforces it `tempest lint-layers` reads the source with `ast` and **never imports the project**. Each violation is one `file:line: CODE message` line, and the message says what to change. The rules on this page enter as **warnings**: they print with `(warning)` and do not fail `tempest check` until you turn on strict mode: ```toml [tool.tempest] layers_strict = true ``` !!! 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). To migrate one rule at a time, filter: ```bash tempest lint-layers --rule IMP002 ``` The full code table, with each one's real output, is in [CLI › Layer rules](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/lint-layers.md). ## 1. One class per file, in a context package **Why:** the file name becomes an index. `services/billing/invoice.py` holds `InvoiceService` and nothing else — whoever looks for the invoice service finds it without opening anything, and a diff touching the file touches only it. A `models/route.py` with five models forces you to open it to learn what is inside. The four layers holding classes — `controllers/`, `services/`, `db/repositories/` and `db/models/` — keep each module in a **context package** (a plural noun of the domain: `products`, `orders`, `billing`), with one class per module. ❌ Before: ```python # src/db/models/route.py from sqlalchemy.orm import Mapped, mapped_column from tempest_fastapi_sdk import BaseModel class RouteModel(BaseModel): """A delivery route.""" __tablename__ = "routes" name: Mapped[str] = mapped_column() class StopModel(BaseModel): """A stop on a route.""" __tablename__ = "stops" address: Mapped[str] = mapped_column() ``` ✅ After — one file per model, and the package re-exporting: ```python # src/db/models/routing/route.py from sqlalchemy.orm import Mapped, mapped_column from tempest_fastapi_sdk import BaseModel class RouteModel(BaseModel): """A delivery route.""" __tablename__ = "routes" name: Mapped[str] = mapped_column() ``` ```python # src/db/models/routing/__init__.py from .route import RouteModel as RouteModel from .stop import StopModel as StopModel __all__: list[str] = ["RouteModel", "StopModel"] ``` | Code | Reports | | --- | --- | | `LAY001` | a second class or a module-level function in `controllers/`, `repositories/` or `models/` | | `LAY002` | a module directly at the root of one of the four layers | | `SVC002` (error) | the same in `services/` | The context name is free: the list the project's `CLAUDE.md` suggests is a guide, not a limit. ### The file name does not repeat the layer The directory already says the layer; the file says what it holds. The class keeps its suffix, because it is the name every call site reads: | ✅ Right | ❌ Wrong | | --- | --- | | `services/orders/checkout.py` → `CheckoutService` | `services/orders/checkout_service.py` | | `controllers/orders/checkout.py` → `CheckoutController` | `controllers/orders/checkout_controller.py` | | `db/repositories/orders/order.py` → `OrderRepository` | `db/repositories/orders/order_repository.py` | A controller inherits one of the SDK's two bases, the same ones the scaffold uses: `BaseController[Service]` when it passes **one** service's CRUD through (its response and update schemas come straight from the service; `BaseController[Service, Schema]` stays accepted for compatibility), and `Controller` when it coordinates several (or none, like the `ServiceInfoController` that `tempest new` writes). ### At most 1000 lines per file Code **and** tests, with no exception list. A big file is hard to change and to review: a big service becomes several, one per responsibility (`services/orders/checkout.py`, `services/orders/refund.py`); a big test file becomes one per theme; a big `__init__.py` becomes a subpackage per domain. | Code | Reports | | --- | --- | | `LAY003` | a module of one of the four layers carrying that layer's suffix in its name (`_controller`, `_service`, `_repository`, `_model`) | | `SIZE001` | a source or test module over 1000 lines, reported at line 1001 | ## 2. Import through the layer package; relative `__init__` **Why:** a package's internal path is its own business. Code importing `from src.services.billing.invoice import InvoiceService` breaks the day the file moves; code importing `from src.services import InvoiceService` does not. And an `__init__.py` importing its neighbours by absolute path repeats the package's own name on every line. ✅ The package imports its neighbours relatively; the rest of the code imports through the package: ```python # src/services/__init__.py from .billing import InvoiceService as InvoiceService from .products import ProductService as ProductService __all__: list[str] = ["InvoiceService", "ProductService"] ``` ```python # src/controllers/billing/invoice.py from tempest_fastapi_sdk import BaseController from src.services import InvoiceService class InvoiceController(BaseController[InvoiceService]): """Invoice coordination.""" ``` | Code | Reports | | --- | --- | | `IMP001` | an `__init__.py` importing a module of its own package by absolute path | | `IMP002` | importing a name from its submodule when a package above already re-exports it (followed transitively, through `import *` too) | | `INIT001` | an `__init__.py` holding more than re-exports and `__all__`: a `def`, a `class`, a call, a constant | An `__init__.py` **only re-exports**. Code that assembles something lives in a module of the package and is re-exported: router composition in `router.py`, a factory in `factory.py`, a seed run in `runner.py`. ❌ 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: ```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"] ``` !!! warning "When the package would close a cycle" `IMP002` suggests the top-most package that re-exports the name **without containing** the importing module. Even so, importing through the package sometimes closes a cycle — in the transport service, tasks and scripts imported `api.dependencies.resources` directly, because importing the `api.dependencies` package would close a cycle with `src.tasks`. That case is a [declared exception](#declared-exception), not an import rewrite. ## 3. What services and controllers receive **Why:** a service taking the `AsyncSession` builds its own repositories, so nobody outside can swap them in a test. A service taking another service hides an orchestration that is the controller's job. And a class with a `from_session` knows how to build its own graph: the knowledge of "what needs what" spreads over every class, and every call site repeats the assembly. ❌ Before: ```python # src/services/wallet/settlement.py from sqlalchemy.ext.asyncio import AsyncSession from src.db.repositories import SettlementRepository class SettlementService: """Settles the held balance.""" def __init__(self, session: AsyncSession) -> None: """Keep the session.""" self.repository = SettlementRepository(session) @classmethod def from_session(cls, session: AsyncSession) -> "SettlementService": """Build the service over a session.""" return cls(session) ``` ✅ After — the service receives the repository, and the graph is assembled in one place, the **composition root**: ```python # src/scripts/composition.py from sqlalchemy.ext.asyncio import AsyncSession from src.controllers import SettlementController from src.db.repositories import SettlementRepository from src.services import SettlementService def build_settlement_controller(session: AsyncSession) -> SettlementController: """Assemble the settlement controller over one session. Args: session (AsyncSession): The session the repository reads through. Returns: SettlementController: The controller, fully wired. """ return SettlementController(SettlementService(SettlementRepository(session))) ``` The request provider in `api/dependencies/controllers.py` calls `build_settlement_controller(session)` with the session `Depends` resolved; a task, a queue consumer, a seed and the suite call the same function. The graph is written once. | Code | Reports | | --- | --- | | `DI001` | an `AsyncSession` parameter in a service or controller `__init__` | | `DI002` | a service taking a `*Service`, a controller taking a `*Controller` | | `DI003` | a function or method named `from_session`, anywhere | The real case where two services must go together exists — in the transport service, the settlement and the wallet credit land in the same transaction. It becomes a [declared exception](#declared-exception), aimed at that one parameter. For the SDK's wallet, since v0.330.0 not even that: the balance write is the [`WalletLedger`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/wallet.md#the-ledger-not-the-service-walletledger), a data layer the service receives the way it receives a repository. ## 4. A repository does not import a repository **Why:** a query over two tables is a `select()` with a `join`, in the repository that owns the query. A repository importing another to "reuse" a query creates a dependency between data classes no service sees, and combining two repositories is exactly the service's job. | Code | Reports | | --- | --- | | `REPO002` | importing a `*Repository` inside `repositories/` (a name used only as a class base — the project's base repository — passes) | ## 5. One router per file; `/api` once; `TempestAPIRouter` **Why:** with `/api` repeated in every `include_router` (22 times, in the transport service), changing the API prefix or mounting a domain outside it turns into a prefix hunt. And two routers in one file hide one of them from whoever looks by name. ✅ Each domain declares only its own prefix; `/api` appears in one place: ```python # src/api/routers/api.py from fastapi import APIRouter from .orders import router as orders_router from .service_info import router as service_info_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(service_info_router) api.include_router(orders_router) return api ``` The domain router has a shape too. The text Swagger shows lives in `api/docs/.py`, one `EndpointDoc` per handler, not in `SUMMARY_*` constants at the top of the router; and the router is a `TempestAPIRouter`, which turns the `@raises(...)` below the decorator into the route's `responses=` — on a `fastapi.APIRouter` the same tag does nothing. ❌ Before: ```python # src/api/routers/orders.py from uuid import UUID from fastapi import APIRouter, Depends from src.api.dependencies import get_order_controller from src.controllers import OrderController from src.schemas import OrderResponseSchema SUMMARY_GET_ORDER: str = "Get an order" router: APIRouter = APIRouter(prefix="/orders", tags=["orders"]) @router.get("/{order_id}", summary=SUMMARY_GET_ORDER) async def get_order( order_id: UUID, controller: OrderController = Depends(get_order_controller), ) -> OrderResponseSchema: """Get an order.""" return await controller.get_by_id(order_id) ``` ✅ After: ```python # src/api/docs/orders.py from .base import EndpointDoc GET_ORDER: EndpointDoc = { "summary": "Get an order", "description": "Returns the order by id. Responds 404 (ORDER_NOT_FOUND) when it does not exist.", } ``` ```python # src/api/routers/orders.py from uuid import UUID from fastapi import Depends from tempest_fastapi_sdk import TempestAPIRouter, raises from src.api.dependencies import get_order_controller from src.api.docs import orders as order_docs from src.controllers import OrderController from src.core.exceptions import OrderNotFoundException from src.schemas import OrderResponseSchema router: TempestAPIRouter = TempestAPIRouter(prefix="/orders", tags=["orders"]) @router.get("/{order_id}", **order_docs.GET_ORDER) @raises(OrderNotFoundException) async def get_order( order_id: UUID, controller: OrderController = Depends(get_order_controller), ) -> OrderResponseSchema: """Get an order.""" return await controller.get_by_id(order_id) ``` The why of each half, with the measured OpenAPI that `@raises` produces, is in the 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) and [Route errors](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/service-standard.md#route-errors-tempestapirouter-raises). The `build_api_router` aggregator stays an `APIRouter`: the errors are built by the router the handler is registered on. | Code | Reports | | --- | --- | | `RTR003` | more than one router (`APIRouter(...)`, `TempestAPIRouter(...)` or a project subclass) in a `routers/` module | | `RTR004` | a `/api` prefix (or below it) outside a `build_api_router` function | | `RTR005` | a `fastapi.APIRouter(...)` in a `routers/` module, outside `build_api_router` | | `RTR006` | `summary=` or `description=` in the decorator of a route in `routers/` | ## 6. No nested function, no private module helper **Why:** a function defined inside another has no importable name, no test of its own, and carries state through a closure, invisible in its signature. A module-level `_x` function is a helper with no home: nobody reuses it, and it drops out of the package's index. ❌ Before: ```python # src/utils/notify.py from collections.abc import Awaitable, Callable def make_sender(channel: str) -> Callable[[str], Awaitable[None]]: """Build a sender for the channel.""" async def send(message: str) -> None: """Send the message.""" print(channel, message) return send ``` ✅ After — state becomes a callable object; a fixed argument becomes `functools.partial` over a module-level function: ```python # src/utils/notify.py from collections.abc import Coroutine from functools import partial from typing import Any async def send(message: str, *, channel: str) -> None: """Send the message through the channel. Args: message (str): The text. channel (str): Where it goes. """ print(channel, message) class ChannelSender: """A sender bound to a channel, with visible state.""" def __init__(self, channel: str) -> None: """Keep the channel. Args: channel (str): Where the messages go. """ self.channel: str = channel async def __call__(self, message: str) -> None: """Send a message through the stored channel. Args: message (str): The text. """ await send(message, channel=self.channel) send_by_email: partial[Coroutine[Any, Any, None]] = partial(send, channel="email") """The same sender, with the channel already fixed.""" ``` | Code | Reports | | --- | --- | | `STR001` | a function defined inside another (in the source **and** the suite) | | `STR002` | a module-level function whose name starts with a single `_` (in the source **and** the suite) | In the suite, the private helper becomes a fixture or a public helper module — in the transport service there were 174 nested functions and 76 `_x` helpers in the tests alone. ## 7. A task is registration only **Why:** the API process should not import the tasks' code — and with it the whole graph they use. A 400-line `tasks.py` mixes registration, rules and scheduling. The task layer `tempest new --extras tasks` writes splits it like this: | File | Role | | --- | --- | | `tasks/names.py` | `*_TASK_NAME` and `*_SCHEDULE` (with `every_n_minutes` / `daily`); imports nothing from the project | | `tasks/example.py` | registration only: `@tq.cron(EXAMPLE_SCHEDULE, name=EXAMPLE_TASK_NAME)`, calling the script | | `scripts/example.py` | the work, callable with or without a worker | | `tasks/dispatch.py` | `TaskDispatcher`: the API enqueues **by name**, without importing the task | | `tasks/worker.py` | imports the task modules and exposes `broker` / `scheduler` | Sending by name uses [`TaskQueue.enqueue_by_name`](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/queue-tasks/tasks.md#enqueue-by-name-enqueue_by_name), and the task's retry policy still applies — the worker restores the labels it was registered with. !!! danger "A task name is for life" A queued message keeps the name. Renaming `EXAMPLE_TASK_NAME` strands the old messages: the worker logs `task "" is not found` and drops them. When reorganizing tasks, **move the code and keep the name**. ## 8. Documented schema **Why:** the client reads the `openapi.json`. A field without `title`, `description` and `examples` arrives there with a name and a type only — 370 fields, in the transport service. A leaf field carries all three; a field holding another schema, only `title` and `description`. This is the only rule that has to import the project, so it runs in the suite (`assert_schema_metadata`) and in the `tempest lint-schemas` command — details in [CLI › Schema metadata](https://mauriciobenjamin700.github.io/tempest-fastapi-sdk/en/recipes/cli/lint-schemas.md). ## 9. The suite explains what it proves **Why:** a test is executable documentation. The docstring says the situation it builds and what it proves; a test that checks nothing always passes; `pytest.raises(Exception)` passes with any bug; and a drawn value in a `parametrize` id makes each `pytest -n` worker collect different tests — the transport suite did not run in parallel because of it (4 min serially, 47 s in parallel after the fix). ✅ The shape: ```python # tests/test_orders.py from fastapi.testclient import TestClient from src.api.app import create_app def test_a_duplicate_order_is_refused() -> None: """Cenário: the same order sent twice. Esperado: the second answers ``409`` with ``ORDER_DUPLICATED``. """ with TestClient(create_app()) as client: payload = {"code": "A-1"} assert client.post("/api/orders", json=payload).status_code == 201 duplicate = client.post("/api/orders", json=payload) assert duplicate.status_code == 409 assert duplicate.json()["code"] == "ORDER_DUPLICATED" ``` | Code | Reports | | --- | --- | | `TST001` | a test docstring without `Cenário:` and `Esperado:` | | `TST002` | a test with no `assert`, no `pytest.raises`/`warns` and no `assert*` call | | `TST003` | `pytest.raises(Exception)` or `BaseException` | | `TST004` | a `parametrize` id holding a value drawn at import | `TST004` follows the measurement, not the assumption: a **bare** `uuid4()` or `datetime.now()` is ided by position and passes; it becomes a problem once it turns into text (`str(uuid4())`, `uuid4().hex`) or sits in `ids=`. ## Declared exception Every rule admits the case you keep on purpose — **with its reason written**, in one place, reviewed in the diff like code: ```python # tests/architecture_exceptions.py ARCHITECTURE_EXCEPTIONS: dict[str, str] = { "DI002 src/services/wallet/settlement.py::SettlementService.wallet_service": ( "the settlement and the credit land in the same transaction" ), } ``` The key is `" "` (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.