Why FastAPI?
FastAPI is a modern Python web framework that combines performance (async by default), developer experience (automatic OpenAPI docs), and type safety (Pydantic validation). It's one of the fastest Python frameworks and generates interactive API documentation automatically.
Getting Started
pip install fastapi uvicorn
# main.py
from fastapi import FastAPI
app = FastAPI(title="My API", version="1.0.0")
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/health")
async def health():
return {"status": "ok"}
uvicorn main:app --reload # run with auto-reload
# Docs: http://localhost:8000/docs (Swagger)
# Docs: http://localhost:8000/redoc
Request Validation with Pydantic
from fastapi import FastAPI
from pydantic import BaseModel, Field, EmailStr
from typing import Optional
from datetime import datetime
class UserCreate(BaseModel):
name: str = Field(min_length=2, max_length=100)
email: EmailStr
age: Optional[int] = Field(None, ge=0, le=150)
class UserResponse(BaseModel):
id: int
name: str
email: str
created_at: datetime
model_config = {"from_attributes": True} # for ORM models
@app.post("/users", response_model=UserResponse, status_code=201)
async def create_user(user: UserCreate):
# FastAPI validates user automatically
db_user = await db.create_user(user)
return db_user
Path, Query, and Header Parameters
from fastapi import Query, Header, Path
@app.get("/users/{user_id}")
async def get_user(
user_id: int = Path(gt=0),
include_posts: bool = Query(default=False),
x_api_key: str = Header(alias="X-API-Key"),
):
return {"user_id": user_id, "include_posts": include_posts}
# GET /users/42?include_posts=true
# Header: X-API-Key: my-key
Dependency Injection
from fastapi import Depends, HTTPException, status
from typing import Annotated
async def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
async def get_current_user(
token: str = Header(alias="Authorization"),
db = Depends(get_db),
) -> User:
user = await verify_token(token, db)
if not user:
raise HTTPException(status_code=401, detail="Invalid token")
return user
# Use as a dependency
@app.get("/me")
async def get_me(current_user: Annotated[User, Depends(get_current_user)]):
return current_user
Background Tasks and Middleware
from fastapi import BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://myapp.com"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/send-email")
async def send_email(
email: str, background_tasks: BackgroundTasks
):
background_tasks.add_task(send_email_task, email)
return {"message": "Email will be sent"}
Error Handling
from fastapi import HTTPException
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
@app.exception_handler(RequestValidationError)
async def validation_handler(request, exc):
return JSONResponse(
status_code=422,
content={"detail": exc.errors(), "body": str(exc.body)},
)
@app.get("/items/{item_id}")
async def get_item(item_id: int):
item = await db.get_item(item_id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
Frequently Asked Questions
FastAPI vs Flask vs Django?
FastAPI: async, automatic docs, Pydantic validation — best for APIs. Flask: simple, synchronous, flexible. Django: full-stack, batteries-included, ORM built-in. For new REST/GraphQL APIs, FastAPI is typically the best choice in 2026.
Is FastAPI production-ready?
Yes. FastAPI is used in production by major companies. Deploy with uvicorn behind nginx or directly on cloud platforms. Use gunicorn -k uvicorn.workers.UvicornWorker for multi-worker production deployments.
aiforeverthing.com — 100+ tools, no signup required
The fastest way to get this running in production is a Hostinger VPS — starting at $3.99/mo, includes one-click Docker support, full root access, and SSD storage. Readers of this guide can use the link below for up to 75% off.
Get Hostinger VPS → Affiliate link — we may earn a commission at no extra cost to you.