
FastAPI
FastAPI is built on ASGI (Asynchronous Server Gateway Interface) and combines Starlette (web framework) with Pydantic (validation). Understanding this architecture is essential for building scalable systems.
ASGI provides true asynchronous I/O, enabling concurrent request handling:
# WSGI (Synchronous) - blocks on I/O operations
def app(environ, start_response):
result = requests.get("http://api.example.com/data") # Blocks
start_response('200 OK', [('Content-Type', 'text/plain')])
return [result.content]
# ASGI/FastAPI (Asynchronous) - doesn't block
@app.get("/data")
async def get_data():
async with httpx.AsyncClient() as client:
result = await client.get("http://api.example.com/data") # Non-blocking
return {"data": result.text}Client Request
↓
Uvicorn/Gunicorn (ASGI Server)
↓
Starlette Routing (URL Pattern Matching)
↓
Path Parameters Extraction & Validation
↓
Query Parameters Extraction & Validation
↓
Request Body Parsing (JSON/Form)
↓
Pydantic Model Validation
↓
Dependency Injection (Depends)
↓
Route Handler Function Execution
↓
Response Serialization (JSON)
↓
Response Headers & Status Code
↓
Client Responsefrom fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from starlette.middleware.base import BaseHTTPMiddleware
import logging
import time
logger = logging.getLogger(__name__)
app = FastAPI()
# Trust specific hosts
app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=["example.com", "www.example.com"]
)
# CORS configuration
app.add_middleware(
CORSMiddleware,
allow_origins=["https://example.com"],
allow_credentials=True,
allow_methods=["GET", "POST"],
allow_headers=["*"],
)
# Custom middleware for timing
class TimingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
logger.info(f"{request.method} {request.url.path} - {process_time:.3f}s")
return response
app.add_middleware(TimingMiddleware)import httpx
from contextlib import asynccontextmanager
# Create a persistent connection pool
client = httpx.AsyncClient()
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
app.state.client = httpx.AsyncClient()
yield
# Shutdown
await app.state.client.aclose()
app = FastAPI(lifespan=lifespan)
@app.get("/external-data")
async def get_external_data():
response = await app.state.client.get("http://api.example.com/data")
return response.json()from fastapi_cache2 import FastAPICache
from fastapi_cache2.backends.redis import RedisBackend
from fastapi_cache2.decorators import cache
from redis import asyncio as aioredis
@app.on_event("startup")
async def startup():
redis = aioredis.from_url("redis://localhost")
FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
@app.get("/cached-data")
@cache(expire=300) # Cache for 5 minutes
async def get_cached_data():
# This response will be cached
return {"data": "expensive operation result"}# Install
pip install gunicorn
# Run with 4 workers
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app --bind 0.0.0.0:8000FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "main:app", "--bind", "0.0.0.0:8000"]from fastapi import FastAPI, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthCredentials
import secrets
security = HTTPBearer()
app = FastAPI()
@app.get("/secure")
async def secure_endpoint(credentials: HTTPAuthCredentials = Depends(security)):
# Validate token securely
correct_token = secrets.compare_digest(
credentials.credentials,
"your-secret-token"
)
if not correct_token:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid credentials"
)
return {"message": "Access granted"}Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward