FastAPI Cheatsheet
Setup
Use this FastAPI reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Installation
Use this FastAPI cheatsheet as a compact backend API reference while you build portfolio projects or move through a computer science curriculum. It covers setup, route structure, typed validation, and deployment habits for software engineering interviews.
pip install fastapi uvicorn[standard] # optional extras pip install fastapi[all] # includes uvicorn, pydantic, python-multipart, etc. pip install sqlalchemy alembic # DB pip install python-jose[cryptography] passlib[bcrypt] # auth
Minimal App
from fastapi import FastAPI app = FastAPI() @app.get("/") def root(): return {"message": "Hello, World"}
Running the Server
# development (auto-reload) uvicorn main:app --reload # specify host/port uvicorn main:app --host 0.0.0.0 --port 8080 --reload # production (multiple workers) uvicorn main:app --workers 4 # or with gunicorn (process manager) gunicorn main:app -k uvicorn.workers.UvicornWorker -w 4
main= the Python file name;app= the FastAPI instance name.
App Constructor Options
app = FastAPI( title="My API", description="API description shown in docs", version="1.0.0", docs_url="/docs", # Swagger UI (None to disable) redoc_url="/redoc", # ReDoc (None to disable) openapi_url="/openapi.json", terms_of_service="https://example.com/terms", contact={"name": "Dev", "email": "dev@example.com"}, license_info={"name": "MIT"}, root_path="/api/v1", # useful behind a proxy/gateway openapi_tags=[ # tag metadata for docs grouping {"name": "users", "description": "User operations"}, ], )
Project Layout (recommended)
project/ ├── app/ │ ├── __init__.py │ ├── main.py # FastAPI() instance + include_router │ ├── dependencies.py # shared Depends() │ ├── models.py # Pydantic schemas │ ├── database.py # SQLAlchemy engine / session │ └── routers/ │ ├── users.py │ └── items.py ├── tests/ └── requirements.txt
Including Routers
# app/routers/users.py from fastapi import APIRouter router = APIRouter(prefix="/users", tags=["users"]) @router.get("/") def list_users(): return [] # app/main.py from fastapi import FastAPI from app.routers import users app = FastAPI() app.include_router(users.router) app.include_router( items.router, prefix="/items", tags=["items"], dependencies=[Depends(verify_token)], # apply to all routes responses={404: {"description": "Not found"}}, )
Startup / Shutdown Events
# Modern: lifespan context manager (FastAPI >= 0.93) from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): # startup logic db.connect() yield # shutdown logic db.disconnect() app = FastAPI(lifespan=lifespan) # Legacy (still works but deprecated): @app.on_event("startup") async def startup(): await db.connect() @app.on_event("shutdown") async def shutdown(): await db.disconnect()
Environment / Settings (pydantic-settings)
# pip install pydantic-settings from pydantic_settings import BaseSettings class Settings(BaseSettings): database_url: str secret_key: str debug: bool = False model_config = {"env_file": ".env", "env_file_encoding": "utf-8"} settings = Settings() # reads from environment / .env automatically # in a route or dependency: from functools import lru_cache @lru_cache def get_settings() -> Settings: return Settings()
Interactive Docs
| URL | Tool |
|---|---|
/docs | Swagger UI (try-it-out) |
/redoc | ReDoc (read-only, clean) |
/openapi.json | Raw OpenAPI schema |