FastAPI Cookbook
“How would you do X?” — practical, production-ready recipes with the approach, full code, pitfalls and variations.
FastAPI
- Add liveness and readiness endpoints to FastAPITell Kubernetes or a load balancer when an instance is alive and ready to receive traffic.
- Add OpenTelemetry tracing to FastAPISee where time goes in a request across your API, database and outbound HTTP calls.
- Add request IDs and structured logs to FastAPICorrelate every log line from one request and return the ID to clients for support.
- Build a WebSocket chat endpoint in FastAPIBroadcast messages to all users in a room in real time, across multiple app instances.
- Cache FastAPI responses in RedisSpeed up an expensive read endpoint and invalidate the cache when data changes.
- Call external APIs with retries and timeouts from FastAPIIntegrate a flaky third-party API without blocking workers or hammering it during outages.
- Implement role-based access control in FastAPIRestrict endpoints by permission and make sure users only access their own resources.
- Isolate tenants in a multi-tenant FastAPI appServe many customer organizations from one database without any data leaking between them.
- Paginate with cursors in FastAPIReturn large result sets page by page, fast and stable even while new rows are inserted.
- Rate limit FastAPI endpoints with RedisLimit login attempts and API usage per user or IP across multiple workers and instances.
- Return RFC 9457 Problem Details from FastAPIMake every error response — validation, not found, conflicts, crashes — use one consistent JSON shape.
- Run background jobs from FastAPI with ARQGenerate reports and send emails asynchronously with retries, outside the request.
- Run scheduled tasks alongside FastAPIRun a cleanup every hour and a report every night without duplicating work across replicas.
- Stream responses with Server-Sent EventsStream progress updates or LLM tokens to the browser as they're produced.
- Support Idempotency-Key headers in FastAPILet clients retry POST requests (like creating payments) safely without duplicate side effects.
- Test FastAPI endpoints against a real databaseWrite fast, isolated API tests that hit PostgreSQL but leave no data behind.
- Upload files directly to S3 from a FastAPI appLet clients upload large files without streaming them through your API servers.
- Use refresh tokens in HttpOnly cookies with FastAPIKeep users signed in for weeks while access tokens stay short-lived and safe from XSS.
- Verify incoming webhooks in FastAPIAccept webhooks from a payment provider securely and process each event exactly once.
- Version a FastAPI API without breaking clientsIntroduce breaking changes (renamed fields, new semantics) while existing clients keep working.