FastAPI
Build production-ready, lightning-fast asynchronous REST APIs in Python with automatic OpenAPI documentation and Pydantic validation.
FastAPI is an asynchronous Python web framework built on Starlette for routing and Pydantic for data validation. It generates OpenAPI specifications automatically from standard Python type hints and runs on any ASGI-compliant server such as Uvicorn.
Installation and Basic Application
Install the framework along with standard dependencies (Uvicorn and Pydantic):
pip install "fastapi[standard]"
A minimal application defines routes by attaching HTTP method decorators to functions:
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
def health_check():
return {"status": "healthy"}
Run the application using Uvicorn:
uvicorn main:app --reload
Visiting http://127.0.0.1:8000/docs displays the automatically generated Swagger UI documentation. Visiting http://127.0.0.1:8000/redoc displays the alternative ReDoc interface.
Path and Query Parameters
FastAPI infers parameter sources from function signatures:
- Variables declared inside the route path (
{item_id}) are parsed as path parameters. - Variables not present in the route path are parsed as query parameters.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int, skip: int = 0, limit: int = 10):
return {
"item_id": item_id,
"skip": skip,
"limit": limit
}
If a client requests /items/abc, FastAPI immediately returns an HTTP 422 Unprocessable Entity because item_id cannot be parsed as an integer.
Request Bodies with Pydantic
Incoming JSON request payloads are validated using Pydantic models:
from fastapi import FastAPI, status
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
name: str = Field(min_length=1, max_length=100)
price: float = Field(gt=0)
in_stock: bool = True
@app.post("/items/", status_code=status.HTTP_201_CREATED)
def create_item(item: Item):
data = item.model_dump()
return {"created": True, "item": data}
FastAPI reads the request body, parses the JSON payload, validates each field against the model constraints, and passes the validated Item instance to the function.
HTTP Status Codes and Error Handling
Raise HTTPException to return standard error responses with custom status codes and messages:
from fastapi import FastAPI, HTTPException, status
app = FastAPI()
database = {1: "Keyboard", 2: "Monitor"}
@app.get("/devices/{device_id}")
def get_device(device_id: int):
if device_id not in database:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Device {device_id} not found"
)
return {"id": device_id, "name": database[device_id]}
Async vs Def Route Handlers
FastAPI supports both standard synchronous functions (def) and asynchronous functions (async def):
# Async handler: executes directly on the main event loop
@app.get("/async-data")
async def get_async_data():
# Use non-blocking async calls
return {"type": "async"}
# Sync handler: FastAPI runs this in an external threadpool
@app.get("/sync-data")
def get_sync_data():
# Safe to use blocking database libraries or file I/O
return {"type": "sync"}
If you write
async def, do not call blocking functions liketime.sleep()or synchronous database queries. Doing so blocks the single event loop thread for all concurrent requests. Use standarddeffor blocking I/O, which FastAPI automatically offloads to a thread pool.
Framework Comparison
| Feature | FastAPI | Flask | Django |
|---|---|---|---|
| Server Interface | ASGI (Native async) | WSGI (Synchronous) | WSGI / ASGI |
| Request Validation | Built-in (Pydantic) | Manual / Extensions | Form / Serializer classes |
| Documentation | Automatic (/docs, /redoc) | Manual setup | Manual setup |
| Included Tooling | API-focused | Minimal microframework | Full-stack (ORM, Admin, Auth) |
| Common Use | High-throughput REST APIs | Simple microservices | Monolithic web applications |