FastAPI with Python for AI Backends
Build a document question-and-answer service step by step: a typed async API, tenant-scoped data in PostgreSQL, a model gateway, durable ingestion, retrieval with citations, streamed answers, tests, deployment and operations. Modules 1–2 are beginner FastAPI, modules 3–6 are intermediate backend work, and modules 7–10 cover advanced testing, operations and security. You should already know Python functions, type hints and imports, basic Git, and basic HTTP and SQL; Python from Zero and SQL & PostgreSQL cover those. Everything runs locally with a fake model, so no paid API key is needed.
What you will be able to do
- Build a typed async FastAPI service with stable request, response and error contracts
- Persist tenant-scoped data in PostgreSQL with migrations, auth and Redis quotas
- Wire model calls, ingestion jobs and pgvector retrieval with citations behind one gateway
- Stream answers to a browser over SSE and handle cancellation and slow clients
- Test, deploy, observe and secure the service, and recover from failures on purpose
Roadmap
Bar length shows each module's share of study time.
- 17h 30m3 topics
HTTP, Python and ASGI
Beginner. How a request reaches your code, your first FastAPI service, and when async helps or hurts. Prerequisites: Python basics and HTTP basics.
Show topicsNot startedTrace one request from the client through TLS, proxy, ASGI server, router, dependencies and handler back to a serialised response.
- Read method, path, headers and body
- Place TLS termination and the reverse proxy
- Explain what the ASGI server does
- Follow routing, dependencies and the handler
- See how the response is serialised
Create, run and smoke-test a FastAPI service in a virtual environment with pinned packages.
- Create a venv and pin packages
- Write the app entry point
- Run Uvicorn with reload
- Open the OpenAPI docs
- Smoke-test with curl
Choose between async routes, sync routes, thread pools and workers for a given kind of work.
- Await network I/O in async routes
- Know when FastAPI uses a thread pool
- Spot blocking calls in async code
- Move CPU-bound work to workers
- Apply backpressure with limits
- 28h 30m3 topics
Contracts and application wiring
Beginner. Pydantic models, dependency injection, lifespan and error contracts that clients can rely on.
Show topicsNot startedDefine validated request and response models with filtering and pagination that keep the API stable.
- Use path, query and body parameters
- Validate fields with constraints
- Filter output with response models
- Paginate list endpoints
- Keep response schemas stable
Wire settings, a shared HTTP client and a database pool through dependencies and the lifespan handler.
- Split routes with APIRouter
- Inject services with Depends
- Load settings from the environment
- Open shared clients at startup
- Close them cleanly on shutdown
Return consistent, safe error responses with request IDs and stable operation IDs.
- Pick the right status codes
- Shape validation error responses
- Map exceptions to safe messages
- Add request IDs to every response
- Keep OpenAPI operation IDs stable
Module resources:Pydantic docs ↗ - 311h3 topics
Application data and access control
Intermediate. PostgreSQL with async sessions and migrations, authentication with tenant isolation, and Redis caching and quotas.
Show topicsNot startedModel users, documents, conversations and jobs in PostgreSQL with async sessions, transactions and Alembic migrations.
- Model the core tables
- Use one async session per request
- Commit or roll back as a unit
- Bound the connection pool
- Add indexes and Alembic migrations
Validate tokens from an identity provider and enforce tenant ownership on every query.
- Validate issuer, audience and expiry
- Get the user and tenant from the token
- Enforce ownership on the server
- Separate CORS from cookies and CSRF
- Test cross-tenant access is denied
Cache results safely and enforce per-user quotas in Redis, with a clear plan for Redis outages.
- Set TTLs on cached results
- Build cache keys with tenant and versions
- Count usage with atomic increments
- Return 429 when a quota is spent
- Decide fail-open or fail-closed
- 49h 30m3 topics
Inference and AI request orchestration
Intermediate. One interface for model calls, resilience against provider failures, and validated structured output and tool use.
Show topicsNot startedPut every model call behind one adapter with a fake provider for local work and clear boundaries for inputs, outputs and credentials.
- Define the adapter interface
- Build a deterministic fake provider
- Compare a remote SDK and a local model
- Keep credentials out of call sites
- Record model and prompt versions
Handle slow and failing model providers with deadlines, bounded retries with jitter and honest fallbacks.
- Set a deadline per request
- Classify 429, 4xx and 5xx errors
- Retry with backoff and jitter
- Decide when to fall back
- Track usage and latency
Parse model output into schemas, handle invalid output and refusals, and run only allowlisted tools in a bounded loop.
- Use discriminated Pydantic unions
- Handle invalid output and refusals
- Allowlist read-only tools
- Check permissions on the server
- Bound the tool-call loop
- 511h 30m3 topics
Ingest, index and retrieve
Intermediate. Accept uploads, run a durable ingestion worker, and retrieve tenant-filtered chunks with citations from pgvector.
Show topicsNot startedAccept validated uploads into object storage and return a job that clients can poll.
- Validate file size and type
- Store the file in object storage
- Create document and job IDs
- Return 202 Accepted
- Paginate job status
Process ingestion jobs in a worker that survives crashes, retries safely and parks poison messages.
- Split API and worker duties
- Model job states
- Make retries idempotent
- Add a dead-letter path
- Recover between DB and queue writes
Chunk, embed and query documents per tenant and return answers with sources or an honest low-confidence reply.
- Extract and chunk text
- Store embeddings with versions
- Filter by tenant before top-k
- Return provenance for citations
- Handle low confidence and deletion
Module resources:pgvector ↗ - 69h 30m3 topics
Connect web clients and live responses
Intermediate. Connect a Next.js client, stream answers over server-sent events, and handle disconnects and slow streams.
Show topicsNot startedCall FastAPI from a Next.js client with the right CORS or proxy setup, typed requests and clear UI states.
- Choose CORS or a same-origin proxy
- Configure the API base URL
- Type requests from OpenAPI
- Send authentication safely
- Show upload and polling states
Stream delta, citation, completion and error events from FastAPI to a browser over SSE with fetch.
- Frame events in SSE format
- Return a StreamingResponse
- Read the stream with fetch
- Send delta, citation and done events
- Know when WebSockets fit better
Keep streams responsive through proxies and stop upstream work when the client goes away.
- Disable proxy buffering
- Measure time to first token
- Send heartbeats
- Propagate cancellation upstream
- Report errors after headers are sent
- 710h 30m3 topics
Test correctness and AI quality
Advanced. Route and dependency tests, retrieval and answer evaluation, and failure drills with local stubs.
Show topicsNot startedTest routes, tenant boundaries, lifespan and database integration with pytest, fakes and dependency overrides.
- Use TestClient or async HTTPX
- Override dependencies with fakes
- Test invalid input and tenant boundaries
- Run lifespan in tests
- Use a real database in integration tests
Measure retrieval recall, citation accuracy, answer quality, latency and cost on a seeded fixture set.
- Build a seeded question set
- Measure retrieval recall@k
- Check citation accuracy
- Grade answer quality
- Track latency and cost per run
Simulate timeouts, invalid output, worker restarts and disconnects and prove the system degrades cleanly.
- Stub a slow provider
- Return invalid model output
- Kill and restart the worker
- Disconnect the browser mid-stream
- Check errors, jobs and traces
- 811h3 topics
Ship and observe the backend
Advanced. Run the full stack in containers, trace requests end to end, and size and scale the service.
Show topicsNot startedRun the API, worker, Postgres and queue with Docker Compose and map it to one managed deployment with health checks and rollback.
- Write the Compose file
- Inject secrets at runtime
- Add liveness and readiness probes
- Run migrations before release
- Plan the rollback
Correlate browser, API, worker, retrieval and model activity with traces, privacy-aware logs and key metrics.
- Propagate trace and job IDs
- Write structured logs without secrets
- Record token usage
- Watch queue lag and error rate
- Read latency percentiles
Size API and worker concurrency, pools and token budgets together, load-test them and write the runbook.
- Match pools to concurrency
- Budget tokens and cost per tenant
- Load-test a local fixture
- Roll out changes gradually
- Write an incident runbook
- 96h 30m2 topics
Secure a multi-tenant AI API
Advanced. Treat retrieved text and model output as untrusted data, and manage secrets, retention and deletion everywhere data lives.
Show topicsNot startedDefend against prompt injection and data leaks with tenant filters, minimisation, validated tools and human review.
- Filter context by tenant
- Minimise data sent to models
- Keep secrets out of logs
- Validate tool arguments
- Require review for writes
Rotate secrets and delete a tenant's data from the API, storage, vector index, logs and providers with an audit trail.
- Rotate secrets without downtime
- Set retention per data store
- Delete across index, storage and logs
- Check third-party inference retention
- Record an audit trail
- 1021h3 topics
Capstone: document Q&A service
Advanced. Design, build and release a multi-tenant document Q&A service with a deterministic fake model.
Show topicsNot startedWrite the architecture, API and event contracts, data model, failure paths and evaluation fixtures.
- Draw the request and ingestion diagrams
- Specify the HTTP and event contract
- Design the data model
- List supported failure paths
- Prepare fixtures for two tenants
Build upload, ingestion, polling, tenant-aware retrieval, streamed chat with citations and a minimal UI on a fake model.
- Build upload and ingestion
- Add polling and job status
- Implement tenant-aware retrieval
- Stream chat with citations
- Add a minimal UI and the fake model
Run tests and evals, demonstrate a failure and recovery, and deploy or document deployment with a teardown plan.
- Run tests and the eval set
- Demonstrate a failure and recovery
- Capture a redacted trace
- Write the migration and rollback checklist
- Deploy or document with teardown
Module resources:FastAPI: bigger applications ↗