DEV Community

Karthikeyan
Karthikeyan

Posted on

FastAPI in Python: The Modern Way to Build APIs

FastAPI in Python: The Modern Way to Build APIs

Introduction

FastAPI is a modern, high-performance web framework for building APIs with Python. It is built on top of standard Python type hints and offers automatic data validation, serialization, and interactive API documentation out of the box.

Since its release, FastAPI has rapidly grown in popularity among Python developers for its speed, simplicity, and developer-friendly features. Whether you are building a microservice, a REST API, or the backend for a web application, FastAPI is an excellent choice.


Why FastAPI?

1. Blazing Fast Performance

FastAPI is one of the fastest Python frameworks available, on par with NodeJS and Go. It is built on ASGI (Asynchronous Server Gateway Interface) using Starlette under the hood.

2. Automatic Documentation

FastAPI auto-generates interactive API docs using:

3. Type Safety & Validation

It leverages Python type hints and Pydantic models to automatically validate request data and provide clear error messages.

4. Easy to Learn

FastAPI's syntax is clean, intuitive, and similar to Flask, making it easy for beginners and experienced devs alike.

5. Async Support

Full support for async/await, making it ideal for I/O-heavy applications.


Installation

Install FastAPI and Uvicorn (ASGI server) using pip:

pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode

Your First FastAPI App

Create a file called main.py and add the following:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI!"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "query": q}
Enter fullscreen mode Exit fullscreen mode

Run the server with:

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:8000 in your browser to see it live!


Using Pydantic Models for Request Body

FastAPI uses Pydantic to define request/response schemas:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    is_available: bool = True

@app.post("/items/")
def create_item(item: Item):
    return {"item_name": item.name, "price": item.price}
Enter fullscreen mode Exit fullscreen mode

FastAPI automatically:

  • Validates the incoming JSON body
  • Returns a 422 error if data is invalid
  • Generates schema in the API docs

Path Parameters & Query Parameters

Path Parameter (part of the URL):

@app.get("/users/{user_id}")
def get_user(user_id: int):
    return {"user_id": user_id}
Enter fullscreen mode Exit fullscreen mode

Query Parameter (optional URL param):

@app.get("/search/")
def search(q: str, limit: int = 10):
    return {"query": q, "limit": limit}
Enter fullscreen mode Exit fullscreen mode

URL: /search/?q=python&limit=5


Async Endpoints

FastAPI supports async functions natively:

import asyncio
from fastapi import FastAPI

app = FastAPI()

@app.get("/async-data/")
async def get_data():
    await asyncio.sleep(1)  # Simulate async I/O
    return {"data": "Loaded asynchronously!"}
Enter fullscreen mode Exit fullscreen mode

Dependency Injection

FastAPI has a powerful dependency injection system:

from fastapi import FastAPI, Depends

app = FastAPI()

def get_current_user():
    return {"username": "john_doe"}

@app.get("/profile/")
def profile(user: dict = Depends(get_current_user)):
    return {"user": user}
Enter fullscreen mode Exit fullscreen mode

This is useful for:

  • Authentication & Authorization
  • Database sessions
  • Shared logic across routes

Handling Errors

Use HTTPException to return HTTP errors:

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get("/items/{item_id}")
def get_item(item_id: int):
    if item_id != 1:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item_id": item_id}
Enter fullscreen mode Exit fullscreen mode

Routers — Organizing Large Apps

Split your app into multiple files using APIRouter:

# routers/users.py
from fastapi import APIRouter

router = APIRouter()

@router.get("/users/")
def get_users():
    return [{"name": "Alice"}, {"name": "Bob"}]
Enter fullscreen mode Exit fullscreen mode
# main.py
from fastapi import FastAPI
from routers import users

app = FastAPI()
app.include_router(users.router)
Enter fullscreen mode Exit fullscreen mode

Middleware

Add middleware to process requests/responses globally:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)
Enter fullscreen mode Exit fullscreen mode

FastAPI vs Flask vs Django REST

Feature FastAPI Flask Django REST
Performance Very High Medium Medium
Auto Docs ✅ YES ❌ NO Partial
Async Support ✅ YES Partial ✅ YES
Type Validation ✅ Pydantic ❌ NO Serializers
Learning Curve Low Low Medium-High
Best For APIs, ML Small apps Full-stack

Real-World Use Cases

FastAPI is widely used in:

  • 🤖 Machine Learning model serving (ML APIs)
  • 🔧 Microservices architecture
  • ⚡ Real-time applications using WebSockets
  • 📱 Backend APIs for mobile and web apps
  • 🔄 Data pipelines and ETL services

Conclusion

FastAPI is a game-changer for Python API development. Its combination of speed, automatic documentation, type safety, and ease of use makes it the go-to framework for modern Python backends.

Whether you are a beginner or a seasoned developer, FastAPI enables you to build robust, production-ready APIs with less code and fewer bugs.

Start building with FastAPI today — your future self will thank you!


Useful Links

Top comments (0)