FastAPI Foundations
FastAPI is a modern Python web framework for building high-performance REST APIs. It combines Python’s type annotations, Pydantic models, and automatic API documentation to simplify backend development. Before learning FastAPI, it’s important to understand how modern web applications communicate and why REST APIs have become the standard for backend development.Topics Covered
In this module, you’ll learn:- Client and Server
- Backend Development
- APIs and REST APIs
- Quick Start
- HTTP Fundamentals
- FastAPI Fundamentals
- Routing and Request Handling
- Request Validation
- Response Models
- Exception Handling
- Building REST APIs
- Best Practices
Try Yourself: 💻 VS Code | 🚀 Colab | 📥 DownloadBy the end of this module, you’ll understand how web applications communicate and build your own REST APIs using FastAPI.
Verify Solutions: 💻 VS Code | 🚀 Colab | 📥 Download
Client and Server
Most modern applications follow the Client-Server Architecture. The client requests a service. The server processes the request and returns a response.Examples of Clients
- Web Browser
- React Application
- Angular Application
- Vue Application
- Flutter Application
- Android Application
- iOS Application
- Postman
Examples of Servers
- FastAPI
- Django
- Flask
- Express.js
- Spring Boot
Exercise 1
Identify whether each of the following is a Client or a Server.Solution
Solution
Exercise 2
Give any three examples of client applications.Solution
Solution
Possible answers:
- Chrome
- Edge
- React
- Flutter
- Android
- iOS
- Postman
Backend Development
The backend is responsible for processing requests and managing application data. Its responsibilities include:- Business Logic
- Authentication
- Authorization
- Data Validation
- Database Operations
- Sending Responses
- Amazon
- Flipkart
- Gmail
- Netflix
Exercise 1
List any four responsibilities of a backend application.Solution
Solution
Possible answers:
- Authentication
- Authorization
- Business Logic
- Database Operations
- Data Validation
- Sending Responses
Exercise 2
Which component is responsible for storing and retrieving data?Solution
Solution
Backend (through a Database)
Backend Returning HTML vs REST API
Backend applications are commonly developed in two different ways.Backend Returning HTML
The backend generates the complete user interface.- Django Templates
- Flask + Jinja
- PHP
- ASP.NET MVC
Backend Returning REST APIs
The backend returns only data, typically in JSON format. The frontend is responsible for rendering the user interface.Comparison
Why REST APIs?
A single backend can serve multiple clients.- Reusable
- Scalable
- Platform Independent
Exercise 1
Which backend approach is generally used for React applications?Solution
Solution
Backend Returning REST APIs
Exercise 2
Which backend approach is commonly used by traditional websites like WordPress?Solution
Solution
Backend Returning HTML
What is an API?
An Application Programming Interface (API) is a set of rules that allows two software applications to communicate. Examples:- React ↔ FastAPI
- Flutter ↔ FastAPI
- Python ↔ Weather API
- Python ↔ Payment Gateway
- Python ↔ OpenAI API
Exercise 1
Give two real-world examples where APIs are used.Solution
Solution
Examples:
- Google Maps API
- OpenAI API
- Weather API
- Payment Gateway API
Exercise 2
Who initiates an API request?Solution
Solution
The Client.
What is a REST API?
A REST API (Representational State Transfer API) is an API that follows REST principles and communicates using the HTTP protocol. Instead of exposing functions, REST APIs expose resources. Examples:Characteristics of REST APIs
- Stateless
- Resource-Oriented
- Client-Server Based
- Cacheable
- Uniform Interface
Exercise 1
Is the following a resource?Solution
Solution
Yes.It represents the Students resource.
Exercise 2
Write suitable endpoints for the following resources.- Employees
- Products
Solution
Solution
Why FastAPI for REST APIs?
FastAPI is highly regarded in the industry for building backend REST APIs. Three main features make it stand out:1. Async-First Architecture
FastAPI natively supports asynchronous programming (async/await).
- High Concurrency: When building REST APIs that depend on external I/O bound tasks, such as calling Large Language Models (LLMs) or database operations, async allows the server to handle other incoming requests without waiting for the LLM response to finish.
- GenAI Compatibility: This is particularly useful for AI systems where LLM calls are latency-heavy. The async-first model makes it highly efficient to stream LLM responses back to the client in real-time.
2. Built-in Pydantic Validation
FastAPI integrates Pydantic for data parsing and validation.- Input Validation: Enforces strict types on incoming payloads (JSON requests) before they enter your backend logic.
- Cost & Time Efficiency: By validating request parameters upfront, FastAPI instantly filters out malformed data (returning a
422 Unprocessable Entitystatus code). This prevents your application from forwarding invalid payloads to external LLM providers, saving both token costs and execution time.
3. Automatic Interactive Documentation
FastAPI automatically generates interactive API documentation based on the OpenAPI specification:- Instant Testing: Enables developers to immediately visualize and test API endpoints directly from the browser (via Swagger UI at
/docsor ReDoc at/redoc) without needing external client tools. - Always in Sync: Because the documentation is generated dynamically from your Python type hints and Pydantic schemas, the documentation is guaranteed to remain in sync with your actual backend code.
Quick Start
Let’s build our first FastAPI application.Step 1: Create a Project
Step 2: Install FastAPI
Step 3: Project Structure
Step 4: Create main.py
Step 5: Run the Application
Show Output
Show Output
Step 6: Open the Application
Show Output
Show Output
Step 7: Interactive API Documentation
FastAPI automatically generates interactive API documentation. Swagger UIExercise 1
Create a FastAPI application that returns:Solution
Solution
Exercise 2
Run the application and verify that the following pages are accessible.Solution
Solution
HTTP Fundamentals
REST APIs communicate using the HTTP (HyperText Transfer Protocol). HTTP defines how clients and servers exchange information through requests and responses.URL (Uniform Resource Locator)
A URL identifies the location of a resource on a server. Example:Endpoint
An Endpoint is a combination of an HTTP method and a URL path that performs a specific operation. Examples:URL vs Endpoint
HTTP Request
An HTTP Request is the complete message sent by a client. ExampleParts of an HTTP Request
HTTP Response
After processing the request, the server returns an HTTP Response. ExampleParts of an HTTP Response
HTTP Methods
REST APIs commonly use the following methods.
Example:
HTTP Status Codes
Every response contains a status code describing the result.Testing REST APIs
REST APIs can be tested using several tools.FastAPI Fundamentals
FastAPI is a modern, high-performance API framework. It is fundamentally different from traditional full-stack web frameworks like Django:- FastAPI (API-First): Focuses solely on building high-performance REST/GraphQL APIs that exchange clean, structured data (typically JSON).
- Django (Full-Stack): A server-rendered framework that manages administrative dashboards, views, and directly renders HTML pages to send to the browser.
Why API-First is Essential 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.
A FastAPI application begins by creating an instance of the
FastAPI class.
app object represents the entire web application.
Every API endpoint is registered with this object.
Creating Your First Route
Show Output
Show Output
Routing
A Route maps an incoming HTTP request to a Python function.- HTTP Method
- URL Path
- Python Function
HTTP Method Decorators
FastAPI provides decorators for common HTTP methods.Path Parameters
Path parameters allow values to be passed as part of the URL.Show Output
Show Output
Exercise 1
Create an endpoint that returns the given employee id. Sample URLSolution
Solution
Query Parameters
Query parameters are optional values appended to a URL.Show Output
Show Output
Exercise 2
Create a route that accepts a query parameter namedcourse.
Sample URL
Solution
Solution
Request Body
Data sent using POST, PUT and PATCH requests is called the Request Body. FastAPI uses Pydantic models to validate request data.Show Output
Show Output
Request Validation
FastAPI automatically validates incoming request data. If invalid data is provided,Show Output
Show Output
Exercise 1
Create aBook model with:
- title
- author
- price
Solution
Solution
Exercise 2
Send an invalid value forprice and observe the validation error.
Solution
Solution
Response Models
So far, our APIs have returned Python objects directly. FastAPI also allows us to define the structure of the response using response models. A response model ensures that the returned data:- Has the expected structure
- Contains the correct data types
- Automatically generates API documentation
Example
Show Output
Show Output
Returning Multiple Objects
Show Output
Show Output
Exercise 1
Create anEmployee model and return a single employee.
Solution
Solution
Exercise 2
Return a list of books usingresponse_model.
Solution
Solution
Basic Exception Handling
Sometimes a request cannot be processed successfully. Instead of returning invalid data, we should return an appropriate HTTP error. FastAPI provides theHTTPException class for this purpose.
Example
Show Output
Show Output
Common Exceptions
Exercise 1
Retrieve an employee by ID. Requirements:- Search for the employee in the given list.
- Return the employee if found.
- Raise a
404 Not Foundexception if the employee does not exist.
Solution
Solution
Exercise 2
Raise a400 exception if age is less than 18.
Solution
Solution
Request Validation
FastAPI automatically validates incoming request data using type annotations and Pydantic.Path Parameters
RequiredExercise
Create an endpoint to retrieve a product by its ID. Requirements:- Endpoint:
/products/{product_id} product_idmust be greater than0.
Solution
Solution
Query Parameters
RequiredExercise
Create an endpoint to list books. Requirements:- Accept an optional query parameter
page. - Default value should be
1.
Solution
Solution
Request Body
Exercise
Create aBook model with the following attributes.
titleprice
Solution
Solution
Model Attributes
RequiredExercise
Modify theBook model.
Requirements:
titleshould have a minimum length of3.priceshould be greater than0.
Solution
Solution
Default Values
A value is considered required if no default value is assigned. Assigning a value using= makes it optional.
Exercise
Create anEmployee model.
Requirements:
name→ requireddepartment→ default"IT"salary→ default25000
Solution
Solution
Exercise
Add optional contact details to theEmployee model.
Requirements:
emailphone
Solution
Solution
Common Validation Rules
Validation Errors
FastAPI automatically validates:- Path Parameters
- Query Parameters
- Request Body
- Model Attributes
- Data Types
Key Points
- Use
Path()for path parameters. - Use
Query()for query parameters. - Use
Body()for request bodies. - Use
Field()for model attributes. - Use
Annotatedto combine type hints with validation metadata. - A value is required if no default value is assigned.
- A value becomes optional when a default value (including
None) is assigned. - FastAPI automatically performs type conversion and request validation.
Mini Project - Student Management REST API
Let’s combine everything we’ve learned so far. We’ll build a simple Student Management API using an in-memory list.Features
- Get all students
- Get a student by ID
- Add a student
- Update a student
- Delete a student
Best Practices
- Use meaningful endpoint names.
- Follow REST naming conventions.
- Use Pydantic models for request and response data.
- Return appropriate HTTP status codes.
- Raise
HTTPExceptionfor invalid requests. - Keep route functions simple and focused.
- Test APIs using Swagger UI or Postman.
Practice
To reinforce what you’ve learned in this section, practice with the interactive follow-along notebook:Follow-Along Practice
Practice creating FastAPI instances, defining path/query parameters, handling request payloads with Pydantic BaseModel schemas, customizing responses, and raising HTTPExceptions.💻 VS Code | 🚀 Colab | 📥 Download
Summary
In this module, you learned how to build REST APIs using FastAPI.Key Concepts Covered
- Client and Server
- Backend Development
- APIs and REST APIs
- HTTP Fundamentals
- FastAPI Fundamentals
- Routing
- Path Parameters
- Query Parameters
- Request Body
- Request Validation
- Response Models
- Basic Exception Handling
- Building REST APIs
- Best Practices