← Back to courses
FastAPI
Modern Python web APIs · Async · Type-safe · Auto docs · From first route to production
01Foundations- Install it, create the app, and turn ordinary Python functions into endpoints that check their own input
Setupstart here
Install FastAPI, start it on your machine, and lay out the files.
pip install "fastapi[standard]"
fastapi dev main.py
/docs -> Swagger UI
3 topics
App instancecore
Create the app object and set the title and version shown in its docs.
app = FastAPI(title=..., version=...)
@app.get("/") -> dict
dict -> JSON automatically
2 topics
Routingmethods
The @app.get and @app.post decorators, the usual URL naming rules, and the options each route takes.
@app.get / post / put / patch / delete
specific paths before {dynamic}
response_model shapes output
3 topics
Path & query paramsparams
Values from the URL path and from the ?query=... part, converted to the type you ask for and checked against limits.
{user_id} in path -> path param
simple type + default -> query
Path()/Query() add constraints
4 topics
Request bodybody
Using a Pydantic model to describe the JSON sent in a request, plus single values with Body() and models inside models.
item: Item -> parsed JSON body
Body(embed=True) wraps by name
nested models validate recursively
3 topics
Pydantic & validationpydantic v2
Limits on each field, your own checking functions, per-model settings, and the handy built-in types.
Field(..., min_length=3, ge=0)
@field_validator / @model_validator
from_attributes=True for ORM
5 topics
02HTTP layer- Control what you send back, read headers and cookies, accept file uploads, and fail in a tidy way
Responsesoutput
Using response_model to drop fields you do not want to send, setting the status code, and picking a response type.
response_model=UserOut strips fields
status_code=201 / 204
JSON, Redirect, File, Streaming
2 topics
Headers & cookieshttp
Read the headers and cookies the caller sent, and set your own on the reply.
user_agent: str = Header(None)
response.set_cookie(httponly=True)
hyphen -> underscore automatically
2 topics
Files & formsmultipart
Receiving uploaded files, checking them before you keep them, and reading normal form fields.
file: UploadFile
name: str = Form(...)
needs python-multipart
2 topics
Error handlingerrors
Raising HTTPException, defining your own error types, and handling anything that slips through.
raise HTTPException(404, detail)
@app.exception_handler(MyError)
catch-all: log, never leak traces
2 topics
03Architecture- Shared setup code, wrappers that run around every request, and startup/shutdown work - the pieces that hold a real app together
DependenciesDI
Depends() for shared setup, yield when something must be cleaned up afterwards, and where to attach each one.
x = Depends(get_x)
yield -> setup / teardown
route, router, or app-wide
3 topics
Middlewarecross-cutting
CORS so a browser app can call you, your own logging and timing wrappers, and the security ones that ship with FastAPI.
CORSMiddleware for the frontend
dispatch(request, call_next)
TrustedHost, GZip
2 topics
Lifecyclestartup
Open shared resources at startup and close them at shutdown.
@asynccontextmanager lifespan
before yield: startup
after yield: shutdown
1 topic
04Advanced- Auth, databases, async, modular routers, testing, and production hardening
Auth & securityJWT
Logging in with a JWT token, a dependency that hands you the current user, role checks, and API keys.
POST /login -> issue JWT
Bearer header -> get_current_user
require_role("admin")
4 topics
DatabaseSQLAlchemy
Talking to PostgreSQL without blocking: the engine, sessions, and create/read/update/delete.
create_async_engine(url)
SessionLocal = async_sessionmaker
select / update / delete
2 topics
Async patternsasync
When to write async def and when plain def, work done after the reply, task queues, WebSockets, and server-sent events.
async def for awaited I/O
def for blocking libs (thread pool)
never time.sleep() in async
5 topics
Routersmodules
Split your routes into separate APIRouter files and keep old versions working.
router = APIRouter(prefix="/users")
app.include_router(router)
/api/v1, /api/v2
1 topic
Testingpytest
TestClient for quick tests, httpx for async ones, and swapping a dependency for a fake.
client = TestClient(app)
AsyncClient(transport=ASGITransport(app))
app.dependency_overrides[dep] = fake
3 topics
Productiondeploy
Settings read from the environment, limits on how often someone can call you, and health check endpoints.
BaseSettings reads .env
@limiter.limit("5/minute")
GET /health checks the DB
3 topics
05Reference- The commands and function signatures you reach for most, on one page
Work through the groups in order the first time - each builds on the last. After that, use search to jump straight to the snippet you need.