FastAPI with Python for AI Backends
From one FastAPI endpoint to a production AI service.
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.
01HTTP, 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.
- Follow an HTTP request through FastAPIAn HTTP request is a method, a path, headers and an optional body. Before it reaches your FastAPI function it passes through TLS termination, usually a reverse proxy, and an ASGI server such as Uvicorn, which turns raw bytes into a Python call. FastAPI then routes it, runs dependencies and validation, calls your handler and serialises the return value into a JSON response.13 min
- Run a typed FastAPI service locallyA first FastAPI service needs only a virtual environment, a few pinned packages and one Python file that creates the app. You run it with Uvicorn or the fastapi command, which reloads on code changes during development. FastAPI then serves interactive OpenAPI docs, and a curl smoke test proves the service answers correctly.11 min
- Async Python and blocking work in FastAPIFastAPI runs async def routes on one event loop, which handles many requests at once as long as each one awaits its slow network calls. Plain def routes run in a thread pool so blocking code does not freeze the loop. CPU-heavy work belongs in separate processes or worker services, and limits on concurrency protect the service when traffic outruns capacity.13 min
02Contracts and application wiring
Beginner. Pydantic models, dependency injection, lifespan and error contracts that clients can rely on.
- Pydantic request and response models in FastAPIA contract is the promise your API makes about what it accepts and what it returns. In FastAPI you write that promise as typed path, query and body parameters plus Pydantic request and response models, and FastAPI validates input, filters output and publishes it all in OpenAPI. Stable models and predictable pagination let clients build on your API without breaking when you change internals.12 min
- Routers, dependencies, settings and lifespanAs an app grows you split routes into APIRouter modules and give them what they need through dependencies declared with Depends. Settings come from the environment through a typed settings class, and expensive shared objects such as an HTTP client or database pool are created once in the lifespan handler and closed on shutdown. Because everything arrives through dependencies, tests can swap in fakes without touching route code.11 min
- HTTP error contracts clients can useAn error contract tells clients exactly what failures look like: which status code, which JSON shape, and which fields they can rely on. Good FastAPI services use the right status codes, return one consistent error body, map internal exceptions to safe messages, and attach a request ID to every response so support can find the logs. Stable OpenAPI operation IDs keep generated clients working as the API evolves.12 min
03Application data and access control
Intermediate. PostgreSQL with async sessions and migrations, authentication with tenant isolation, and Redis caching and quotas.
- Connect FastAPI to PostgreSQL with async sessionsThe document Q&A service keeps its users, documents, conversations and ingestion jobs in PostgreSQL. FastAPI talks to it through SQLAlchemy 2.0 async sessions: each request gets one session, does its reads and writes inside one transaction, and either commits everything or rolls everything back. Alembic migrations change the schema in small, reviewed, reversible steps.14 min
- Authenticate requests and isolate tenantsThe API does not handle passwords. An identity provider signs in the user and issues a token; FastAPI checks its signature, issuer, audience and expiry on every request, then reads the user and tenant IDs from it. Every query is then scoped to that tenant on the server, so a valid user from one company can never read another company's documents.12 min
- Redis caching and per-user usage limitsRedis is an in-memory key-value store that the service uses for two jobs: caching results that are expensive to compute, and counting how many model calls each user makes. Cached values get a time to live and keys that include the tenant and the model and prompt versions. Quotas use atomic increments and return 429 when spent, and you decide in advance what happens when Redis is down.13 min
04Inference and AI request orchestration
Intermediate. One interface for model calls, resilience against provider failures, and validated structured output and tool use.
- One application interface for model callsA model gateway is one small interface that every part of the service uses to call a language model. Behind it sit adapters: a deterministic fake for local work and tests, a remote provider reached through its SDK or HTTP API, and optionally a local model server. Routes never see provider SDKs, API keys or raw responses, only typed requests and results that record which model and prompt version produced them.12 min
- Deadlines, retries and fallbacks for model callsModel providers are slow sometimes and fail sometimes. A resilient gateway gives each request a deadline, sorts errors into retryable and permanent, retries only the retryable ones a few times with exponential backoff and jitter, and then either falls back honestly or fails with a clear error. It records usage and latency for every attempt so you can see what is happening.13 min
- Validate structured model output and tool requestsWhen the service needs structured data from a model, such as an answer with citations or a request to run a tool, it parses the output into Pydantic models instead of trusting raw text. A discriminated union tells the parser which shape to expect, invalid output gets one repair attempt or a clean error, and refusals are handled as normal results. Tools come from a server-side allowlist, are read-only, check permissions with the real user's identity and run inside a loop with a hard turn limit.13 min
05Ingest, index and retrieve
Intermediate. Accept uploads, run a durable ingestion worker, and retrieve tenant-filtered chunks with citations from pgvector.
- Accept a document and start an ingestion jobAn upload endpoint should do as little as possible while the client waits: check the file, store it in object storage, record a document and a job, and answer 202 Accepted. The slow work of reading, chunking and embedding happens later in a worker. The client then polls a job URL to see progress, so a large PDF never ties up a request for minutes.12 min
- Run a durable ingestion pipelineA worker is a separate process that takes ingestion jobs and runs the slow steps: download, extract, chunk, embed and index. It must survive crashes, retry without creating duplicates, and park jobs that keep failing in a dead-letter state. The hard part is keeping the database and the queue consistent when a crash hits between two writes.12 min
- Tenant-filtered retrieval with citations in pgvectorRetrieval turns stored documents into small, searchable chunks with embeddings, then finds the chunks closest to a question. With pgvector the chunks, vectors and metadata live in Postgres, so you can filter by tenant in the same query as the similarity search. Each result keeps its source so the answer can cite it, and weak matches lead to an honest low-confidence reply.11 min
06Connect web clients and live responses
Intermediate. Connect a Next.js client, stream answers over server-sent events, and handle disconnects and slow streams.
- Connect React or Next.js to FastAPIA Next.js frontend and a FastAPI backend usually run on different origins, so the browser applies CORS rules to every call between them. You either allow the frontend's origin in FastAPI or route calls through a same-origin proxy such as Next.js rewrites. Generate TypeScript types from FastAPI's OpenAPI schema so the client and server agree on every request and response.10 min
- Stream AI responses from FastAPI to a browserServer-sent events (SSE) let a server push a stream of small text events over one HTTP response. FastAPI can produce them with a StreamingResponse of media type text/event-stream, and the browser reads them with fetch so it can send a POST with a JSON body. Typed events such as delta, citation, done and error let the UI show text as it is generated.10 min
- Handle disconnects and slow streamsStreams fail in ways normal requests do not: proxies buffer them, idle connections are closed, and users leave mid-answer. A healthy stream disables buffering, sends heartbeats during long pauses and measures time to first token. When the client goes away, the server should stop the model call too, and once the 200 status is sent, errors must travel as events.11 min
07Test correctness and AI quality
Advanced. Route and dependency tests, retrieval and answer evaluation, and failure drills with local stubs.
- Test FastAPI routes with dependency overridesFastAPI routes get their database sessions, current user and model client through dependencies, so tests can swap any of them for a fake with app.dependency_overrides. Fast unit-style tests use fakes and TestClient; slower integration tests run the real lifespan against a real PostgreSQL database. Together they prove the contract, the validation and the tenant boundary without calling a paid model.12 min
- Evaluate retrieval and answer qualityAn AI answer can fail in three separate places: retrieval missed the right chunk, the answer cited the wrong source, or the wording was wrong. A seeded evaluation set of questions with known answers and known source chunks lets you measure each of these on its own, along with latency and cost. Running the same set after every change shows whether quality went up or down.11 min
- Failure drills for an AI backendA failure drill breaks one dependency on purpose, such as a slow model, bad JSON from the model, a crashed worker or a browser that leaves mid-stream, and checks that the system fails cleanly. Local stubs make each drill repeatable and free. The evidence you look for is a stable error response, a job that finishes or retries, released resources and a trace that explains what happened.11 min
08Ship and observe the backend
Advanced. Run the full stack in containers, trace requests end to end, and size and scale the service.
- Deploy the API, worker and database stackThe Q&A service is really four processes: the FastAPI API, the ingestion worker, PostgreSQL and a queue such as Redis. Docker Compose runs all four locally from one file, with health checks, secrets injected at runtime and a one-off migration step before the API starts. The same shape then maps to one managed deployment, where the release plan also says how to roll back.13 min
- Trace an AI request end to endOne question to the Q&A service touches the browser, the API, sometimes a queued job and worker, the retrieval query and a model call. Tracing gives every step the same trace ID so you can see the whole path, how long each part took and where it failed. Structured logs without secrets and a few key metrics, such as token usage, queue lag, error rate and latency percentiles, complete the picture.11 min
- Size and scale an AI backendAPI processes, worker concurrency, database pool sizes and model rate limits are linked: raising one without the others just moves the queue somewhere else. Sizing them together, enforcing token budgets per tenant and load-testing against a local fake model shows where the real limit is. Gradual rollouts and a written runbook keep changes and incidents under control.13 min
09Secure a multi-tenant AI API
Advanced. Treat retrieved text and model output as untrusted data, and manage secrets, retention and deletion everywhere data lives.
- Treat retrieved text and model output as untrustedIn an AI backend, retrieved document text and model output are data from outside your trust boundary, even when they come from your own database or your own provider. Anyone who can upload a document can plant instructions in it, so the model may try to leak data or call tools it should not. You defend by deciding access in code before the model runs, sending the model only what it needs, and checking everything the model asks for before acting on it.13 min
- Secrets, retention and deletion across the stackSecrets and customer data both have a lifecycle: they are created, used, copied into several places and must eventually be rotated or deleted. In a document Q&A service a tenant's data lives in Postgres, object storage, the vector index, caches, logs, backups and possibly a model provider. A real deletion or rotation plan lists every one of those places, says how long data stays in each, and leaves an audit record that proves the work was done.12 min
10Capstone: document Q&A service
Advanced. Design, build and release a multi-tenant document Q&A service with a deterministic fake model.
- Capstone: design the document Q&A serviceBefore writing code, you write down how the document Q&A service will work: the two main paths through the system, the HTTP and event contract, the data model, which failures it must handle and the fixtures you will test against. Two demo tenants, contoso and fabrikam, share one synthetic document set so every design choice can be checked for tenant isolation. A one-page design like this keeps the build focused and gives reviewers something concrete to challenge.13 min
- Capstone: build the document Q&A serviceThis milestone turns the design into a running service: upload and ingestion, job polling, tenant-aware retrieval, streamed chat with citations and a minimal browser page, all on a deterministic fake model. Everything runs locally with Docker Compose, so it costs nothing and gives the same answers every time. A real model provider can be plugged in later behind the same adapter.12 min
- Capstone: verify, release and hand overThe final milestone proves the service works and hands it over safely. You run the tests and the eval set, break something on purpose and show it recover, capture a redacted trace, write a migration and rollback checklist, and either deploy or document a deployment with a teardown plan. The result is a package another engineer could pick up and run without asking you questions.12 min