Home β€Ί Curriculum β€Ί FastAPI & Modern APIs
Updated for Python 3.12+ Β· November 2026

⚑ FastAPI & Modern APIs
in Python

Learn FastAPI: path and query parameters, Pydantic validation, response models, dependency injection, async endpoints, JWT auth and testing, with runnable teaching models.

Advanced 9 lessonsβ‰ˆ 53 min read by Glenn Pansensoy

What this lesson is about

FastAPI is a modern Python framework for building web APIs: servers that other programs, such as a mobile app or a JavaScript front end, talk to by sending HTTP requests and receiving JSON. It has become popular because it lets you describe an endpoint with ordinary Python functions and type hints, and then does a large amount of work for you: it reads the request, validates the data, converts types, produces JSON and even writes interactive documentation.

Under the hood FastAPI combines two libraries. Starlette handles the web part (routing, requests, responses, async support) and Pydantic handles data validation using your type hints. The server that actually listens on a port is a separate program, usually uvicorn. Understanding that split makes errors much easier to read: a 422 response means Pydantic rejected the input, while a crash at startup usually means your app object could not be imported.

FastAPI itself cannot run in the browser, so the framework code on this page is shown as static blocks that you run on your own computer. To make sure you understand the machinery and not just the syntax, I have also built small runnable versions of the three key ideas in plain Python: a validation engine in the style of Pydantic, a dependency-injection resolver built on inspect, and a routing table with a decorator. When you meet the real thing, you will already know what it is doing. If you have not yet met web basics, my Flask lesson and type hints lesson make good warm-ups.

What you will learn

  • βœ“Create an app, run it with uvicorn and explore the automatic /docs page
  • βœ“Declare path parameters and query parameters with type hints
  • βœ“Validate request bodies with Pydantic models and constraints
  • βœ“Shape output with response_model, status codes and HTTPException
  • βœ“Use Depends for dependency injection and understand how it is resolved
  • βœ“Write async def endpoints and know when def is the better choice
  • βœ“Understand JWT-based authentication, including what a token does and does not protect
  • βœ“Test endpoints without a server using TestClient

Why programmers should learn this

  • β˜…APIs are the glue of modern software: web front ends, mobile apps and other services all talk to back ends over HTTP, and FastAPI is one of the most widely used Python tools for building them.
  • β˜…Type hints do double duty as validation and documentation, so there is less boilerplate and fewer mismatches between what your docs say and what your code does.
  • β˜…Automatic OpenAPI documentation gives front-end developers and teammates a live, testable description of your API without extra writing.
  • β˜…Dependency injection keeps authentication, database sessions and settings out of your endpoint bodies, which makes code shorter and much easier to test.
  • β˜…Machine-learning models and data pipelines are very often exposed to other programs through a small FastAPI service, so the skill connects directly to data and AI work.

Your first FastAPI app and the uvicorn server

A FastAPI application is an object of the class FastAPI, plus functions decorated with the HTTP method and path they serve. The decorator @app.get('/') says: when a GET request arrives at /, call this function and send back whatever it returns as JSON. Return a dict, a list, a string or a number and FastAPI converts it for you.

To run it you install two packages, fastapi and uvicorn, then start the server with uvicorn main:app --reload. The text main:app means 'in the file main.py, the variable called app'. --reload restarts the server when you save a file, which is for development only. Open http://127.0.0.1:8000/docs and you will find an interactive page generated from your code where you can try each endpoint with a button.

Both the function name and the docstring end up in that generated documentation, so write them for a human reader. Keep a virtual environment per project; if that is new to you, read my venv and pip lesson first.

Terminalrun on your computer
pip install fastapi "uvicorn[standard]"
uvicorn main:app --reload

Line by line

  1. 1Install the framework and the server. The quotes keep some shells from misreading the square brackets.
  2. 2Start uvicorn, import app from main.py and reload automatically on file changes.
main.pyrun on your computer
from fastapi import FastAPI

app = FastAPI(title="Bookshelf API", version="0.1.0")


@app.get("/")
def read_root():
    """Health check that also shows the shape of a JSON reply."""
    return {"status": "ok", "service": "bookshelf"}


@app.get("/ping")
async def ping():
    return "pong"

Line by line

  1. 1Import the application class.
  2. 3Create the app. The title and version appear in the automatic documentation.
  3. 6-9A GET endpoint at /. Returning a dict makes FastAPI send {"status": "ok", ...} as JSON with status 200. The docstring becomes the endpoint description in /docs.
  4. 12-14A second endpoint written with async def. For something this small there is no difference to the caller.
ℹ️

uvicorn --reload is a development convenience. In production you start uvicorn (or a process manager that runs it) without --reload and put a reverse proxy in front of it.

Path parameters and query parameters

A path parameter is part of the URL itself, written in curly braces: /books/{book_id}. You name the same variable in your function signature, and its type hint tells FastAPI how to convert it. Declare book_id: int and a request to /books/7 gives you the integer 7, while /books/abc is rejected automatically with a 422 error describing what was wrong. You wrote no validation code.

A query parameter is anything after the ? in a URL, such as /books?limit=5&genre=scifi. Any function parameter that is not in the path is treated as a query parameter. Give it a default and it becomes optional; leave the default off and it is required. str | None = None is the modern way to say 'optional string'.

When you need extra rules, use Query() and Path() to add constraints such as a minimum value or a maximum length. They show up in the documentation too, which is a lovely side effect. Order matters for routes: declare fixed paths such as /books/featured before /books/{book_id}, otherwise the word 'featured' is matched as an id.

pythonrun on your computer
from typing import Annotated
from fastapi import FastAPI, Query, Path

app = FastAPI()

BOOKS = {1: "Dune", 2: "Hyperion", 3: "Neuromancer"}


@app.get("/books/featured")
def featured():
    return {"title": BOOKS[1]}


@app.get("/books/{book_id}")
def get_book(book_id: Annotated[int, Path(ge=1)]):
    return {"id": book_id, "title": BOOKS.get(book_id)}


@app.get("/books")
def list_books(
    limit: Annotated[int, Query(ge=1, le=50)] = 10,
    search: str | None = None,
):
    titles = list(BOOKS.values())
    if search:
        titles = [t for t in titles if search.lower() in t.lower()]
    return {"limit": limit, "results": titles[:limit]}

Line by line

  1. 1-2Annotated lets us attach extra metadata, here validation rules, to a plain type.
  2. 9-11The fixed path is declared first so that /books/featured is never mistaken for an id.
  3. 14-16{book_id} in the path matches the book_id argument. int converts it and Path(ge=1) requires 1 or more. Requesting /books/0 gives a 422 error.
  4. 19-23limit and search are not in the path so they are query parameters. limit defaults to 10 and must be between 1 and 50; search is optional.
  5. 24-27Ordinary Python does the rest: filter by the search text, then slice by limit.

A request such as GET /books?limit=2&search=n would return {"limit": 2, "results": [...]} with the matching titles. Try limit=500 in the docs page and read the error message: it names the parameter, the rule and the value that broke it.

πŸ’‘

Use a path parameter to say *which* resource (/books/7), and query parameters to filter, sort or paginate a collection (/books?limit=5).

Pydantic models: validating request bodies

For data sent in the body of a POST or PUT request you describe the shape with a Pydantic model: a class whose attributes are annotated with types. FastAPI reads the JSON body, builds an instance of your model, and on any problem answers with a 422 error that lists every invalid field. By the time your function runs, the data is already checked and typed.

Pydantic also coerces compatible input in its default mode: the string "42" becomes the integer 42 for an int field. Constraints go in Field(...), for example Field(gt=0) or Field(min_length=3, max_length=40). Optional fields have defaults. Models can nest, so a Book may contain an Author model and a list of tags, and validation reaches all the way down.

Since Pydantic cannot run in the browser here, the second block after the real code is a tiny validation engine built with dataclasses. It follows the same idea in about thirty lines: look at each field's type and constraints, coerce, collect all the errors, and raise one exception holding the list. Reading it will make the 422 responses feel logical instead of magical.

Real FastAPI and Pydanticrun on your computer
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class BookIn(BaseModel):
    title: str = Field(min_length=1, max_length=100)
    author: str
    year: int = Field(ge=0, le=2100)
    price: float = Field(gt=0)
    tags: list[str] = []


@app.post("/books", status_code=201)
def create_book(book: BookIn):
    return {"created": book.title, "year": book.year}

Line by line

  1. 2BaseModel is the Pydantic base class; Field adds constraints.
  2. 7-12The body must be a JSON object with these fields. title needs 1 to 100 characters, year must be between 0 and 2100, and price must be greater than zero. tags is optional and defaults to an empty list.
  3. 15-17A parameter whose type is a Pydantic model is read from the request body. status_code=201 means 'Created'. Inside the function book is a validated object.
Runnable: a tiny Pydantic-style validator
from dataclasses import dataclass, field, fields, MISSING


class ValidationError(Exception):
    def __init__(self, errors):
        self.errors = errors
        super().__init__(f"{len(errors)} validation error(s)")


def Field(**rules):
    return field(metadata=rules)


def validate(cls, data):
    errors, clean = [], {}
    for f in fields(cls):
        if f.name not in data:
            if f.default is MISSING and f.default_factory is MISSING:
                errors.append({"loc": f.name, "msg": "field required"})
            continue
        raw = data[f.name]
        try:
            if f.type is str:
                if not isinstance(raw, str):
                    raise ValueError("input should be a valid string")
                value = raw
            else:
                value = f.type(raw)
        except (ValueError, TypeError):
            errors.append({"loc": f.name, "msg": f"input should be a valid {f.type.__name__}"})
            continue
        rules = f.metadata
        if "ge" in rules and value < rules["ge"]:
            errors.append({"loc": f.name, "msg": f"must be >= {rules['ge']}"})
        elif "gt" in rules and value <= rules["gt"]:
            errors.append({"loc": f.name, "msg": f"must be > {rules['gt']}"})
        elif "min_length" in rules and len(value) < rules["min_length"]:
            errors.append({"loc": f.name, "msg": f"needs at least {rules['min_length']} characters"})
        else:
            clean[f.name] = value
    if errors:
        raise ValidationError(errors)
    return cls(**clean)


@dataclass
class BookIn:
    title: str = Field(min_length=1)
    year: int = Field(ge=0)
    price: float = Field(gt=0)
    tags: list = field(default_factory=list)


good = validate(BookIn, {"title": "Dune", "year": "1965", "price": 9.99})
print(good)

try:
    validate(BookIn, {"title": "", "year": "soon", "price": -1})
except ValidationError as e:
    print(e)
    for err in e.errors:
        print(" ", err["loc"], "->", err["msg"])

try:
    validate(BookIn, {"year": 1})
except ValidationError as e:
    print([x["loc"] for x in e.errors])
Expected output
BookIn(title='Dune', year=1965, price=9.99, tags=[])
3 validation error(s)
  title -> needs at least 1 characters
  year -> input should be a valid int
  price -> must be > 0
['title', 'price']

Line by line

  1. 1Dataclasses already know each field's name, type and default; we reuse them as a schema.
  2. 4-7One exception type carries a list of every problem, like FastAPI's 422 reply.
  3. 10-11A Field helper stores our constraints in the dataclass field's metadata dictionary.
  4. 14-17Loop over the declared fields. Missing fields with no default are errors; missing ones with a default are skipped.
  5. 19-28Coerce the raw value to the declared type. Text must really be a string, while numbers are converted ('1965' becomes 1965). A failed conversion becomes an error and we continue to the next field.
  6. 29-37Apply the rules from the metadata. A value that passes is stored in clean.
  7. 38-41If any error was found raise them all together, otherwise build and return the dataclass.
  8. 44-49The model: the string constraints and numeric limits are written next to the fields.
  9. 52-53Valid input with the year as a string: it is coerced to the integer 1965.
  10. 55-60Three bad fields give three errors at once, not just the first one.
  11. 62-65A missing title with no default is reported as field required; price is missing too.
ℹ️

Real Pydantic is far more capable: nested models, email and URL types, custom validators, and a Rust-powered core that makes it fast. The engine above only shows the principle.

Response models, status codes and errors

What you accept and what you return are often different. A user model might hold a password hash that must never be sent back. FastAPI lets you declare response_model=UserOut, or simply annotate the return type, and the output is filtered and validated against that model. Fields not in the response model, like the hash, are dropped from the JSON. This is one of the most valuable safety features in the framework, so use separate 'in' and 'out' models as a habit.

Status codes tell the client what happened. Use 200 for a normal success, 201 for a created resource, 204 for success with no body, 400 or 422 for bad input, 401 for 'who are you?', 403 for 'you may not', 404 for not found and 409 for a conflict such as a duplicate. Set the success code with status_code= on the decorator.

To report an error from inside your logic, raise HTTPException(status_code=404, detail='Book not found'). FastAPI stops the function and sends the matching JSON reply {"detail": "Book not found"}. Do not return error dictionaries with a 200 code: clients rely on the status code to know something failed.

pythonrun on your computer
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, EmailStr

app = FastAPI()


class UserIn(BaseModel):
    email: EmailStr
    password: str


class UserOut(BaseModel):
    id: int
    email: EmailStr


FAKE_DB: dict[int, dict] = {}


@app.post("/users", response_model=UserOut, status_code=status.HTTP_201_CREATED)
def create_user(user: UserIn):
    if any(u["email"] == user.email for u in FAKE_DB.values()):
        raise HTTPException(status_code=409, detail="Email already registered")
    new_id = len(FAKE_DB) + 1
    FAKE_DB[new_id] = {"id": new_id, "email": user.email, "password_hash": "not-stored-here"}
    return FAKE_DB[new_id]


@app.get("/users/{user_id}", response_model=UserOut)
def read_user(user_id: int):
    if user_id not in FAKE_DB:
        raise HTTPException(status_code=404, detail="User not found")
    return FAKE_DB[user_id]

Line by line

  1. 2EmailStr validates addresses; it needs the extra package email-validator.
  2. 7-9The input model has a password because the client must send one.
  3. 12-14The output model has no password field at all.
  4. 17A dictionary standing in for a real database in this example.
  5. 20-21response_model filters what is returned and status_code sets the success code to 201.
  6. 22-23If the email already exists, HTTPException produces a 409 response with a JSON detail.
  7. 24-26We store a record that includes password_hash (a placeholder, never store plain passwords) and return the whole dict. The response model removes everything except id and email.
  8. 29-33A lookup that answers 404 when the id is unknown.
⚠️

Never store or log plain-text passwords. Real code hashes them with a purpose-built password-hashing library and compares hashes at login.

Dependency injection with Depends

Many endpoints need the same helpers: a database session, the current user, application settings, a pagination object. Copying that code into every function is repetitive and hard to test. FastAPI's answer is dependency injection. You write a function that produces the thing, then declare Depends(that_function) as a parameter's default. Before calling your endpoint, FastAPI calls the dependency (resolving *its* dependencies first), and passes the result in.

Dependencies can depend on other dependencies, forming a small graph. get_current_user might depend on get_token, which reads a header. Within one request, FastAPI calls each dependency once and reuses the result even if several functions ask for it. A dependency written with yield can run clean-up code after the response, which is the standard way to open and close a database session.

The testing payoff is large. Because your endpoint asks for a database session rather than creating one, a test can replace it with app.dependency_overrides[get_db] = fake_db. Nothing inside the endpoint changes. The runnable block after the real code builds a resolver with inspect.signature so you can see exactly how the machinery reads a signature, finds the Depends markers, caches results and honours overrides.

Real FastAPI dependenciesrun on your computer
from fastapi import Depends, FastAPI, Header, HTTPException

app = FastAPI()


def get_db():
    db = {"users": {"ana": {"name": "Ana"}}}
    try:
        yield db
    finally:
        pass  # a real dependency would close the session here


def get_username(x_user: str | None = Header(default=None)):
    if x_user is None:
        raise HTTPException(status_code=401, detail="Missing X-User header")
    return x_user


def get_current_user(username: str = Depends(get_username), db: dict = Depends(get_db)):
    user = db["users"].get(username)
    if user is None:
        raise HTTPException(status_code=403, detail="Unknown user")
    return user


@app.get("/me")
def me(user: dict = Depends(get_current_user)):
    return user

Line by line

  1. 5-10A dependency with yield: the value before yield is injected, the finally block runs after the response is sent.
  2. 13-16A dependency that reads a request header and returns 401 when it is missing. Header() maps x_user to the X-User header.
  3. 19-23A dependency that depends on two others. FastAPI resolves get_username and get_db first and passes their results in.
  4. 26-28The endpoint only says it needs a user. It does not care how one is found, which is why tests can swap the whole chain.
Runnable: a dependency resolver built on inspect
import inspect


class Depends:
    def __init__(self, func):
        self.func = func


def resolve(func, context, overrides=None, cache=None):
    overrides = overrides or {}
    cache = {} if cache is None else cache
    kwargs = {}
    for name, param in inspect.signature(func).parameters.items():
        if isinstance(param.default, Depends):
            dep = param.default.func
            dep = overrides.get(dep, dep)
            if dep not in cache:
                cache[dep] = resolve(dep, context, overrides, cache)
            kwargs[name] = cache[dep]
        elif name in context:
            kwargs[name] = context[name]
        elif param.default is not inspect.Parameter.empty:
            kwargs[name] = param.default
        else:
            raise TypeError(f"cannot supply parameter {name!r} for {func.__name__}")
    print("  calling", func.__name__)
    return func(**kwargs)


def get_db():
    return {"users": {"ana": "Ana Reyes", "ben": "Ben Cruz"}}


def get_username(x_user=None):
    return x_user


def get_current_user(username=Depends(get_username), db=Depends(get_db)):
    return db["users"][username]


def endpoint(user=Depends(get_current_user), db=Depends(get_db)):
    return f"hello {user} ({len(db['users'])} users)"


print("normal request:")
print(resolve(endpoint, {"x_user": "ana"}))

print("get_db requested twice but called once per request (see log above).")

def fake_db():
    return {"users": {"zed": "Zed Test"}}

print("test with an override:")
print(resolve(endpoint, {"x_user": "zed"}, overrides={get_db: fake_db}))
Expected output
normal request:
  calling get_username
  calling get_db
  calling get_current_user
  calling endpoint
hello Ana Reyes (2 users)
get_db requested twice but called once per request (see log above).
test with an override:
  calling get_username
  calling fake_db
  calling get_current_user
  calling endpoint
hello Zed Test (1 users)

Line by line

  1. 1inspect.signature lets code look at a function's parameters at run time, which is how FastAPI works.
  2. 4-6A marker class that just remembers the dependency function.
  3. 9-12resolve builds the keyword arguments for a call. cache is shared across the whole resolution, like one request.
  4. 13-18If a parameter's default is a Depends, look up an override, resolve the dependency recursively unless the cache already holds its result, and use that as the argument.
  5. 19-24Otherwise take the value from the request context by name, fall back to the Python default, or complain that nothing can supply the parameter.
  6. 25-26Print which function is really called so the one-call-per-request behaviour is visible.
  7. 29-43Three dependencies in a small graph: the endpoint needs the user and the db; the user needs a username and the same db.
  8. 46-47Resolve the endpoint. The log shows get_db runs once even though two functions asked for it.
  9. 51-55Pass overrides={get_db: fake_db} to swap the database without touching the endpoint code, the same trick as dependency_overrides.

How routing and automatic docs work

When you write @app.get('/books/{book_id}'), the decorator does not call your function. It *registers* it in a table of routes, a list holding the method, the path pattern and the function, then returns the function unchanged. When a request arrives, the framework searches that table for a matching method and path, extracts the path values, converts them using type hints and calls the function.

That same table is also what produces the documentation. Because each registered function carries its parameter names and annotations, the framework can walk the table and output a machine-readable description called an OpenAPI document. The /docs page (Swagger UI) and the /redoc page are just viewers for that JSON, which you can also fetch at /openapi.json and feed to code generators.

The runnable version below is a miniature of the whole mechanism: a decorator that fills a route table, a dispatcher that matches {name} segments and converts them by annotation, query-string handling with urllib.parse, and a method that emits a small OpenAPI-like dictionary. It is not FastAPI, but it is the same design, and it makes the framework far less mysterious.

Runnable: a route table, decorator and mini OpenAPI
import inspect, json, re
from urllib.parse import urlsplit, parse_qs


class MiniApp:
    def __init__(self):
        self.routes = []

    def route(self, method, path):
        def decorator(func):
            regex = re.compile("^" + re.sub(r"\{(\w+)\}", r"(?P<\1>[^/]+)", path) + "$")
            self.routes.append((method, path, regex, func))
            return func
        return decorator

    def get(self, path):
        return self.route("GET", path)

    def handle(self, method, url):
        parts = urlsplit(url)
        query = {k: v[0] for k, v in parse_qs(parts.query).items()}
        for m, path, regex, func in self.routes:
            match = regex.match(parts.path)
            if m != method or not match:
                continue
            values = {**query, **match.groupdict()}
            kwargs = {}
            for name, param in inspect.signature(func).parameters.items():
                if name in values:
                    try:
                        kwargs[name] = param.annotation(values[name])
                    except ValueError:
                        return 422, {"detail": f"{name} must be {param.annotation.__name__}"}
                elif param.default is inspect.Parameter.empty:
                    return 422, {"detail": f"{name} is required"}
            return 200, func(**kwargs)
        return 404, {"detail": "Not Found"}

    def openapi(self):
        paths = {}
        for method, path, _, func in self.routes:
            params = []
            for name, p in inspect.signature(func).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})
            paths.setdefault(path, {})[method.lower()] = {"summary": func.__name__, "parameters": params}
        return {"openapi": "mini-0.1", "paths": paths}


app = MiniApp()


@app.get("/books/{book_id}")
def get_book(book_id: int):
    return {"id": book_id}


@app.get("/books")
def list_books(limit: int = 10, genre: str = "any"):
    return {"limit": limit, "genre": genre}


print(app.handle("GET", "/books/7"))
print(app.handle("GET", "/books/abc"))
print(app.handle("GET", "/books?limit=3&genre=scifi"))
print(app.handle("GET", "/books"))
print(app.handle("GET", "/nothing"))
print(app.handle("POST", "/books"))
print(json.dumps(app.openapi()["paths"]["/books/{book_id}"], sort_keys=True))
Expected output
(200, {'id': 7})
(422, {'detail': 'book_id must be int'})
(200, {'limit': 3, 'genre': 'scifi'})
(200, {'limit': 10, 'genre': 'any'})
(404, {'detail': 'Not Found'})
(404, {'detail': 'Not Found'})
{"get": {"parameters": [{"in": "path", "name": "book_id", "required": true, "type": "int"}], "summary": "get_book"}}

Line by line

  1. 1-2Standard-library tools only: inspect to read signatures, re to match paths, urllib.parse to split URLs.
  2. 6-8The app keeps one list of registered routes.
  3. 10-15route is a decorator factory. It converts /books/{book_id} into a regular expression with a named group, stores the route, and returns the function untouched.
  4. 17-18get is a convenience wrapper, just like @app.get in FastAPI.
  5. 20-24Split the URL into path and query, turning ?limit=3 into a dictionary.
  6. 25-29Search the table for a route whose method and path both match; skip the rest.
  7. 30-40Merge query and path values, then build the arguments by converting each one with the parameter's annotation (int('abc') fails, which becomes a 422). A missing required value is also a 422.
  8. 41-42Call the function and return a status and body. If no route matched, return 404.
  9. 44-53openapi walks the same table and reads each signature to describe where every parameter lives and whether it is required.
  10. 56-65Two endpoints registered with the decorator.
  11. 68-74Try several requests: success, a conversion failure, defaults, unknown path, wrong method, and the generated documentation for one path.

Async endpoints: async def or def?

FastAPI lets you write endpoints as either def or async def. With plain def, FastAPI runs your function in a worker thread pool so a slow function does not freeze the server for everybody. With async def, your function runs directly on the event loop, which is a single thread that switches between tasks whenever one of them awaits something slow, such as a network or database call made with an async library.

The rule I follow: use async def when everything you call inside can be awaited (an async HTTP client, an async database driver). Use plain def when you call blocking code such as requests, ordinary file reads or a CPU-heavy calculation. The most common performance bug is a blocking call inside async def: it stops the event loop, and every other request waits behind it. If you have not used async and await before, my async lesson covers them from scratch.

To see what 'switching tasks' means without a framework, the second block builds a toy event loop. Each task is a coroutine; await pause() hands control back to the scheduler, which then runs the next task. You will see the tasks interleave, which is exactly how one thread can serve many requests while they wait for I/O.

Real async and sync endpointsrun on your computer
import asyncio
import httpx
from fastapi import FastAPI

app = FastAPI()


@app.get("/combined")
async def combined():
    async with httpx.AsyncClient(timeout=5) as client:
        a, b = await asyncio.gather(
            client.get("https://api.example.com/a"),
            client.get("https://api.example.com/b"),
        )
    return {"a": a.json(), "b": b.json()}


@app.get("/report")
def report():
    # plain def: FastAPI runs this in a thread pool, so blocking work is fine
    total = sum(i * i for i in range(1_000_000))
    return {"total": total}

Line by line

  1. 2httpx is an HTTP client with both sync and async versions; install it with pip.
  2. 8-14An async endpoint awaits two requests at the same time with gather, so the total wait is about the slower of the two instead of their sum.
  3. 17-21A synchronous endpoint doing CPU work. Because it is a plain def, it does not block the event loop.
Runnable: a toy event loop showing interleaving
class pause:
    """Awaitable that gives control back to the scheduler once."""
    def __await__(self):
        yield


async def worker(name, steps, log):
    for i in range(1, steps + 1):
        log.append(f"{name} step {i}")
        await pause()
    return f"{name} finished"


def run_all(coros):
    ready = list(coros)
    results = []
    while ready:
        coro = ready.pop(0)
        try:
            coro.send(None)
            ready.append(coro)
        except StopIteration as done:
            results.append(done.value)
    return results


log = []
results = run_all([worker("A", 3, log), worker("B", 1, log), worker("C", 2, log)])
print("\n".join(log))
print(results)
Expected output
A step 1
B step 1
C step 1
A step 2
C step 2
A step 3
['B finished', 'C finished', 'A finished']

Line by line

  1. 1-4pause is a tiny awaitable. Its yield suspends the running coroutine and returns control to whoever is driving it.
  2. 7-11A task that logs a step, then pauses, repeatedly. The pause is where other tasks get a turn.
  3. 14-24The scheduler keeps a queue. It resumes the first coroutine with send(None); if it paused it goes to the back of the queue, and if it finished its return value is collected.
  4. 27-30Run three workers with different lengths. The log shows A, B and C taking turns, and the shortest one finishes first.
⚠️

Calling time.sleep() or requests.get() inside async def blocks the whole event loop. Use await asyncio.sleep() and an async client, or make the endpoint a plain def.

Authentication and JWT: the concepts

Authentication answers 'who are you?' and authorisation answers 'what may you do?'. A common design for APIs is token-based: the user logs in once with a username and password, the server replies with a signed token, and the client sends that token in an Authorization: Bearer ... header on later requests. The server checks the token instead of the password each time.

A JWT (JSON Web Token) is one popular token format. It has three dot-separated parts: a header (the algorithm), a payload of claims (such as the user id sub and an expiry time exp) and a signature computed with a secret key. Anyone can *read* the first two parts because they are only base64url-encoded, not encrypted, so never put secrets in them. The signature is what makes tampering detectable: change one character of the payload and the signature no longer matches.

The runnable demo below builds and verifies an HS256-style token with the standard library, using a fake clock so it is deterministic. The key in it is a throwaway demo value; in a real project you load the key from an environment variable and use a maintained library for JWTs, because correct handling of algorithms and edge cases is subtle. Always set a short expiry, always use HTTPS, and remember that a JWT is only as safe as the place the client stores it.

Runnable: build and verify a signed token
import base64, hashlib, hmac, json

DEMO_KEY = b"demo-key-for-teaching-only"


def b64(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def unb64(text: str) -> bytes:
    return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))


def sign(message: str) -> str:
    return b64(hmac.new(DEMO_KEY, message.encode(), hashlib.sha256).digest())


def make_token(claims: dict, now: int, lifetime: int = 60) -> str:
    header = b64(json.dumps({"alg": "HS256", "typ": "JWT"}, sort_keys=True).encode())
    payload = b64(json.dumps({**claims, "exp": now + lifetime}, sort_keys=True).encode())
    return f"{header}.{payload}.{sign(header + '.' + payload)}"


def check_token(token: str, now: int) -> dict:
    header, payload, signature = token.split(".")
    if not hmac.compare_digest(signature, sign(header + "." + payload)):
        raise ValueError("bad signature")
    claims = json.loads(unb64(payload))
    if claims["exp"] < now:
        raise ValueError("token expired")
    return claims


token = make_token({"sub": "ana", "role": "reader"}, now=1000)
print(len(token.split(".")), "parts")
print(json.loads(unb64(token.split(".")[1])))
print("valid at t=1030:", check_token(token, now=1030))

for label, t, when in [
    ("expired", token, 1100),
    ("tampered", token.split(".")[0] + "." + b64(json.dumps({"sub": "ana", "role": "admin", "exp": 5000}, sort_keys=True).encode()) + "." + token.split(".")[2], 1030),
]:
    try:
        check_token(t, now=when)
    except ValueError as e:
        print(label, "->", e)
Expected output
3 parts
{'exp': 1060, 'role': 'reader', 'sub': 'ana'}
valid at t=1030: {'exp': 1060, 'role': 'reader', 'sub': 'ana'}
expired -> token expired
tampered -> bad signature

Line by line

  1. 1-3Only the standard library is needed. The key is a made-up constant for the demo; real keys come from the environment and are never committed to code.
  2. 6-11JWTs use URL-safe base64 without = padding. unb64 puts the padding back before decoding.
  3. 14-15The signature is an HMAC-SHA256 of the text header.payload, computed with the secret key.
  4. 18-21Build a token from a header, a payload with an expiry time added, and the signature. now is passed in so the clock is under our control.
  5. 24-31To verify, recompute the signature and compare in constant time with compare_digest, then decode the payload and check that it has not expired.
  6. 34-36The payload is plainly readable by anyone: it is encoded, not encrypted.
  7. 38-47An old token fails the expiry check. A token whose payload was edited to claim admin fails because the signature no longer matches.
Real FastAPI login with PyJWTrun on your computer
import os
from datetime import datetime, timedelta, timezone

import jwt  # the PyJWT package
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm

SECRET_KEY = os.environ["APP_SECRET_KEY"]  # set outside the code, never commit it
ALGORITHM = "HS256"

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


def authenticate(username: str, password: str):
    ...  # look the user up and compare a password hash; return the user or None


@app.post("/token")
def login(form: OAuth2PasswordRequestForm = Depends()):
    user = authenticate(form.username, form.password)
    if user is None:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Incorrect username or password")
    expires = datetime.now(timezone.utc) + timedelta(minutes=15)
    token = jwt.encode({"sub": form.username, "exp": expires}, SECRET_KEY, algorithm=ALGORITHM)
    return {"access_token": token, "token_type": "bearer"}


def current_user(token: str = Depends(oauth2_scheme)):
    try:
        claims = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    except jwt.PyJWTError:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid or expired token")
    return claims["sub"]


@app.get("/profile")
def profile(username: str = Depends(current_user)):
    return {"user": username}

Line by line

  1. 4PyJWT (pip install pyjwt) handles encoding, decoding and expiry checks.
  2. 8The secret comes from an environment variable, so it is not in the source code.
  3. 11OAuth2PasswordBearer tells FastAPI to read the bearer token from the Authorization header and adds the 'Authorize' button to /docs.
  4. 14-15A placeholder for your own user lookup and password-hash check.
  5. 18-25The login endpoint reads a form with username and password, returns 401 on failure, and otherwise issues a token that expires in 15 minutes.
  6. 28-33A dependency that decodes the token. Pass algorithms=[...] explicitly when decoding, and turn any library error (bad signature, expired) into a 401.
  7. 36-38Any endpoint that depends on current_user is now protected.
⚠️

Never put a real secret key in code, a lesson or a Git repository. If one leaks, rotate it immediately.

Testing with TestClient and deploying with uvicorn

FastAPI makes testing pleasant because you do not need a running server. TestClient wraps your app and lets you call client.get('/books/1') as if it were a requests-style client, returning a response with status_code and .json(). Tests run in milliseconds and live next to your other tests; I explain the underlying tools in my pytest lesson.

Combine TestClient with dependency_overrides to replace the database, the clock or the current user. A good test suite for an API checks the happy path, then the error paths: missing fields (422), unknown ids (404) and unauthenticated calls (401). Those error responses are part of your API's contract just as much as the success ones.

When you are ready to deploy, remove --reload, bind to the right host and port, and run uvicorn behind a reverse proxy or a platform that manages processes for you. Configuration such as database URLs and secret keys belongs in environment variables. Check the deployment notes of your hosting provider for the current recommended command, because platforms change their defaults.

test_api.py (run with pytest)run on your computer
from fastapi.testclient import TestClient

from main import app, get_db

client = TestClient(app)


def fake_db():
    yield {"users": {"zed": {"name": "Zed"}}}


def test_read_root():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json()["status"] == "ok"


def test_book_not_found_is_404():
    response = client.get("/books/999")
    assert response.status_code == 404


def test_validation_error_is_422():
    response = client.post("/books", json={"title": "", "year": "soon"})
    assert response.status_code == 422
    assert len(response.json()["detail"]) >= 2


def test_override_dependency():
    app.dependency_overrides[get_db] = fake_db
    try:
        response = client.get("/me", headers={"X-User": "zed"})
        assert response.json() == {"name": "Zed"}
    finally:
        app.dependency_overrides.clear()

Line by line

  1. 1TestClient ships with FastAPI; it needs the httpx package installed.
  2. 3Import the app and the dependency we want to replace.
  3. 5One client for the whole test file.
  4. 8-9A fake dependency that yields a tiny in-memory database.
  5. 12-15The simplest test: call an endpoint and check the status code and JSON.
  6. 18-20Test the error path as well as the happy path.
  7. 23-26Invalid input returns 422 and a detail list describing each problem.
  8. 29-35Override a dependency for one test and always clear the overrides in finally so other tests are not affected.
Running tests and the serverrun on your computer
pytest -q

# development
uvicorn main:app --reload

# production-style start (host and port are examples)
uvicorn main:app --host 0.0.0.0 --port 8000

Line by line

  1. 1Run every test quietly.
  2. 3-4Development server with automatic reload.
  3. 6-7A production-style start. 0.0.0.0 listens on all network interfaces, so only use it behind a firewall or proxy you control.

Common mistakes

❌ Blocking the event loop inside async def

Calling requests.get, time.sleep or heavy CPU code in an async def endpoint freezes every other request. Use async libraries with await, or declare the endpoint with plain def so it runs in a thread pool.

❌ Returning the database model directly

If your stored record contains a password hash or internal fields, returning it leaks them. Declare a separate output model with response_model so only intended fields are sent.

❌ Declaring routes in the wrong order

/books/{book_id} declared before /books/featured captures the word 'featured' as an id. Put fixed paths before parameterised ones.

❌ Hardcoding secrets and using weak tokens

A secret key typed into the source ends up in Git history. Load it from an environment variable, give tokens a short expiry and never put sensitive data in a JWT payload, since it is readable.

❌ Using mutable default values wrongly or sharing global state

A module-level list or dict used as storage is shared by every request and is lost on restart or when running several workers. Use a real database and inject sessions with Depends.

Quick quiz

Tap an answer. I explain every one, right or wrong.

Q1. A function parameter is not part of the path and has a default value. How does FastAPI treat it?

Q2. What HTTP status does FastAPI return when request data fails Pydantic validation?

Q3. What is response_model mainly useful for?

Q4. Why does app.dependency_overrides help in tests?

Q5. Which statement about a JWT payload is true?

Q6. When should an endpoint be plain def rather than async def?

Frequently asked questions

They suit different jobs. FastAPI is strong for JSON APIs with validation, async support and automatic docs. Flask is small and flexible, and Django includes an admin, ORM and templates for full websites. Many teams use more than one.

No. Plain def endpoints are fully supported and run in a thread pool. Use async def when your code awaits async libraries.

Starlette provides the web toolkit FastAPI is built on, Pydantic validates data from type hints, and uvicorn is the server that listens for connections and runs your app.

Create a session per request in a dependency that uses yield, and inject it with Depends. SQLAlchemy is a common choice, and my SQLite lesson covers the SQL underneath.

The official FastAPI documentation is the best source, since the framework changes and recommended patterns evolve. Check the version you have installed with pip show fastapi and read the matching docs.

Key takeaways

  • βœ“A FastAPI app is a table of routes built with decorators and served by uvicorn; /docs is generated from that table.
  • βœ“Path parameters choose a resource, query parameters filter it, and type hints convert and validate both.
  • βœ“Pydantic models validate request bodies and, as response_model, filter what you send back.
  • βœ“Depends injects helpers such as sessions and the current user, and dependency_overrides makes endpoints easy to test.
  • βœ“Use async def only with awaitable code; blocking work belongs in plain def endpoints.
  • βœ“JWTs are signed, not secret: keep keys in the environment, set expiries and test happy and error paths with TestClient.