Skip to main content

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:
  1. Client and Server
  2. Backend Development
  3. APIs and REST APIs
  4. Quick Start
  5. HTTP Fundamentals
  6. FastAPI Fundamentals
  7. Routing and Request Handling
  8. Request Validation
  9. Response Models
  10. Exception Handling
  11. Building REST APIs
  12. Best Practices
Try Yourself: 💻 VS Code | 🚀 Colab | 📥 Download
Verify Solutions: 💻 VS Code | 🚀 Colab | 📥 Download
By the end of this module, you’ll understand how web applications communicate and build your own REST APIs using FastAPI.

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.

Exercise 2

Give any three examples of client applications.
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
A typical web application looks like this.
Examples of backend-powered applications:
  • Amazon
  • Flipkart
  • Gmail
  • Instagram
  • Netflix
  • WhatsApp

Exercise 1

List any four responsibilities of a backend application.
Possible answers:
  • Authentication
  • Authorization
  • Business Logic
  • Database Operations
  • Data Validation
  • Sending Responses

Exercise 2

Which component is responsible for storing and retrieving data?
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.
Examples:
  • 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.
This makes applications:
  • Reusable
  • Scalable
  • Platform Independent

Exercise 1

Which backend approach is generally used for React applications?
Backend Returning REST APIs

Exercise 2

Which backend approach is commonly used by traditional websites like WordPress?
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
Applications exchange information through requests and responses.

Exercise 1

Give two real-world examples where APIs are used.
Examples:
  • Google Maps API
  • OpenAI API
  • Weather API
  • Payment Gateway API

Exercise 2

Who initiates an API request?
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:
Clients perform different operations using HTTP methods.

Characteristics of REST APIs

  • Stateless
  • Resource-Oriented
  • Client-Server Based
  • Cacheable
  • Uniform Interface

Exercise 1

Is the following a resource?
Yes.It represents the Students resource.

Exercise 2

Write suitable endpoints for the following resources.
  • Employees
  • Products

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 Entity status 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 /docs or 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

Output ?

Step 6: Open the Application

Output ?

Step 7: Interactive API Documentation

FastAPI automatically generates interactive API documentation. Swagger UI
ReDoc

Exercise 1

Create a FastAPI application that returns:

Exercise 2

Run the application and verify that the following pages are accessible.
Then open the URLs in your browser.

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:
A URL consists of several parts.

Endpoint

An Endpoint is a combination of an HTTP method and a URL path that performs a specific operation. Examples:
In FastAPI,
creates the endpoint

URL vs Endpoint

HTTP Request

An HTTP Request is the complete message sent by a client. Example

Parts of an HTTP Request

HTTP Response

After processing the request, the server returns an HTTP Response. Example

Parts 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:
  1. 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.
  2. 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.
The app object represents the entire web application. Every API endpoint is registered with this object.

Creating Your First Route

Open
Output ?

Routing

A Route maps an incoming HTTP request to a Python function.
Every route consists of:
  • 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.
Open
Output ?

Exercise 1

Create an endpoint that returns the given employee id. Sample URL
Expected Output

Query Parameters

Query parameters are optional values appended to a URL.
Open
Output ?

Exercise 2

Create a route that accepts a query parameter named course. Sample URL
Expected Output

Request Body

Data sent using POST, PUT and PATCH requests is called the Request Body. FastAPI uses Pydantic models to validate request data.
Request Body
Output ?

Request Validation

FastAPI automatically validates incoming request data. If invalid data is provided,
FastAPI returns Output ?
No additional validation code is required because FastAPI uses Pydantic internally.

Exercise 1

Create a Book model with:
  • title
  • author
  • price
Create a POST endpoint that returns the received data.

Exercise 2

Send an invalid value for price and observe the validation error.
FastAPI automatically returns a 422 Validation Error.

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

Output ?

Returning Multiple Objects

Output ?

Exercise 1

Create an Employee model and return a single employee.

Exercise 2

Return a list of books using response_model.

Basic Exception Handling

Sometimes a request cannot be processed successfully. Instead of returning invalid data, we should return an appropriate HTTP error. FastAPI provides the HTTPException class for this purpose.

Example

Request
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 Found exception if the employee does not exist.

Exercise 2

Raise a 400 exception if age is less than 18.

Request Validation

FastAPI automatically validates incoming request data using type annotations and Pydantic.

Path Parameters

Required
With Validation

Exercise

Create an endpoint to retrieve a product by its ID. Requirements:
  • Endpoint: /products/{product_id}
  • product_id must be greater than 0.

Query Parameters

Required
Optional with Default
With Validation

Exercise

Create an endpoint to list books. Requirements:
  • Accept an optional query parameter page.
  • Default value should be 1.
Example

Request Body

Exercise

Create a Book model with the following attributes.
  • title
  • price
Create a POST endpoint that returns the received object.

Model Attributes

Required
Required with Validation
Optional with Default
Optional Nullable

Exercise

Modify the Book model. Requirements:
  • title should have a minimum length of 3.
  • price should be greater than 0.

Default Values

A value is considered required if no default value is assigned. Assigning a value using = makes it optional.

Exercise

Create an Employee model. Requirements:
  • name → required
  • department → default "IT"
  • salary → default 25000

Exercise

Add optional contact details to the Employee model. Requirements:
  • email
  • phone
Both should be optional.

Common Validation Rules

Validation Errors

FastAPI automatically validates:
  • Path Parameters
  • Query Parameters
  • Request Body
  • Model Attributes
  • Data Types
If validation fails, FastAPI automatically returns:

Key Points

  • Use Path() for path parameters.
  • Use Query() for query parameters.
  • Use Body() for request bodies.
  • Use Field() for model attributes.
  • Use Annotated to 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
The data will be stored in a Python list.
In the next module, we’ll replace this list with a database using SQLAlchemy ORM.

Best Practices

  • Use meaningful endpoint names.
  • Follow REST naming conventions.
  • Use Pydantic models for request and response data.
  • Return appropriate HTTP status codes.
  • Raise HTTPException for 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
You now have a solid understanding of FastAPI fundamentals. In the next module, you’ll learn how to organize larger applications using APIRouter, integrate a database with SQLAlchemy ORM, apply Dependency Injection, and build a modular FastAPI application.