Wednesday, 22 October 2025

#16 FAST API

FastAPI Masterclass: 10 Modules

FastAPI Masterclass: Build & Deploy APIs in 10 Modules

This comprehensive guide introduces you to FastAPI, the modern Python framework for building high-performance APIs and web apps. Each module builds on the next, taking you from setup to deployment.

Module 1: Introduction to FastAPI

FastAPI is a high-performance web framework built for speed with async support. Install it and run your first app.

pip install fastapi uvicorn
# app.py
from fastapi import FastAPI

app = FastAPI()

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

# Run with: uvicorn app:app --reload

Module 2: Path and Query Parameters

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

Module 3: Request Body with Pydantic

from pydantic import BaseModel

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

@app.post("/items/")
def create_item(item: Item):
    return {"item": item}

Module 4: Handling Responses

Customize your JSON responses and status codes.

from fastapi.responses import JSONResponse

@app.get("/custom")
def custom_response():
    return JSONResponse(content={"status": "success"}, status_code=201)

Module 5: Error Handling

from fastapi import HTTPException

@app.get("/divide")
def divide(a: int, b: int):
    if b == 0:
        raise HTTPException(status_code=400, detail="Division by zero not allowed")
    return {"result": a / b}

Module 6: Background Tasks

from fastapi import BackgroundTasks

def write_log(message: str):
    with open("log.txt", "a") as f:
        f.write(f"{message}\n")

@app.post("/log/")
def log_message(background_tasks: BackgroundTasks, message: str):
    background_tasks.add_task(write_log, message)
    return {"status": "Task scheduled"}

Module 7: Working with Databases (SQLite + SQLAlchemy)

pip install sqlalchemy
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)

Base.metadata.create_all(bind=engine)

Module 8: Authentication with FastAPI

from fastapi.security import OAuth2PasswordBearer
from fastapi import Depends

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/users/me")
def read_current_user(token: str = Depends(oauth2_scheme)):
    return {"token": token}

Module 9: Building a RESTful API

users = []

@app.post("/users/")
def create_user(name: str):
    user = {"id": len(users) + 1, "name": name}
    users.append(user)
    return user

@app.get("/users/")
def get_users():
    return users

Module 10: Deploying FastAPI (Using Uvicorn + Git)

  1. Create a requirements.txt file:
    pip freeze > requirements.txt
    
  2. Create a Procfile for Heroku/Render:
    web: uvicorn app:app --host=0.0.0.0 --port=$PORT
    
  3. Push to GitHub and Deploy via Render or Heroku Dashboard.
FastAPI automatically generates interactive API docs at /docs and /redoc!

No comments:

Post a Comment

#20b Python (run+edit in browser ^ all in one)

๐Ÿ Python Basics — 5 Interactive Modules Edit code live with syntax highlighting and click ▶ Run . Each module runs separately ...