Skip to content

FastAPI & Pydantic

πŸš€ FastAPI & Pydantic: Modern Web APIs

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.


🟒 Level 1: Foundations

1. Pydantic Models (Data Validation)

FastAPI uses Pydantic to validate request and response data.

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None

2. Path & Query Parameters

from fastapi import FastAPI

app = FastAPI()

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

🟑 Level 2: Dependency Injection

FastAPI has a powerful Dependency Injection system for shared logic like Auth or Database sessions.

from fastapi import Depends

def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons

πŸ”΄ Level 3: Advanced Patterns

3. Async Database with SQLModel

Using async def and await with an asynchronous database driver.

4. Background Tasks

Run long-running processes after returning a response.

from fastapi import BackgroundTasks

def write_log(message: str):
    with open("log.txt", mode="a") as log:
        log.write(message)

@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_log, f"notification sent to {email}")
    return {"message": "Notification sent in the background"}