β‘ 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.
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
/docspage - βDeclare path parameters and query parameters with type hints
- βValidate request bodies with Pydantic models and constraints
- βShape output with
response_model, status codes andHTTPException - βUse
Dependsfor dependency injection and understand how it is resolved - βWrite
async defendpoints and know whendefis 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.
pip install fastapi "uvicorn[standard]" uvicorn main:app --reload
Line by line
- 1Install the framework and the server. The quotes keep some shells from misreading the square brackets.
- 2Start uvicorn, import
appfrommain.pyand reload automatically on file changes.
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
- 1Import the application class.
- 3Create the app. The title and version appear in the automatic documentation.
- 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. - 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.
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-2
Annotatedlets us attach extra metadata, here validation rules, to a plain type. - 9-11The fixed path is declared first so that
/books/featuredis never mistaken for an id. - 14-16
{book_id}in the path matches thebook_idargument.intconverts it andPath(ge=1)requires 1 or more. Requesting/books/0gives a 422 error. - 19-23
limitandsearchare not in the path so they are query parameters.limitdefaults to 10 and must be between 1 and 50;searchis optional. - 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.
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
- 2
BaseModelis the Pydantic base class;Fieldadds constraints. - 7-12The body must be a JSON object with these fields.
titleneeds 1 to 100 characters,yearmust be between 0 and 2100, andpricemust be greater than zero.tagsis optional and defaults to an empty list. - 15-17A parameter whose type is a Pydantic model is read from the request body.
status_code=201means 'Created'. Inside the functionbookis a validated object.
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])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
- 1Dataclasses already know each field's name, type and default; we reuse them as a schema.
- 4-7One exception type carries a list of every problem, like FastAPI's 422 reply.
- 10-11A
Fieldhelper stores our constraints in the dataclass field'smetadatadictionary. - 14-17Loop over the declared fields. Missing fields with no default are errors; missing ones with a default are skipped.
- 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. - 29-37Apply the rules from the metadata. A value that passes is stored in
clean. - 38-41If any error was found raise them all together, otherwise build and return the dataclass.
- 44-49The model: the string constraints and numeric limits are written next to the fields.
- 52-53Valid input with the year as a string: it is coerced to the integer 1965.
- 55-60Three bad fields give three errors at once, not just the first one.
- 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.
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
- 2
EmailStrvalidates addresses; it needs the extra packageemail-validator. - 7-9The input model has a password because the client must send one.
- 12-14The output model has no password field at all.
- 17A dictionary standing in for a real database in this example.
- 20-21
response_modelfilters what is returned andstatus_codesets the success code to 201. - 22-23If the email already exists,
HTTPExceptionproduces a 409 response with a JSONdetail. - 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 exceptidandemail. - 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.
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 userLine by line
- 5-10A dependency with
yield: the value beforeyieldis injected, thefinallyblock runs after the response is sent. - 13-16A dependency that reads a request header and returns 401 when it is missing.
Header()mapsx_userto theX-Userheader. - 19-23A dependency that depends on two others. FastAPI resolves
get_usernameandget_dbfirst and passes their results in. - 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.
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}))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
inspect.signaturelets code look at a function's parameters at run time, which is how FastAPI works. - 4-6A marker class that just remembers the dependency function.
- 9-12
resolvebuilds the keyword arguments for a call.cacheis shared across the whole resolution, like one request. - 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. - 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.
- 25-26Print which function is really called so the one-call-per-request behaviour is visible.
- 29-43Three dependencies in a small graph: the endpoint needs the user and the db; the user needs a username and the same db.
- 46-47Resolve the endpoint. The log shows
get_dbruns once even though two functions asked for it. - 51-55Pass
overrides={get_db: fake_db}to swap the database without touching the endpoint code, the same trick asdependency_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.
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))(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-2Standard-library tools only:
inspectto read signatures,reto match paths,urllib.parseto split URLs. - 6-8The app keeps one list of registered routes.
- 10-15
routeis a decorator factory. It converts/books/{book_id}into a regular expression with a named group, stores the route, and returns the function untouched. - 17-18
getis a convenience wrapper, just like@app.getin FastAPI. - 20-24Split the URL into path and query, turning
?limit=3into a dictionary. - 25-29Search the table for a route whose method and path both match; skip the rest.
- 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. - 41-42Call the function and return a status and body. If no route matched, return 404.
- 44-53
openapiwalks the same table and reads each signature to describe where every parameter lives and whether it is required. - 56-65Two endpoints registered with the decorator.
- 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.
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
- 2
httpxis an HTTP client with both sync and async versions; install it with pip. - 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. - 17-21A synchronous endpoint doing CPU work. Because it is a plain
def, it does not block the event loop.
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)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-4
pauseis a tiny awaitable. Itsyieldsuspends the running coroutine and returns control to whoever is driving it. - 7-11A task that logs a step, then pauses, repeatedly. The pause is where other tasks get a turn.
- 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. - 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.
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)3 parts
{'exp': 1060, 'role': 'reader', 'sub': 'ana'}
valid at t=1030: {'exp': 1060, 'role': 'reader', 'sub': 'ana'}
expired -> token expired
tampered -> bad signatureLine by line
- 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.
- 6-11JWTs use URL-safe base64 without
=padding.unb64puts the padding back before decoding. - 14-15The signature is an HMAC-SHA256 of the text
header.payload, computed with the secret key. - 18-21Build a token from a header, a payload with an expiry time added, and the signature.
nowis passed in so the clock is under our control. - 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. - 34-36The payload is plainly readable by anyone: it is encoded, not encrypted.
- 38-47An old token fails the expiry check. A token whose payload was edited to claim
adminfails because the signature no longer matches.
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
- 4PyJWT (
pip install pyjwt) handles encoding, decoding and expiry checks. - 8The secret comes from an environment variable, so it is not in the source code.
- 11
OAuth2PasswordBearertells FastAPI to read the bearer token from theAuthorizationheader and adds the 'Authorize' button to/docs. - 14-15A placeholder for your own user lookup and password-hash check.
- 18-25The login endpoint reads a form with
usernameandpassword, returns 401 on failure, and otherwise issues a token that expires in 15 minutes. - 28-33A dependency that decodes the token. Pass
algorithms=[...]explicitly when decoding, and turn any library error (bad signature, expired) into a 401. - 36-38Any endpoint that depends on
current_useris 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.
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
TestClientships with FastAPI; it needs thehttpxpackage installed. - 3Import the app and the dependency we want to replace.
- 5One client for the whole test file.
- 8-9A fake dependency that yields a tiny in-memory database.
- 12-15The simplest test: call an endpoint and check the status code and JSON.
- 18-20Test the error path as well as the happy path.
- 23-26Invalid input returns 422 and a
detaillist describing each problem. - 29-35Override a dependency for one test and always clear the overrides in
finallyso other tests are not affected.
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
- 1Run every test quietly.
- 3-4Development server with automatic reload.
- 6-7A production-style start.
0.0.0.0listens 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?
detail listing each invalid field.Q3. What is response_model mainly useful for?
Q4. Why does app.dependency_overrides help in tests?
Depends, so a test can substitute a fake provider.Q5. Which statement about a JWT payload is true?
Q6. When should an endpoint be plain def rather than async def?
def endpoints run in a thread pool, so blocking calls do not stall the event loop.Frequently asked questions
Is FastAPI better than Flask or Django?
+Do I have to use async def?
+No. Plain def endpoints are fully supported and run in a thread pool. Use async def when your code awaits async libraries.
What is the difference between FastAPI, Starlette, Pydantic and uvicorn?
+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.
How do I connect a database?
+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.
Where do I find current FastAPI features and syntax?
+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;
/docsis 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. - β
Dependsinjects helpers such as sessions and the current user, anddependency_overridesmakes endpoints easy to test. - βUse
async defonly with awaitable code; blocking work belongs in plaindefendpoints. - βJWTs are signed, not secret: keep keys in the environment, set expiries and test happy and error paths with
TestClient.