FastAPI - Modern Python Web Framework
What is FastAPI?
FastAPI is a modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. Created by Sebastián Ramirez, it's
designed to be fast, easy to use, and production-ready.
Key Features
High Performance: One of the fastest Python frameworks, comparable to NodeJS and Go
Fast Development: Increases development speed by 200-300%
Fewer Bugs: Reduces human-induced errors by ~40%
Intuitive: Great editor support with auto-completion everywhere
Easy: Designed to be easy to use and learn
Short : Minimize code duplication
Robust : Production-ready code with automatic interactive documentation
Standards-based : Based on OpenAPI and JSON Schema
Installation
pip install fastapi[all] # Includes uvicorn server
# or minimal installation
pip install fastapi uvicorn
Basic Example
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: bool = False
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
@app.post("/items/")
def create_item(item: Item):
return item
# Run with: uvicorn main:app --reload
Core Concepts
Path Parameters
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id}
Query Parameters
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
Request Body
@app.post("/items/")
def create_item(item: Item):
return {"item_name": item.name, "item_price": item.price}
Dependencies
from fastapi import Depends
def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
def read_items(commons: dict = Depends(common_parameters)):
return commons
Advanced Features
Middleware
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
Authentication
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi import Depends, HTTPException
security = HTTPBearer()
def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
# Validate token logic here
return {"username": "user"}
Background Tasks
from fastapi import BackgroundTasks
def write_notification(email: str, message=""):
with open("log.txt", mode="w") as email_file:
content = f"notification for {email}: {message}"
email_file.write(content)
@app.post("/send-notification/{email}")
def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Notification sent in the background"}
Best Practices
1. Use Type Hints: Always specify types for better IDE support and validation
2. Organize with Routers: Split large applications using APIRouter
3. Handle Errors : Use HTTPException for proper error responses
4. Validate Data: Leverage Pydantic models for request/response validation
5. Use Dependencies: Implement dependency injection for reusable logic
6. Document APIs: FastAPI automatically generates OpenAPI docs at /docs
Testing
from fastapi.testclient import TestClient
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"Hello": "World"}
Deployment
# Development
uvicorn main:app --reload --host 0.0.0.0 --port 8000
# Production with Gunicorn
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker
FastAPI combines the best of modern Python development with high performance, making it ideal for building robust APIs quickly and efficiently.