What is FastAPI?
FastAPI is a modern, high-performance Python framework for building REST APIs. It uses Python type hints, provides automatic validation, and generates interactive API documentation out of the box.Key Features of FastAPI
- 🚀 High Performance: Built on top of Starlette and Pydantic, making it one of the fastest Python frameworks available, on par with Node.js and Go.
- ✍️ Faster Coding: Speeds up feature development by 200% to 300%.
- 🛡️ Fewer Bugs: Reduces developer-induced errors by about 40% through automatic validation.
- 📖 Auto-Generated Documentation: Generates interactive documentation pages (Swagger UI and ReDoc) automatically.
- 🔒 Modern & Async: Native support for asynchronous programming (
async/await) out of the box.
FastAPI vs. Django (API-First vs. Full-Stack)
When comparing backend frameworks, it is important to understand their core objectives:- Django (Full-Stack): Designed as a “batteries-included” framework that renders HTML templates directly on the server to send full pages to the browser.
- FastAPI (API-First): Focuses solely on building high-performance REST/GraphQL APIs that return structured data (typically JSON).
Why API-First is Crucial for Modern & GenAI Apps
This backend-frontend decoupling is the industry standard today:- Modern Frontends: Single Page Applications (Next.js, React, Vue) and mobile apps only require a backend to serve raw JSON data, not server-rendered HTML.
- Generative AI (GenAI): AI agents, LLM tool-calling (OpenAI, Claude), and real-time streaming interfaces rely heavily on highly concurrent web services. FastAPI’s async speed makes it the primary choice for modern AI and GenAI backend applications.
The Tech Stack Under the Hood
FastAPI stands on the shoulders of giants:- Uvicorn: An ASGI (Asynchronous Server Gateway Interface) web server implementation for Python. It acts as the web server that receives incoming TCP connections from clients and forwards them to FastAPI.
- Starlette: A lightweight ASGI framework toolkit. FastAPI inherits all its routing and web handling capabilities from Starlette.
- Pydantic: The data validation and serialization library. It enforces types and formats data.
FastAPI Architecture
FastAPI is not built from scratch. It combines the strengths of Python, Starlette, and Pydantic, while adding its own API-specific features.Python Language Features
FastAPI relies heavily on Python’s language features.- Functions
- Classes & Objects
- Type Hints
- Function Parameters
- Default Arguments
- Async/Await
- Decorators
- Generators (
yield) - Context Managers
- Exceptions
- Modules & Packages
- Function definition
- Decorator syntax
- Type hints
- Default arguments
- Async programming support
Starlette Responsibilities (Web Layer)
Starlette provides the web framework capabilities.- ASGI application
- Routing
- Request object
- Response classes
- Middleware
- Exception handling
- WebSockets
- Background Tasks
- Static Files
- Template rendering
- Lifespan events (startup/shutdown)
Pydantic Responsibilities (Data Layer)
Pydantic handles data validation and serialization.- Data Models (
BaseModel) - Request Body Validation
- Type Conversion
- Serialization (
model_dump()) - Deserialization
- Field Validation
- JSON Schema Generation
- Settings Management (
BaseSettings)
- Validates input data
- Converts compatible types
- Generates validation errors
- Serializes responses
- Generates schemas for API documentation
FastAPI Responsibilities
FastAPI binds Starlette and Pydantic together and adds API-specific features.Request Handling
- Path Parameters
- Query Parameters
- Headers
- Cookies
- Request Body Parsing
Dependency Injection
Depends()- Automatic dependency resolution
- Dependency cleanup using
yield
Response Handling
- Response Models
- Automatic serialization
- Status code handling
API Documentation
- OpenAPI generation
- Swagger UI
- ReDoc
Security
- OAuth2 helpers
- JWT integration helpers
- API Key support
- Security dependencies
Routing Enhancements
- APIRouter
- Tags
- Prefixes
- API versioning support
Responsibility Summary
How They Work Together
Summary
Learning Objectives in this chapter..
After completing this chapter, you will be able to:- Install and configure FastAPI
- Create and run your first API
- Understand routing and HTTP methods
- Work with path and query parameters
- Accept request data using Pydantic models
- Return structured responses
- Validate request data
- Use HTTP status codes
- Explore the generated API documentation
Prerequisites
- Python 3.10 or later
- pip or uv
- Virtual Environment (recommended)
- VS Code or any Python IDE
Creating a Virtual Environment
Installing FastAPI
Your First FastAPI Application
Create a file namedmain.py.
Understanding the First FastAPI Program
Unlike traditional Python programs, a FastAPI application is not a program that runs from top to bottom and immediately produces an output. Instead, we configure the FastAPI server by telling it:- What application to create
- Which URLs it should respond to
- Which function should execute for each URL
Key Points
1. Import the FastAPI Class
2. Create the Application
app object stores:
- API endpoints
- Application configuration
- Middleware
- Dependencies
- API documentation
Note: This does not start the server. It only creates and configures the application.
3. Register an Endpoint
/).
It tells FastAPI:
“If a GET request is received for /, execute the function below.”
4. Define the Request Handler
5. Return the Response
6. JSON is the Default Response Format
FastAPI automatically converts Python objects such as:- Dictionaries
- Lists
- Pydantic models
Traditional Python vs FastAPI
Traditional Python
- Program executes from top to bottom.
- Functions are called explicitly by the programmer.
- Program ends after execution.
FastAPI
- You configure the application.
- Register API endpoints.
- Start the server.
- FastAPI waits for incoming requests.
- FastAPI automatically calls the appropriate function when a request arrives.
Execution Flow
Key Takeaways
FastAPI()creates the web application.@app.get("/")registers an endpoint.- Functions are executed automatically by FastAPI.
- Most FastAPI code is configuration, not direct execution.
- By default, FastAPI returns responses in JSON format.
- FastAPI handles request routing and response generation automatically.
Running the Application
main→ Python file (main.py)app→ FastAPI application object--reload→ Restart server on code changes--host→ Host address--port→ Server port
Accessing the Application
Routing
A route maps an API endpoint to a Python function.Common conventions for designing clean and consistent REST APIs
General Guidelines
- Use nouns for resources, not verbs.
- Use plural resource names.
- Keep URLs lowercase.
- Use hyphens (
-) instead of underscores (_). - Keep URLs short and meaningful.
Good Examples
Bad Examples
HTTP Methods
Path Variables
Use path variables when identifying a specific resource.Good Examples
Bad Examples
Rule: If the value uniquely identifies a resource, use a path variable.
Query Parameters
Use query parameters for optional operations, such as:- Filtering
- Searching
- Sorting
- Pagination
Good Examples
Bad Examples
Rule: If the parameter changes how data is retrieved rather than which resource is retrieved, use a query parameter.
Request Body
Use the request body with POST, PUT, and PATCH requests.Student API Example
Quick Rules
Common Routes
A route simply connects an API endpoint to a Python function.
Path Parameters
Path parameters are part of the URL and identify a specific resource.Query Parameters
Query parameters appear after the? in the URL.
- Searching
- Filtering
- Sorting
- Pagination
Request Body
Use a Pydantic model to receive JSON data.Response Models
Define the response structure usingresponse_model.
Status Codes
Request Validation
FastAPI automatically validates incoming data.Data Validation can be applied to:
- Request Body using
Field() - Query Parameters using
Query() - Path Parameters using
Path()
Annotated type.
What is Annotated?
Annotated lets you combine a data type with validation metadata.
Syntax
intspecifies the expected data type.Field(gt=0, lt=100)specifies the validation rules.
Annotated is the recommended approach in FastAPI and Pydantic v2.
1. Field() – Request Body Validation
Field() is used inside Pydantic models to validate request body fields.
Recommended
2.Query() – Query Parameter Validation
Query() validates values passed as query parameters.
Example request:
3. Path() – Path Parameter Validation
Path() validates values passed as path parameters.
Example request:
Common Validation Options
Common Pydantic Types
Example:
Note:EmailStrrequires theemail-validatorpackage.
Automatic API Documentation
Quick Commands
Summary
In this chapter, you learned how to:- Install FastAPI
- Create and run a FastAPI application
- Define routes
- Work with path and query parameters
- Accept request bodies
- Return response models
- Validate request data
- Use HTTP status codes
- Explore the generated API documentation