Python - Building REST APIs with FastAPI
Introduction
FastAPI is a modern, high-performance Python framework used for building Application Programming Interfaces (APIs). It is designed to create web services quickly and efficiently while maintaining clean, readable code. FastAPI is based on standard Python type hints and provides automatic validation, serialization, and interactive API documentation.
FastAPI has become popular because it offers excellent performance, comparable to frameworks built with languages such as Node.js and Go, while retaining Python's simplicity.
What is a REST API?
A REST (Representational State Transfer) API is a set of rules that allows different software applications to communicate over the internet. REST APIs use HTTP methods to perform operations on resources.
Common HTTP methods include:
-
GET – Retrieve data
-
POST – Create new data
-
PUT – Update existing data
-
DELETE – Remove data
-
PATCH – Partially update data
For example, in a student management system:
-
GET /students → Retrieve all students
-
GET /students/1 → Retrieve a specific student
-
POST /students → Add a new student
-
PUT /students/1 → Update student information
-
DELETE /students/1 → Delete a student
Why Use FastAPI?
High Performance
FastAPI is built on Starlette and Pydantic, allowing it to process requests efficiently. It is one of the fastest Python web frameworks available.
Automatic Data Validation
FastAPI validates incoming data automatically using Python type annotations.
Example:
from pydantic import BaseModel
class Student(BaseModel):
name: str
age: int
If a user sends an incorrect data type, FastAPI automatically returns an error message.
Automatic Documentation
FastAPI automatically generates API documentation using Swagger UI and ReDoc.
When the application runs:
http://localhost:8000/docs
provides an interactive interface to test APIs.
Easy to Learn
Developers familiar with Python can quickly understand FastAPI because it follows Python standards and syntax.
Installing FastAPI
Install FastAPI and the Uvicorn server:
pip install fastapi uvicorn
Verify installation:
pip show fastapi
Creating Your First FastAPI Application
Create a file named:
main.py
Write the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def home():
return {"message": "Welcome to FastAPI"}
Run the application:
uvicorn main:app --reload
Open:
http://127.0.0.1:8000
Output:
{
"message": "Welcome to FastAPI"
}
Creating Multiple Endpoints
Example:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def home():
return {"message": "Home Page"}
@app.get("/about")
def about():
return {"message": "About Page"}
@app.get("/contact")
def contact():
return {"message": "Contact Page"}
Each endpoint represents a different route.
Working with Path Parameters
Path parameters allow dynamic values in URLs.
Example:
@app.get("/students/{student_id}")
def get_student(student_id: int):
return {"student_id": student_id}
Request:
/students/5
Response:
{
"student_id": 5
}
FastAPI automatically converts the parameter to an integer.
Query Parameters
Query parameters provide additional filtering information.
Example:
@app.get("/search")
def search(name: str):
return {"name": name}
Request:
/search?name=John
Response:
{
"name": "John"
}
Multiple parameters:
@app.get("/products")
def products(category: str, limit: int):
return {
"category": category,
"limit": limit
}
Request Body Using Pydantic Models
When creating data, information is usually sent in JSON format.
Example:
from pydantic import BaseModel
class Student(BaseModel):
name: str
age: int
course: str
Create a POST endpoint:
@app.post("/students")
def create_student(student: Student):
return student
Request:
{
"name": "John",
"age": 20,
"course": "Python"
}
Response:
{
"name": "John",
"age": 20,
"course": "Python"
}
CRUD Operations
CRUD stands for:
-
Create
-
Read
-
Update
-
Delete
Create
@app.post("/students")
def create_student(student: Student):
return {"message": "Student created"}
Read
@app.get("/students/{id}")
def get_student(id: int):
return {"id": id}
Update
@app.put("/students/{id}")
def update_student(id: int, student: Student):
return {
"id": id,
"student": student
}
Delete
@app.delete("/students/{id}")
def delete_student(id: int):
return {"message": "Student deleted"}
These operations form the foundation of most REST APIs.
Response Models
Response models define the structure of returned data.
Example:
class StudentResponse(BaseModel):
name: str
age: int
@app.get("/student", response_model=StudentResponse)
def get_student():
return {
"name": "John",
"age": 20,
"password": "secret"
}
Output:
{
"name": "John",
"age": 20
}
The password field is automatically excluded.
Error Handling
FastAPI provides built-in exception handling.
Example:
from fastapi import HTTPException
@app.get("/students/{id}")
def get_student(id: int):
if id != 1:
raise HTTPException(
status_code=404,
detail="Student not found"
)
return {"id": id}
Response:
{
"detail": "Student not found"
}
Dependency Injection
Dependency Injection allows reusable functionality.
Example:
from fastapi import Depends
def verify_user():
return "Authorized"
@app.get("/dashboard")
def dashboard(user=Depends(verify_user)):
return {"status": user}
This technique is commonly used for authentication and database connections.
Database Integration
FastAPI can work with databases such as:
-
MySQL
-
PostgreSQL
-
SQLite
-
MongoDB
Example using SQLAlchemy:
from sqlalchemy import create_engine
engine = create_engine(
"sqlite:///students.db"
)
The API can store, retrieve, update, and delete records from databases.
Authentication and Security
FastAPI supports various authentication mechanisms:
API Key Authentication
X-API-Key
JWT Authentication
JSON Web Tokens are widely used for secure login systems.
Workflow:
-
User enters credentials.
-
Server verifies credentials.
-
Server generates JWT token.
-
User sends token with requests.
-
Server validates token.
This prevents unauthorized access.
Middleware
Middleware executes before and after requests.
Example uses:
-
Logging
-
Authentication
-
Request monitoring
-
Security checks
Example:
@app.middleware("http")
async def log_requests(request, call_next):
response = await call_next(request)
return response
Background Tasks
FastAPI supports tasks that run after sending responses.
Example:
from fastapi import BackgroundTasks
def send_email():
print("Email sent")
@app.post("/register")
def register(background_tasks: BackgroundTasks):
background_tasks.add_task(send_email)
return {"message": "User registered"}
The user receives a response immediately while the email task runs in the background.
Testing FastAPI Applications
FastAPI includes testing support.
Example:
from fastapi.testclient import TestClient
client = TestClient(app)
def test_home():
response = client.get("/")
assert response.status_code == 200
Testing ensures APIs behave correctly before deployment.
Deployment
FastAPI applications can be deployed using:
-
Uvicorn
-
Gunicorn
-
Docker
-
Nginx
-
Kubernetes
-
Cloud platforms such as AWS, Azure, and Google Cloud
Example:
uvicorn main:app --host 0.0.0.0 --port 8000
This makes the application accessible to external users.
Advantages of FastAPI
-
Very fast execution speed
-
Automatic API documentation
-
Built-in data validation
-
Easy integration with databases
-
Supports asynchronous programming
-
Strong security features
-
Clean and maintainable code
-
Excellent support for modern Python features
Real-World Applications
FastAPI is commonly used for:
-
E-commerce platforms
-
Banking applications
-
Mobile application backends
-
Machine learning model APIs
-
Healthcare systems
-
Student management systems
-
Inventory management systems
-
Real-time analytics services
-
Cloud-based applications
Conclusion
FastAPI is one of the most powerful frameworks for building REST APIs in Python. It combines high performance, automatic validation, security, and ease of development into a single framework. By understanding routing, request handling, CRUD operations, authentication, database integration, and deployment, developers can create scalable and production-ready APIs that serve web applications, mobile apps, and enterprise systems efficiently.