FastAPI Highlights Summary
Every highlight bullet from the 12 pages in this section, gathered on one page and grouped by the page it came from.
- FastAPI is a typed layer over Starlette, an ASGI toolkit, not a server of its own
- Route signatures are introspected once at startup to build a per-path dependency graph
- Pydantic validates and coerces input before your handler body ever runs
- Sync path operations and sync dependencies run in a threadpool; async ones run on the event loop
- response_model re-validates and filters output, independent of what your handler actually returns
- FastAPI 0.115+ uses Pydantic 2 for request and response validation
- Type hints drive OpenAPI schemas automatically
- Use async def when awaiting I/O; sync def for CPU-only handlers
- APIRouter splits large apps into feature modules
- response_model strips sensitive fields from JSON output
- Pydantic 2 models validate requests and shape responses at boundary
- Separate In/Out models hide secrets and match OpenAPI documentation
- Field validators normalize input like sorting tags to lowercase sets
- Reject unknown keys at boundary using ConfigDict extra forbid option
- Always validate at boundary with Pydantic, not just internally
- Use async drivers or run_in_threadpool to avoid blocking event loop
- Share database sessions and auth handlers via Depends yielding resources
- Yield in dependencies executes cleanup code after response delivery
- Dependencies cache by callable identity, executing only once per request
- Verify x_api_key headers against settings in sub-dependency chains
- Use app.dependency_overrides to replace providers in test isolation
- Apply route-level dependencies for header-based access control on endpoints
- Create async engines with asyncpg for non-blocking PostgreSQL queries
- Use async_sessionmaker with expire_on_commit=False for proper session lifecycle
- Inject request-scoped sessions via Depends(get_session) in async route handlers
- Keep transactions short to maximize event loop efficiency in high-concurrency APIs
- Query with SQLAlchemy 2.0 select style inside async route handlers
- Apply pool_pre_ping=True to detect stale database connections early
- OAuth2PasswordBearer dependency extracts and validates bearer tokens
- Hash passwords with argon2 or bcrypt, never store in plain text
- Catch jwt.PyJWTError and raise HTTPException 401 on invalid tokens
- Use short-lived access tokens plus refresh flow for browser clients
- Authorization checks permissions per resource after authentication proves identity
- Include exp claim in JWT to enforce token expiration times
- Use BackgroundTasks for fire-and-forget, Celery for durable cross-restart jobs
- Call tasks.add_task(work, args) to run work after HTTP response sent
- BackgroundTasks run on same worker after response, not separate process
- Celery workers retry and track visibility with Redis or RabbitMQ broker
- Decorate functions with @celery_app.task and call via func.delay(args)
- Never run heavy CPU or long I/O in BackgroundTasks during high load
- WebSockets upgrade HTTP into persistent framed channels for bidirectional messaging
- Use @app.websocket with ws.accept, ws.send_text, ws.close for real-time endpoints
- StreamingResponse yields async generator chunks as server-sent events for dashboards
- Catch WebSocketDisconnect exceptions to gracefully handle client disconnections
- Authenticate sockets at connect time using cookies or bearer tokens
- SSE format: prefix each chunk with event: name and data: content headers
- Add CORS middleware with allow_origins, allow_methods, allow_headers configurations
- Use HTTP middleware to inject X-Request-Id headers across all requests
- Register exception handlers that convert domain errors to safe JSON responses
- Middleware execution order follows add_middleware calls, outermost-first wrapping
- Log full server errors internally, return minimal safe information to clients
- Create custom AppError exceptions with code and status for consistent responses
- TestClient(app).get() runs routes in-process without network I/O
- Override app.dependency_overrides[func] to inject test doubles like fake DB
- Assert response.status_code and response.json() in regression tests
- Use httpx.AsyncClient with ASGITransport to test async route handlers
- Clear dependency_overrides after each test to avoid test pollution
- OpenAPI schema stays in sync with your actual route implementations
- Deploy FastAPI with Gunicorn using UvicornWorker for production scaling
- Scale Gunicorn workers based on CPU cores and connection pool limits
- Put TLS and rate limiting at the reverse proxy, not in Gunicorn workers
- Run database migrations as a separate job, not on pod startup
- Use /health endpoint returning JSON status for load balancer health probes
- Keep routers thin and services testable, one router module per domain area
- Validate at HTTP boundary with Pydantic 2 using separate input and output models
- Use async routes for I/O-heavy handlers and set timeouts on HTTP and DB calls
- Size database connection pools from max connections and worker count
- Never log tokens or passwords in FastAPI services
- Disable public docs in production and apply auth dependencies consistently
Revisado por Chris St. John·Última atualização: 31 de jul. de 2026