Build Modern, Production-Ready APIs and Web Applications with Python
Introduction
Who This Book Is For
How This Book Is Structured
The Running Application
Conventions Used in This Book
What You Will Be Able to Do After This Book
Part I: Foundations — Understanding FastAPI and Its Ecosystem
Chapter 1: Your First FastAPI Application
- Installing FastAPI and Uvicorn
- Writing Your First API Endpoint
- Running and Testing Your First App
- Understanding ASGI vs WSGI
- The Request-Response Lifecycle at a Glance
- Automatic Interactive Documentation
- Common Beginner Pitfalls
- Summary
Chapter 2: Python Type Hints and Pydantic — The Foundation of FastAPI
- Python Type Hints Refresher
- Pydantic Models: Definition, Validation, Serialization
- Nested Models and Complex Data Structures
- Field Configuration with Field()
- Custom Validators and Computed Fields
- When to Use TypedDict or Dataclasses Instead of Pydantic
- Summary
Part II: Core Features — Building Real APIs
Chapter 3: Routing, Parameters, and Request Bodies
- Path Operations and HTTP Methods
- Path Parameters: Typing, Validation, Regex Constraints
- Query Parameters: Optional vs Required, Defaults, Multiple Values
- Request Bodies with Pydantic Models
- Headers, Cookies, and Dependencies on Them
- Form Data and File Uploads
- Mixing Different Parameter Types
- Summary
Chapter 4: Responses, Status Codes, and Error Handling
- Response Models and Automatic Serialization
- HTTP Status Codes: Choosing the Right One
- Custom Responses: JSONResponse, FileResponse, HTMLResponse, StreamingResponse
- Headers and Cookies in Responses
- Exception Handling with Custom Exception Classes
- Global Error Handlers and Response Formatting
- Summary
Chapter 5: Dependency Injection — FastAPI’s Superpower
- What Dependency Injection Is and Why It Matters
- Defining Dependencies with Depends()
- Dependencies on Parameters and Other Dependencies
- Sub-dependencies and Dependency Graphs
- Yield-Based Dependencies for Setup and Teardown
- Dependency Override for Testing
- Common Patterns: Database Sessions, Current User, Config Access
- Summary
Chapter 6: Middleware, Lifespan Events, and Background Tasks
- What Middleware Is and How It Works in ASGI
- Writing Custom Middleware (Logging, Timing, Request ID)
- Built-in Middleware: CORS, TrustedHost, GZip
- Lifespan Events: Startup and Shutdown Hooks
- Background Tasks for Async Work After Responses
- When to Use Background Tasks vs Message Queues
- Summary
Chapter 7: Configuration, Logging, and OpenAPI Documentation
- Environment-Based Configuration (Pydantic Settings)
- Loading Config from .env Files, Environment Variables, and Secrets
- Structured Logging with Python Logging Module
- Log Levels, Formatters, and Handlers for Production
- OpenAPI Specification: What It Is and How FastAPI Generates It
- Customizing Documentation (Swagger UI, ReDoc, API Title/Version)
- Hiding Endpoints from Docs, Custom Tags, Grouping
- Summary
Part III: Data Layer — Databases, ORMs, and Persistence
Chapter 8: Database Integration with SQLAlchemy
- Relational Database Concepts for API Developers
- Installing and Configuring SQLAlchemy with PostgreSQL
- Async Engine and Session Setup
- Defining Models (Declarative Base, Columns, Types)
- CRUD Operations: Create, Read, Update, Delete
- Filtering, Ordering, Pagination in Queries
- Summary
Chapter 9: Relationships, Transactions, and Migrations
- One-to-Many, Many-to-One, and Many-to-Many Relationships
- Loading Strategies: Eager vs Lazy Loading
- Transaction Management in FastAPI
- Database Migrations with Alembic
- Summary
Chapter 10: Repository and Service Patterns
- Why Separation of Concerns Matters in APIs
- The Repository Pattern: Abstracting Data Access
- The Service Layer: Encapsulating Business Logic
- Wiring Repositories and Services with Dependencies
- Handling Errors at Each Layer
- When to Skip Patterns (Small Apps) vs When They Are Essential
- Summary
Part IV: Security, Authentication, and Advanced Features
Chapter 11: Authentication and Authorization
- Auth vs Authorization: Key Concepts
- Password Hashing with Argon2
- Session-Based Authentication (Cookies)
- JWT Tokens: Structure, Signing, Verification
- OAuth2 Password Flow with FastAPI Security
- Role-Based and Permission-Based Access Control
- Securing Individual Endpoints
- Summary
Chapter 12: Security Best Practices and Hardening
- HTTPS and TLS in Production
- CORS Configuration and Common Mistakes
- Input Validation and Sanitization
- SQL Injection Prevention (Parameterized Queries)
- Rate Limiting and Throttling
- Security Headers
- Secrets Management in Production
- Summary
Chapter 13: Advanced Features — WebSockets, Streaming, Caching, Pagination, and External APIs
- WebSockets: Setup, Message Handling, Connection Management
- Server-Sent Events (SSE) as an Alternative to WebSockets
- Streaming Responses for Large Data
- Caching Strategies: In-Memory, Redis, HTTP Cache Headers
- Pagination Patterns: Offset, Cursor, Keyset
- Filtering and Searching APIs
- External API Integration with httpx
- Summary
Part V: Testing, Architecture, and Production Deployment
Chapter 14: Testing FastAPI Applications
- Why Test APIs and What to Test (Unit vs Integration vs E2E)
- Using TestClient for Request-Level Testing
- Testing Path Operations, Validation, and Responses
- Mocking External Services and Dependencies
- Using Dependency Overrides in Tests
- Database Testing Strategies (In-Memory SQLite, Fixtures, Transactions)
- Async Test Patterns with pytest-asyncio
- Summary
Chapter 15: Architecture, Deployment, and Production Operations
- Project Structure for Medium to Large Applications
- Modularization with Routers and Packages
- Docker Containerization (Multi-Stage Builds)
- Production ASGI Servers: Uvicorn Workers, Gunicorn
- Reverse Proxies: Nginx Configuration
- CI/CD Pipelines (GitHub Actions Example)
- Monitoring, Health Checks, and Observability
- Scaling Strategies and Performance Tuning
- Summary