Skip to content

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.

24 min read0/7 questions

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.py

If 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 after setup
  • 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:

app/main.py
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"}
Quick check
Which command should you use inside your production container?
Need a nudge? A hint rules out a wrong answer.

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:

pyproject.toml
[tool.fastapi]
entrypoint = "app.main:app"

The differences are all about where the server runs:

fastapi devfastapi run
Reload on file changeOnOff (reload is slow and memory-hungry)
Listens on127.0.0.1, only your machine0.0.0.0, every interface, needed in a container
WorkersOne--workers N for several processes
Proxy headersOn, trusted only from 127.0.0.1 by defaultSame; 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.)

app/main.py
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.

GET /todos/999 through FastAPI
curlUvicornFastAPIget_todoGET /todos/999app(scope, receive, send)get_todo(todo_id=999)raise HTTPException(404)404 {"detail": "Todo not found"}

The client sends a plain HTTP request to port 8000.

1/5

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 the pairs0/5 matched

Match each request to the decorator that handles it.

Choose an item, then its match on the other side.

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.

Pythonmini_fastapi.py
class MiniApp: def __init__(self): self.routes = {} def route(self, method, path, status_code=200): def register(fn): self.routes[(method, path)] = (fn, status_code) return fn # the function itself is unchanged return register def get(self, path, status_code=200): return self.route("GET", path, status_code) def post(self, path, status_code=200): return self.route("POST", path, status_code) def handle(self, method, path): if (method, path) not in self.routes: return 404, {"detail": "Not Found"} fn, code = self.routes[(method, path)] return code, fn() app = MiniApp() @app.get("/")def root(): return {"message": "hi"} @app.post("/todos", status_code=201)def create_todo(): return {"id": 3, "title": "New"} print(app.routes.keys())print(app.handle("GET", "/"))print(app.handle("POST", "/todos"))print(app.handle("GET", "/nope"))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

With the MiniApp above, what does this print?

@app.get("/health")
def health():
  return "ok"

print(app.handle("GET", "/health")[0], len(app.routes))
Need a nudge? Hints walk you through it.

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:

Pythontiny_openapi.py
import inspect def get_todo(todo_id: int, verbose: bool = False): """Read one todo by its id.""" def describe(method, path, fn): params = [] for name, p in inspect.signature(fn).parameters.items(): where = "path" if "{" + name + "}" in path else "query" params.append({ "name": name, "in": where, "type": p.annotation.__name__, "required": p.default is inspect.Parameter.empty, }) return {path: {method.lower(): {"summary": fn.__doc__, "parameters": params}}} import jsonprint(json.dumps(describe("GET", "/todos/{todo_id}", get_todo), indent=2))
Output
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.

Quick check
Where does FastAPI get the information shown on /docs?
Need a nudge? A hint rules out a wrong answer.

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.

CodeMeaningTypical route
200 OKSuccess with a bodyGET /todos
201 CreatedA new resource was madePOST /todos
204 No ContentSuccess, no bodyDELETE /todos/7
404 Not FoundThat resource does not existGET /todos/999
422 Unprocessable ContentInput failed validationGET /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.

app/main.py
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 pass lifespan=, those handlers do not run at all, so do not mix the two.
  • It runs in every worker process. With --workers 4 you 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.

Quick check
You start the app with fastapi run --workers 4. Your lifespan creates a database pool of 10 connections. How many connections can the app open in total?
Need a nudge? A hint rules out a wrong answer.

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:

app/main.py
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 dropped

A 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:

app/exports.py
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:

app/jobs.py
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:

Pythonsse_wire.py
import json def sse(data=None, event=None, id=None, retry=None, comment=None): """Encode one event the way text/event-stream expects it.""" lines = [] if comment is not None: lines.append(f": {comment}") if event is not None: lines.append(f"event: {event}") if data is not None: lines.append(f"data: {json.dumps(data)}") if id is not None: lines.append(f"id: {id}") if retry is not None: lines.append(f"retry: {retry}") return "\n".join(lines) + "\n\n" # a blank line ends the event stream = ( sse({"pct": 0}, id="1") + sse(comment="ping") # keep-alive: clients ignore comments + sse({"pct": 50}, id="2") + sse({"pct": 100}, event="done", id="3"))print(stream) def parse(stream): """What the browser's EventSource does with those bytes.""" last_id = None for block in stream.strip().split("\n\n"): fields = {} for line in block.split("\n"): if line.startswith(":"): continue name, _, value = line.partition(": ") fields[name] = value if "data" in fields: last_id = fields.get("id", last_id) print(fields.get("event", "message"), json.loads(fields["data"])) return last_id print("Reconnect with Last-Event-ID:", parse(stream))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

Using the sse function above, what does this print?

print(repr(sse("hi", id="7")))
Need a nudge? Hints walk you through it.

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.

Put it in order5 steps

Order the steps to get a new FastAPI app answering requests.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Practice

ChallengeMedium

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) and delete(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"}).
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).

Python
class App: def __init__(self): pass def get(self, path: str, status_code: int = 200): pass def post(self, path: str, status_code: int = 200): pass def delete(self, path: str, status_code: int = 200): pass def handle(self, method: str, path: str) -> tuple: pass
Key terms
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 run is 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 detail message.
lifespan
An async context manager passed to FastAPI(lifespan=...). Code before yield runs 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's EventSourceResponse produces it.