Leanpub Header

Skip to main content

Web Development with FastAPI

Build Modern, Production-Ready APIs and Web Applications with Python

Web Development with FastAPI
This book is 100% completeLast updated on 2026-08-23

Build fast, modern web applications with Python and FastAPI. Starting with your first endpoint, you’ll develop a real application step by step while learning databases, authentication, WebSockets, testing, Docker and deployment. By the end, you’ll know how to turn Python code into secure, production-ready systems.

Minimum price

$19.00

$29.00

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

PDF
EPUB
WEB
APP
210
Pages
About

About

About the Book

This book takes you from your first FastAPI endpoint to designing, building, testing, securing, and deploying professional production-grade systems. You will learn the framework through a realistic application that grows chapter by chapter, gaining hands-on experience with type hints, Pydantic validation, SQLAlchemy databases, authentication, WebSockets, caching, testing with pytest, Docker containerization, and production deployment behind Nginx. No prior web framework experience is required beyond basic Python knowledge.

Author

About the Author

Steve Publications

Steve is a technology professional with more than 20 years of experience in software development, server infrastructure, cybersecurity, vulnerability research and reverse engineering. Throughout his career, he has designed, secured, analyzed and tested complex software and infrastructure, with a particular focus on understanding how systems fail and how they can be made more secure.

Outside of work, Steve enjoys sharing knowledge with the technology community. He collaborates with researchers, industry experts and technology professionals to write practical books covering software development, cybersecurity, cloud computing, networking, DevOps, artificial intelligence and enterprise technologies. His books focus on practical learning through clear explanations, real-world examples and hands-on exercises. With more than two decades of industry experience, his goal is to help IT professionals, students and technology enthusiasts build useful skills and stay current in a rapidly changing industry.

We believe readers deserve to know how our books are created. Most of our authors are not native English speakers, so we use AI to help translate, proofread manuscripts, fix grammar, improve sentence structure and make technical explanations easier to read. AI is used as an editing tool only. It does not replace the research, technical knowledge or hands-on experience behind our books. Some of our authors also prefer to remain anonymous for privacy or professional reasons. In those cases, we publish their work under a different name. The author's name may be different, but the quality of the content and our review process remain the same.

Every book is written, reviewed and maintained by experienced technology professionals, with contributions from our private technical community of more than 420 engineers and researchers. We spend far more time validating technical accuracy and keeping our content up to date than generating text. We are always interested in working with experienced professionals who have deep expertise in a particular technology or domain. If you would like to publish a book with us or help review an existing manuscript, we'd love to hear from you. Send us a message describing your area of expertise. We are especially interested in niche technologies, specialized skills and emerging topics that are underrepresented in existing technical literature.

If you look through the contents of our books, you'll see practical examples, detailed explanations and material that is regularly updated. Our goal is to publish books that professionals can actually rely on, not low-effort AI-generated content. If you ever feel that one of our books does not meet that standard, Leanpub offers a 60-day money-back guarantee. Feel free to request a refund if you are not satisfied with your purchase.

Contents

Table of Contents

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

  1. Installing FastAPI and Uvicorn
  2. Writing Your First API Endpoint
  3. Running and Testing Your First App
  4. Understanding ASGI vs WSGI
  5. The Request-Response Lifecycle at a Glance
  6. Automatic Interactive Documentation
  7. Common Beginner Pitfalls
  8. Summary

Chapter 2: Python Type Hints and Pydantic — The Foundation of FastAPI

  1. Python Type Hints Refresher
  2. Pydantic Models: Definition, Validation, Serialization
  3. Nested Models and Complex Data Structures
  4. Field Configuration with Field()
  5. Custom Validators and Computed Fields
  6. When to Use TypedDict or Dataclasses Instead of Pydantic
  7. Summary

Part II: Core Features — Building Real APIs

Chapter 3: Routing, Parameters, and Request Bodies

  1. Path Operations and HTTP Methods
  2. Path Parameters: Typing, Validation, Regex Constraints
  3. Query Parameters: Optional vs Required, Defaults, Multiple Values
  4. Request Bodies with Pydantic Models
  5. Headers, Cookies, and Dependencies on Them
  6. Form Data and File Uploads
  7. Mixing Different Parameter Types
  8. Summary

Chapter 4: Responses, Status Codes, and Error Handling

  1. Response Models and Automatic Serialization
  2. HTTP Status Codes: Choosing the Right One
  3. Custom Responses: JSONResponse, FileResponse, HTMLResponse, StreamingResponse
  4. Headers and Cookies in Responses
  5. Exception Handling with Custom Exception Classes
  6. Global Error Handlers and Response Formatting
  7. Summary

Chapter 5: Dependency Injection — FastAPI’s Superpower

  1. What Dependency Injection Is and Why It Matters
  2. Defining Dependencies with Depends()
  3. Dependencies on Parameters and Other Dependencies
  4. Sub-dependencies and Dependency Graphs
  5. Yield-Based Dependencies for Setup and Teardown
  6. Dependency Override for Testing
  7. Common Patterns: Database Sessions, Current User, Config Access
  8. Summary

Chapter 6: Middleware, Lifespan Events, and Background Tasks

  1. What Middleware Is and How It Works in ASGI
  2. Writing Custom Middleware (Logging, Timing, Request ID)
  3. Built-in Middleware: CORS, TrustedHost, GZip
  4. Lifespan Events: Startup and Shutdown Hooks
  5. Background Tasks for Async Work After Responses
  6. When to Use Background Tasks vs Message Queues
  7. Summary

Chapter 7: Configuration, Logging, and OpenAPI Documentation

  1. Environment-Based Configuration (Pydantic Settings)
  2. Loading Config from .env Files, Environment Variables, and Secrets
  3. Structured Logging with Python Logging Module
  4. Log Levels, Formatters, and Handlers for Production
  5. OpenAPI Specification: What It Is and How FastAPI Generates It
  6. Customizing Documentation (Swagger UI, ReDoc, API Title/Version)
  7. Hiding Endpoints from Docs, Custom Tags, Grouping
  8. Summary

Part III: Data Layer — Databases, ORMs, and Persistence

Chapter 8: Database Integration with SQLAlchemy

  1. Relational Database Concepts for API Developers
  2. Installing and Configuring SQLAlchemy with PostgreSQL
  3. Async Engine and Session Setup
  4. Defining Models (Declarative Base, Columns, Types)
  5. CRUD Operations: Create, Read, Update, Delete
  6. Filtering, Ordering, Pagination in Queries
  7. Summary

Chapter 9: Relationships, Transactions, and Migrations

  1. One-to-Many, Many-to-One, and Many-to-Many Relationships
  2. Loading Strategies: Eager vs Lazy Loading
  3. Transaction Management in FastAPI
  4. Database Migrations with Alembic
  5. Summary

Chapter 10: Repository and Service Patterns

  1. Why Separation of Concerns Matters in APIs
  2. The Repository Pattern: Abstracting Data Access
  3. The Service Layer: Encapsulating Business Logic
  4. Wiring Repositories and Services with Dependencies
  5. Handling Errors at Each Layer
  6. When to Skip Patterns (Small Apps) vs When They Are Essential
  7. Summary

Part IV: Security, Authentication, and Advanced Features

Chapter 11: Authentication and Authorization

  1. Auth vs Authorization: Key Concepts
  2. Password Hashing with Argon2
  3. Session-Based Authentication (Cookies)
  4. JWT Tokens: Structure, Signing, Verification
  5. OAuth2 Password Flow with FastAPI Security
  6. Role-Based and Permission-Based Access Control
  7. Securing Individual Endpoints
  8. Summary

Chapter 12: Security Best Practices and Hardening

  1. HTTPS and TLS in Production
  2. CORS Configuration and Common Mistakes
  3. Input Validation and Sanitization
  4. SQL Injection Prevention (Parameterized Queries)
  5. Rate Limiting and Throttling
  6. Security Headers
  7. Secrets Management in Production
  8. Summary

Chapter 13: Advanced Features — WebSockets, Streaming, Caching, Pagination, and External APIs

  1. WebSockets: Setup, Message Handling, Connection Management
  2. Server-Sent Events (SSE) as an Alternative to WebSockets
  3. Streaming Responses for Large Data
  4. Caching Strategies: In-Memory, Redis, HTTP Cache Headers
  5. Pagination Patterns: Offset, Cursor, Keyset
  6. Filtering and Searching APIs
  7. External API Integration with httpx
  8. Summary

Part V: Testing, Architecture, and Production Deployment

Chapter 14: Testing FastAPI Applications

  1. Why Test APIs and What to Test (Unit vs Integration vs E2E)
  2. Using TestClient for Request-Level Testing
  3. Testing Path Operations, Validation, and Responses
  4. Mocking External Services and Dependencies
  5. Using Dependency Overrides in Tests
  6. Database Testing Strategies (In-Memory SQLite, Fixtures, Transactions)
  7. Async Test Patterns with pytest-asyncio
  8. Summary

Chapter 15: Architecture, Deployment, and Production Operations

  1. Project Structure for Medium to Large Applications
  2. Modularization with Routers and Packages
  3. Docker Containerization (Multi-Stage Builds)
  4. Production ASGI Servers: Uvicorn Workers, Gunicorn
  5. Reverse Proxies: Nginx Configuration
  6. CI/CD Pipelines (GitHub Actions Example)
  7. Monitoring, Health Checks, and Observability
  8. Scaling Strategies and Performance Tuning
  9. Summary

Conclusion

References

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $15 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub