অধ্যায় ১০ / ১৮Backend & data

Python ও FastAPI

Python দিয়ে দ্রুত, typed আর async API বানাও।

FastAPI হলো Python এর আধুনিক async web framework। Type hint থেকেই validation, serialization আর OpenAPI docs (/docs) নিজে থেকে তৈরি হয়। AI/ML product এর backend এ এটা এখন প্রথম পছন্দ, কারণ model আর data লাইব্রেরি সব Python এ।

Python এর যা জানতে হবে

  • Type hints, dataclass, list/dict comprehension, generator (yield), decorator, context manager (with)।
  • async/await আর asyncio event loop; blocking call (time.sleep, requests) async function এ দিলে পুরো server আটকে যায়।
  • GIL: একসাথে একটা thread Python bytecode চালায়। I/O-bound কাজে async/thread, CPU-bound কাজে multiprocessing।
  • Package manager: uv (খুব দ্রুত) বা Poetry; প্রতিটা project এ আলাদা virtual environment। Lint/format এর জন্য Ruff, type check এর জন্য mypy/pyright।

FastAPI এর মূল অংশ

python
from fastapi import FastAPI, Depends, HTTPException, status
from pydantic import BaseModel, EmailStr, Field

app = FastAPI()

class UserCreate(BaseModel):
    email: EmailStr
    password: str = Field(min_length=8)

class UserOut(BaseModel):
    id: int
    email: EmailStr
    model_config = {"from_attributes": True}   # ORM object থেকে পড়া

@app.post("/users", response_model=UserOut, status_code=status.HTTP_201_CREATED)
async def create_user(body: UserCreate, db: AsyncSession = Depends(get_db)):
    if await users_repo.get_by_email(db, body.email):
        raise HTTPException(409, "Email already registered")
    return await users_repo.create(db, body)
  • Pydantic v2: request body validate করে, response_model output filter করে (password কখনো response এ যাবে না)।
  • Dependency Injection (Depends): DB session, current user, pagination, permission check সব dependency হিসেবে লেখা হয়, আর test এ app.dependency_overrides দিয়ে বদলানো যায়।
  • yield dependency: আগে resource খোলো, পরে বন্ধ করো (DB session)।
  • async def বনাম def: async library (asyncpg, httpx) হলে async def; blocking library হলে def লেখো, FastAPI সেটা threadpool এ চালাবে।
  • APIRouter দিয়ে feature অনুযায়ী route ভাগ করো; startup/shutdown এর জন্য lifespan।

Database আর Auth

  • SQLAlchemy 2.0 (async) অথবা SQLModel; migration এর জন্য Alembic।
  • Auth: OAuth2 password flow + JWT (OAuth2PasswordBearer), password hash এর জন্য Argon2 বা bcrypt।
python
async def get_current_user(token: str = Depends(oauth2_scheme), db=Depends(get_db)) -> User:
    payload = decode_jwt(token)            # invalid হলে 401
    user = await db.get(User, payload["sub"])
    if not user:
        raise HTTPException(401, "Invalid token")
    return user

Production

  • Server: Uvicorn (বা Gunicorn + Uvicorn worker), প্রতি CPU core এ একটা worker দিয়ে শুরু।
  • Background: ছোট কাজে BackgroundTasks; ভারী কাজে Celery, Dramatiq বা ARQ।
  • Settings: pydantic-settings দিয়ে env পড়ো। Test: pytest + httpx.AsyncClient।
  • AI feature: LLM response stream করতে StreamingResponse বা SSE।

Django না FastAPI?

Django "batteries included": admin panel, ORM, auth সব তৈরি, content-heavy app এ দ্রুত। FastAPI হালকা, async, API-first, AI/microservice এ ভালো। Flask এখন পুরনো codebase এ বেশি দেখা যায়।

Interview প্রশ্ন

  • FastAPI কেন দ্রুত? (Starlette + async + Pydantic এর Rust core)
  • Depends কীভাবে কাজ করে? Test এ dependency কীভাবে override করবে?
  • async def endpoint এ blocking code লিখলে কী হয়?
  • GIL কী? CPU-bound কাজ কীভাবে সামলাবে?
  • response_model কেন দরকারি?

এই অধ্যায় পড়া শেষ?

পড়া শেষ চিহ্নিত করো, নিজের অগ্রগতি ধরে রাখো।