Python - Building REST APIs using FastAPI

FastAPI is a modern Python web framework used for building APIs quickly and efficiently. It is designed to create high-performance web services with less code and automatic documentation support. FastAPI is built on top of Starlette for web handling and Pydantic for data validation. It is widely used in modern backend development because of its speed, simplicity, and support for asynchronous programming.

A REST API, or Representational State Transfer Application Programming Interface, allows different software applications to communicate with each other over the internet using HTTP methods such as GET, POST, PUT, and DELETE. FastAPI simplifies the process of building REST APIs by providing automatic request validation, clear routing systems, and interactive API documentation.

Features of FastAPI

High Performance

FastAPI is one of the fastest Python frameworks because it supports asynchronous programming using Python’s async and await keywords. It performs similarly to frameworks written in Node.js or Go.

Automatic API Documentation

FastAPI automatically generates interactive API documentation using Swagger UI and ReDoc. Developers can test API endpoints directly from the browser.

Data Validation

FastAPI uses Pydantic models to validate incoming request data automatically. Invalid data produces clear error messages.

Type Hint Support

FastAPI heavily uses Python type hints to improve readability and validation.

Easy Learning Curve

Developers familiar with Python can easily understand FastAPI because it follows clean and modern syntax.


Installing FastAPI

To use FastAPI, install it using pip.

pip install fastapi uvicorn
  • FastAPI is the main framework.

  • Uvicorn is the ASGI server used to run the application.


Creating a Simple FastAPI Application

Create a file named main.py.

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def home():
    return {"message": "Welcome to FastAPI"}

Run the application using:

uvicorn main:app --reload

Explanation:

  • main refers to the filename.

  • app refers to the FastAPI object.

  • --reload automatically reloads the server during development.

Open the browser and visit:

http://127.0.0.1:8000

Output:

{
    "message": "Welcome to FastAPI"
}

Understanding API Routes

Routes define URL paths for different operations.

Example:

@app.get("/students")
def get_students():
    return ["Rahul", "Anita", "John"]

The @app.get() decorator creates a GET endpoint.

Different HTTP methods include:

Method Purpose
GET Retrieve data
POST Create data
PUT Update data
DELETE Remove data

Path Parameters

Path parameters allow dynamic values in URLs.

Example:

@app.get("/student/{id}")
def get_student(id: int):
    return {"student_id": id}

Request:

/student/5

Response:

{
    "student_id": 5
}

FastAPI automatically converts the parameter into an integer because of type hints.


Query Parameters

Query parameters are optional values added to URLs.

Example:

@app.get("/search")
def search_student(name: str):
    return {"student_name": name}

Request:

/search?name=Rahul

Response:

{
    "student_name": "Rahul"
}

Using Pydantic Models

Pydantic models define the structure of request data.

Example:

from pydantic import BaseModel

class Student(BaseModel):
    name: str
    age: int
    course: str

Creating a POST API:

@app.post("/students")
def create_student(student: Student):
    return {
        "message": "Student created",
        "data": student
    }

Request Body:

{
    "name": "Rahul",
    "age": 21,
    "course": "Python"
}

FastAPI validates the data automatically.


Request Validation

If incorrect data is sent, FastAPI returns validation errors.

Example:

{
    "name": "Rahul",
    "age": "twenty"
}

Response:

{
    "detail": [
        {
            "msg": "value is not a valid integer"
        }
    ]
}

This helps developers prevent invalid data from entering the system.


Response Models

Response models control the structure of returned data.

Example:

@app.get("/student/{id}", response_model=Student)
def get_student(id: int):
    return {
        "name": "Rahul",
        "age": 20,
        "course": "FastAPI"
    }

This ensures consistent API responses.


HTTP Status Codes

FastAPI supports HTTP status codes for indicating request results.

Example:

from fastapi import status

@app.post("/students", status_code=status.HTTP_201_CREATED)
def create_student(student: Student):
    return student

Common status codes:

Code Meaning
200 Success
201 Created
400 Bad Request
404 Not Found
500 Internal Server Error

Automatic API Documentation

FastAPI automatically creates API documentation.

Swagger UI:

http://127.0.0.1:8000/docs

ReDoc:

http://127.0.0.1:8000/redoc

These pages allow developers to test APIs directly.


Asynchronous APIs

FastAPI supports asynchronous functions using async.

Example:

@app.get("/async-data")
async def get_data():
    return {"message": "Async response"}

Asynchronous programming improves performance when handling many users simultaneously.


Connecting FastAPI with Databases

FastAPI can work with databases such as:

  • MySQL

  • PostgreSQL

  • SQLite

  • MongoDB

Example using SQLite with SQLAlchemy:

from sqlalchemy import create_engine

engine = create_engine("sqlite:///students.db")

Database integration allows storing and retrieving persistent data.


CRUD Operations in FastAPI

CRUD stands for:

Operation Description
Create Add new data
Read Retrieve data
Update Modify data
Delete Remove data

Example:

@app.put("/students/{id}")
def update_student(id: int):
    return {"message": "Student updated"}
@app.delete("/students/{id}")
def delete_student(id: int):
    return {"message": "Student deleted"}

Dependency Injection

FastAPI supports dependency injection for reusable components.

Example:

from fastapi import Depends

def common_function():
    return "Common Data"

@app.get("/data")
def read_data(info: str = Depends(common_function)):
    return {"info": info}

This improves code organization and reusability.


Authentication in FastAPI

Authentication protects APIs from unauthorized access.

Common authentication methods include:

  • JWT Authentication

  • OAuth2

  • API Keys

Example:

from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

Authentication is important for secure applications.


Middleware in FastAPI

Middleware processes requests before reaching endpoints.

Example uses:

  • Logging

  • Authentication

  • CORS handling

  • Request monitoring

Example:

from fastapi.middleware.cors import CORSMiddleware

Advantages of FastAPI

  1. Fast execution speed

  2. Automatic validation

  3. Interactive documentation

  4. Simple syntax

  5. Asynchronous support

  6. Strong typing system

  7. Easy API development


Limitations of FastAPI

  1. Smaller ecosystem compared to Django

  2. Requires understanding of type hints

  3. Some advanced features may need additional libraries


Applications of FastAPI

FastAPI is used in:

  • Machine learning APIs

  • Microservices

  • Real-time applications

  • Backend systems

  • Data science platforms

  • Cloud-based services

Companies and developers prefer FastAPI because it combines speed, simplicity, and modern Python development practices.


Conclusion

FastAPI is a powerful framework for building REST APIs in Python. It simplifies API development through automatic validation, asynchronous support, and built-in documentation. Developers can create scalable and high-performance backend systems with minimal code. Because of its modern architecture and ease of use, FastAPI has become one of the most popular frameworks for Python web API development.