Lesson 7 of 59How backends work
Your First FastAPI App
Create a FastAPI project with uv, write path operations, run it with fastapi dev, and explore the automatic docs.
FastAPI is one of the most popular Python web frameworks for new APIs, and it is used for everything from small side projects to machine learning services at large companies. The reason is simple: you write ordinary typed Python functions and get routing, validation, JSON and interactive documentation for free. In this lesson you build and run a real one.
Set up the project
You need Python 3.10 or newer (3.13 is a good choice) and uv, the fast Python package and project manager. fastapi[standard] installs FastAPI plus the extras most apps want: Uvicorn, the fastapi command line tool, and a few parsers.
uv init todo-apicd todo-apiuv add "fastapi[standard]"mkdir app && touch app/__init__.py app/main.pyIf you prefer pip: create a virtual environment, activate it, and run pip install "fastapi[standard]". Either way, the dependency ends up listed in pyproject.toml.
- todo-api/
- .venv/created by uv, never commit it
- app/
- __init__.pymakes app a package
- main.pyyour FastAPI app lives here
- .python-versionthe Python version uv will use
- pyproject.tomlproject metadata and dependencies
- uv.lockexact versions of every package, commit it
- README.md
Now the smallest useful app:
from fastapi import FastAPI
app = FastAPI(title="Todo API")
@app.get("/")
def root():
return {"message": "Hello from the Todo API"}Three things are going on. FastAPI() creates the ASGI application object from the last lesson. @app.get("/") registers the function below it for GET requests to /. And the function returns a plain dict, which FastAPI turns into a JSON response with status 200.
Run it
uv run fastapi dev app/main.py FastAPI Starting development server INFO Serving at: http://127.0.0.1:8000 INFO API docs: http://127.0.0.1:8000/docs INFO Will watch for changes in these directories: ['/home/ada/todo-api']fastapi dev starts Uvicorn for you with auto-reload on, listening on 127.0.0.1:8000. Its sibling fastapi run is the production mode: no reload, and it listens on 0.0.0.0. Under the hood both are just uvicorn app.main:app with sensible flags.
Open http://127.0.0.1:8000 in a browser, or use curl in a second terminal:
curl http://127.0.0.1:8000/# {"message":"Hello from the Todo API"}fastapi dev versus fastapi run
The fastapi command comes from the fastapi-cli package, which fastapi[standard] installs along with Uvicorn, python-multipart (forms and uploads), email-validator, the HTTP client that TestClient uses, Jinja2 and pydantic-settings. Plain fastapi without [standard] installs only the framework, so fastapi dev will not exist. That is the right choice for a slim library, and the wrong one for an app.
Both commands find your app the same way. Given a path, they import it and look for an object called app or api. Given nothing, they try main.py, app.py, api.py, then app/main.py and friends. You can make it explicit in pyproject.toml, so every teammate and every script runs the same thing:
[tool.fastapi]
entrypoint = "app.main:app"The differences are all about where the server runs:
fastapi dev | fastapi run | |
|---|---|---|
| Reload on file change | On | Off (reload is slow and memory-hungry) |
| Listens on | 127.0.0.1, only your machine | 0.0.0.0, every interface, needed in a container |
| Workers | One | --workers N for several processes |
| Proxy headers | On, trusted only from 127.0.0.1 by default | Same; list your load balancer in --forwarded-allow-ips |
Useful flags on both: --port (or the PORT environment variable, which many hosting platforms set), --host, and --root-path when a proxy serves the app under a prefix such as /api. In a container you will usually write CMD ["fastapi", "run", "--workers", "4"], and Deploying FastAPI explains how many workers to pick.
Path operations
FastAPI calls a combination of a path (/todos) and an operation (an HTTP method like GET) a path operation. The decorated function is the path operation function. There is one decorator per method: @app.get, @app.post, @app.put, @app.patch, @app.delete.
Here is a tiny todo API that keeps its data in a list. (A list in memory is fine for learning. It disappears on restart, and you will swap it for a database later in the track.)
from fastapi import FastAPI, HTTPException, status
app = FastAPI(title="Todo API")
todos = [
{"id": 1, "title": "Buy milk", "done": False},
{"id": 2, "title": "Write tests", "done": True},
]
@app.get("/todos")
def list_todos():
return todos
@app.get("/todos/{todo_id}")
def get_todo(todo_id: int):
for todo in todos:
if todo["id"] == todo_id:
return todo
raise HTTPException(status_code=404, detail="Todo not found")
@app.delete("/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_todo(todo_id: int):
todos[:] = [t for t in todos if t["id"] != todo_id]Look at todo_id: int. That single type hint tells FastAPI to pull todo_id out of the path, convert "2" to 2, and reply with a 422 error if someone requests /todos/abc. The next lesson is all about that.
The client sends a plain HTTP request to port 8000.
raise HTTPException(...) stops the function and sends an error response: {"detail": "Todo not found"} with status 404. And status_code=status.HTTP_204_NO_CONTENT sets the success code for that route. The status module just holds readable names for the numbers.
Match each request to the decorator that handles it.
What the decorators really do
@app.get(...) does not call your function. It registers it in a table, and the framework calls it later when a matching request arrives. Here is a small imitation you can run. It also shows how FastAPI picks the status code.
Press Run (⌘ Enter) to see what happens.With the MiniApp above, what does this print?
@app.get("/health")
def health():
return "ok"
print(app.handle("GET", "/health")[0], len(app.routes))Automatic docs
Open http://127.0.0.1:8000/docs. You get Swagger UI: every route, its parameters and its responses, with a "Try it out" button that sends real requests. http://127.0.0.1:8000/redoc shows the same information in a reading-friendly layout.
Both pages are drawn from one JSON document at /openapi.json. OpenAPI is a standard format for describing HTTP APIs. FastAPI builds it by inspecting your functions: their paths, their type hints and their docstrings. Because the docs come from the code, they cannot drift out of date.
You can do the same trick with the standard library's inspect module:
Press Run (⌘ Enter) to see what happens.Real OpenAPI documents have more fields, but the idea is identical. Frontend teams often feed /openapi.json into a generator to get a fully typed TypeScript client for your API.
/docs?Status codes and return values
Whatever you return is converted to JSON. Dicts become objects, lists become arrays, and Pydantic models (two lessons from now) become objects shaped by the model. The default status is 200; set another with status_code= on the decorator.
| Code | Meaning | Typical route |
|---|---|---|
200 OK | Success with a body | GET /todos |
201 Created | A new resource was made | POST /todos |
204 No Content | Success, no body | DELETE /todos/7 |
404 Not Found | That resource does not exist | GET /todos/999 |
422 Unprocessable Content | Input failed validation | GET /todos/abc |
lifespan: startup and shutdown
Some work must happen once per process, not once per request: opening a database connection pool, creating one shared httpx.AsyncClient, loading a machine learning model, warming a cache. And it must be undone cleanly when the process stops, or you leak connections on every deploy. FastAPI's answer is a lifespan function: an async context manager where code before yield is startup and code after it is shutdown.
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI, Request
@asynccontextmanager
async def lifespan(app: FastAPI):
client = httpx.AsyncClient(timeout=10) # startup: once per worker process
model = load_model("models/ranker.onnx")
yield {"http": client, "model": model} # the server accepts requests now
await client.aclose() # shutdown: after the last request
app = FastAPI(title="Todo API", lifespan=lifespan)
@app.get("/suggestions")
async def suggestions(request: Request):
client = request.state.http # the dict you yielded
...The dict you yield becomes lifespan state: each request sees its keys on request.state. You can also set attributes on app.state inside the lifespan. Both work; the yielded dict keeps the startup and the values side by side, and in practice you wrap the lookup in a dependency so routes never touch request.state directly (the next lessons show how).
Three things seniors know about lifespan:
- It replaces
@app.on_event("startup")and@app.on_event("shutdown"), which are deprecated. Old tutorials still use them. If you passlifespan=, those handlers do not run at all, so do not mix the two. - It runs in every worker process. With
--workers 4you get four pools and four loaded models. Size your database pool with that in mind, as Performance and Scaling explains. - If startup raises, the server refuses to start. That is a feature: a container that cannot reach its database should crash and be restarted, not serve 500s. Keep startup quick, though, because orchestrators wait for it before routing traffic.
In tests, TestClient(app) alone does not run the lifespan. Use it as a context manager, with TestClient(app) as client:, so startup runs on entry and shutdown on exit. Testing FastAPI builds on this.
fastapi run --workers 4. Your lifespan creates a database pool of 10 connections. How many connections can the app open in total?Return type annotations as response models
You will meet Pydantic models properly in two lessons, but one habit is worth starting now. Annotate what a route returns:
from pydantic import BaseModel
class TodoRead(BaseModel):
id: int
title: str
done: bool
@app.get("/todos/{todo_id}")
def get_todo(todo_id: int) -> TodoRead:
row = {"id": todo_id, "title": "Buy milk", "done": False, "owner_email": "ada@example.com"}
return row # validated against TodoRead, owner_email is droppedA return annotation does three jobs. FastAPI validates the result against the model, so a route that returns the wrong shape fails loudly in your tests instead of sending bad data. It filters the result, so only declared fields leave the server. And it documents the response in /docs, which is what generated frontend clients are built from.
It is also faster. When a route has a response model and uses the default response class, FastAPI serialises the result straight to JSON bytes in Pydantic's Rust core. Without one, it walks the returned dict with jsonable_encoder and then calls json.dumps. This is why the old advice to switch to ORJSONResponse for speed is outdated: those response classes are deprecated, and a response model is the fast path.
When the annotation and the real return value disagree on purpose, for example you return an ORM object or a dict but want TodoRead in the docs, put the model in the decorator: @app.get(..., response_model=TodoRead). The decorator wins over the annotation. If a route returns a Response object directly (a redirect, a file), annotate it as that response class, or pass response_model=None.
Streaming responses and Server-Sent Events
Normally FastAPI builds the whole response body, then sends it. Sometimes you want to send it as it is produced: a 2 GB CSV export that should not sit in memory, tokens from a language model as they arrive, progress updates from a long job. For bytes, use StreamingResponse with a generator:
from collections.abc import Iterator
from fastapi.responses import StreamingResponse
@app.get("/todos/export.csv")
def export_csv() -> StreamingResponse:
def rows() -> Iterator[str]:
yield "id,title,done\n"
for todo in repo.iter_all(batch_size=1000): # never load everything at once
yield f"{todo.id},{csv_escape(todo.title)},{todo.done}\n"
return StreamingResponse(rows(), media_type="text/csv")For a stream of events that a browser should consume, use Server-Sent Events (SSE): one long HTTP response with the text/event-stream content type, made of small text blocks. Current FastAPI has first-class support in fastapi.sse. Set response_class=EventSourceResponse and make the route itself a generator:
from collections.abc import AsyncIterable
from fastapi.sse import EventSourceResponse, ServerSentEvent
from pydantic import BaseModel
class Progress(BaseModel):
pct: int
@app.get("/jobs/{job_id}/events", response_class=EventSourceResponse)
async def job_events(job_id: str) -> AsyncIterable[Progress]:
async for pct in watch_job(job_id):
yield Progress(pct=pct) # sent as data: {"pct":40}
@app.get("/jobs/{job_id}/log", response_class=EventSourceResponse)
async def job_log(job_id: str):
async for line in tail_log(job_id):
yield ServerSentEvent(raw_data=line, event="log", id=line.cursor)Each yielded model or dict is JSON-encoded into a data: line. Yield a ServerSentEvent when you need an event name (the browser's addEventListener("log", ...)), an id (sent back as Last-Event-ID when the browser reconnects), a retry hint, or raw_data for text that should not be JSON-encoded. Note that data="hello" is JSON-encoded too, so it arrives with quotes. FastAPI also sends a keep-alive comment every 15 seconds when nothing else is sent, so proxies with idle timeouts do not cut the stream, and it sets Cache-Control: no-cache and X-Accel-Buffering: no so nginx does not buffer it. Older code builds these strings by hand with StreamingResponse, as WebSockets in FastAPI shows; the built-in class is now the simpler choice, and the import path is fastapi.sse at the time of writing (check the docs if it moves).
This is what the wire format looks like, and what the browser does with it:
Press Run (⌘ Enter) to see what happens.Using the sse function above, what does this print?
print(repr(sse("hi", id="7")))Two production cautions. A streaming route keeps a worker's connection open for the whole stream, so set limits and timeouts, and remember that a client can disconnect at any time (the generator is cancelled). And any yield dependency, such as a database session, is still open while the stream runs, which is one reason FastAPI changed when dependency cleanup happens, as you will see in Dependency Injection.
Order the steps to get a new FastAPI app answering requests.
- Tap the steps below in the right order.
Practice
Build a decorator router
Recreate the heart of @app.get. Write a class App with:
get(path, status_code=200),post(path, status_code=200)anddelete(path, status_code=200): each returns a decorator that registers the function for that method and path, and returns the function unchanged.handle(method, path): returns a tuple(status, body):- a registered method and path: call the handler with no arguments and return
(status_code, result); - the path exists but not for this method:
(405, {"detail": "Method Not Allowed"}); - the path does not exist at all:
(404, {"detail": "Not Found"}).
- a registered method and path: call the handler with no arguments and return
app = App()
@app.post("/todos", status_code=201)
def create():
return {"id": 1}
app.handle("POST", "/todos") # (201, {"id": 1})
app.handle("GET", "/todos") # (405, {"detail": "Method Not Allowed"})Paths are matched exactly (no path parameters here).
- path operation
- A path plus an HTTP method, like
GET /todos, registered with a decorator such as@app.get. - fastapi dev
- Starts Uvicorn with auto-reload on
127.0.0.1:8000.fastapi runis the production version. - OpenAPI
- A standard JSON format describing an HTTP API. FastAPI generates it at
/openapi.json. - Swagger UI
- The interactive docs page at
/docs, drawn from the OpenAPI schema. - HTTPException
- Raise it in a route to stop and return an error status with a
detailmessage. - lifespan
- An async context manager passed to
FastAPI(lifespan=...). Code beforeyieldruns at startup, code after it at shutdown, once per worker. - response model
- The model a route's output is validated, filtered and documented with, from the return annotation or
response_model=. - Server-Sent Events
- A one-way stream of text events over a long HTTP response with type
text/event-stream. FastAPI'sEventSourceResponseproduces it.