DEV Community

DevCorner2
DevCorner2

Posted on

πŸ“˜ FastAPI In-Depth Documentation

Table of Contents

  1. Introduction to FastAPI
  2. Project Setup
  3. Folder Structure (Production Grade)
  4. Basic FastAPI Application
  5. Path Parameters, Query Parameters, and Request Bodies
  6. Pydantic Models for Data Validation
  7. CRUD with SQL Databases (MySQL/MariaDB)
  8. Dependency Injection
  9. Exception Handling
  10. Standardized Response Structure
  11. Authentication & Authorization
  12. Testing FastAPI Applications
  13. Running in Production
  14. Documentation & OpenAPI
  15. Conclusion

1. πŸ“Œ Introduction to FastAPI

FastAPI is a modern, high-performance, Python web framework for building APIs with:

  • Type hints
  • Automatic validation
  • Auto-generated Swagger UI
  • ASGI (async support)

2. βš™οΈ Project Setup

πŸ“¦ Install FastAPI and Uvicorn

pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode

For MySQL support:

pip install sqlalchemy pymysql alembic
Enter fullscreen mode Exit fullscreen mode

3. πŸ—‚ Folder Structure (Production Grade)

app/
β”œβ”€β”€ api/
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   └── user.py
β”‚   └── dependencies.py
β”œβ”€β”€ core/
β”‚   β”œβ”€β”€ config.py
β”‚   └── security.py
β”œβ”€β”€ db/
β”‚   β”œβ”€β”€ base.py
β”‚   β”œβ”€β”€ session.py
β”‚   └── models/
β”‚       └── user.py
β”‚   └── crud/
β”‚       └── user.py
β”œβ”€β”€ schemas/
β”‚   └── user.py
β”œβ”€β”€ services/
β”‚   └── user_service.py
β”œβ”€β”€ main.py
└── exceptions/
    └── handlers.py
Enter fullscreen mode Exit fullscreen mode

4. 🧱 Basic FastAPI Application

main.py:

from fastapi import FastAPI
from app.api.routes import user
from app.exceptions.handlers import add_exception_handlers

app = FastAPI(title="FastAPI CRUD App")

app.include_router(user.router, prefix="/api/v1/users")

add_exception_handlers(app)
Enter fullscreen mode Exit fullscreen mode

5. πŸ“₯ Handling Parameters

from fastapi import FastAPI, Query, Path

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

6. πŸ“ Pydantic Models

schemas/user.py

from pydantic import BaseModel, EmailStr

class UserCreate(BaseModel):
    name: str
    email: EmailStr
    password: str

class UserRead(BaseModel):
    id: int
    name: str
    email: EmailStr

    class Config:
        orm_mode = True
Enter fullscreen mode Exit fullscreen mode

7. πŸ—ƒοΈ CRUD with SQLAlchemy

db/session.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "mysql+pymysql://user:password@localhost/dbname"

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Enter fullscreen mode Exit fullscreen mode

db/models/user.py

from sqlalchemy import Column, Integer, String
from app.db.base import Base

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(50))
    email = Column(String(100), unique=True, index=True)
    password = Column(String(100))
Enter fullscreen mode Exit fullscreen mode

db/base.py

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
Enter fullscreen mode Exit fullscreen mode

db/crud/user.py

from sqlalchemy.orm import Session
from app.db.models.user import User
from app.schemas.user import UserCreate

def create_user(db: Session, user: UserCreate):
    db_user = User(**user.dict())
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

def get_users(db: Session, skip: int = 0, limit: int = 10):
    return db.query(User).offset(skip).limit(limit).all()
Enter fullscreen mode Exit fullscreen mode

8. 🧩 Dependency Injection

api/dependencies.py

from app.db.session import SessionLocal
from fastapi import Depends

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
Enter fullscreen mode Exit fullscreen mode

9. ❗ Exception Handling

exceptions/handlers.py

from fastapi import Request, FastAPI
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError

def add_exception_handlers(app: FastAPI):
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Request, exc: RequestValidationError):
        return JSONResponse(
            status_code=422,
            content={"detail": exc.errors(), "body": exc.body},
        )

    @app.exception_handler(Exception)
    async def general_exception_handler(request: Request, exc: Exception):
        return JSONResponse(
            status_code=500,
            content={"message": "Internal server error"},
        )
Enter fullscreen mode Exit fullscreen mode

10. πŸ“¦ Standardized Response Structure

Use a common response model:

from pydantic import BaseModel
from typing import Generic, TypeVar, Optional

T = TypeVar("T")

class ResponseModel(BaseModel, Generic[T]):
    success: bool
    message: str
    data: Optional[T] = None
Enter fullscreen mode Exit fullscreen mode

Use it in endpoints:

@app.post("/", response_model=ResponseModel[UserRead])
def create(user: UserCreate, db: Session = Depends(get_db)):
    new_user = crud.create_user(db, user)
    return ResponseModel(success=True, message="User created", data=new_user)
Enter fullscreen mode Exit fullscreen mode

11. πŸ” Authentication & Authorization

core/security.py:

from passlib.context import CryptContext
from jose import jwt

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"

def hash_password(password: str):
    return pwd_context.hash(password)

def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)

def create_access_token(data: dict):
    return jwt.encode(data, SECRET_KEY, algorithm=ALGORITHM)
Enter fullscreen mode Exit fullscreen mode

Use OAuth2PasswordBearer from fastapi.security.


12. πŸ§ͺ Testing FastAPI Applications

test_main.py:

from fastapi.testclient import TestClient
from app.main import app

client = TestClient(app)

def test_create_user():
    response = client.post("/api/v1/users", json={"name": "Test", "email": "test@example.com", "password": "123456"})
    assert response.status_code == 200
    assert response.json()["data"]["email"] == "test@example.com"
Enter fullscreen mode Exit fullscreen mode

13. πŸš€ Running in Production

Use Uvicorn with Gunicorn:

pip install gunicorn
gunicorn -w 4 -k uvicorn.workers.UvicornWorker app.main:app
Enter fullscreen mode Exit fullscreen mode

Use environment variables, .env, and tools like python-dotenv.


14. πŸ“ƒ Documentation & OpenAPI

FastAPI automatically generates:

  • /docs β€” Swagger UI
  • /redoc β€” ReDoc
  • /openapi.json β€” OpenAPI schema

Customize via:

FastAPI(
    title="My App",
    description="API for My Application",
    version="1.0.0",
    docs_url="/documentation",
    redoc_url=None
)
Enter fullscreen mode Exit fullscreen mode

15. βœ… Conclusion

FastAPI is a production-ready, robust, and efficient Python web framework that scales well with modern microservice-based and async-first architectures.

Key Advantages:

  • Automatic docs
  • Pydantic-based validation
  • Async support
  • Easy to test and scale
  • Secure and extensible

Top comments (0)