⚡ FastAPI Endpoints
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+.
Mastering this concept will significantly boost your Python data science skills!
💻 Code Example:
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from pydantic import BaseModel, EmailStr, field_validator from typing import Optional from datetime import datetime app = FastAPI( title="Pynfinity API", description="Learning platform API by santoshtvk", version="1.0.0", ) # ── Security ───────────────────────────────────────────────── bearer = HTTPBearer() VALID_TOKENS = {"pynfinity_secret_token_tvk"} def verify_token(creds: HTTPAuthorizationCredentials = Depends(bearer)): if creds.credentials not in VALID_TOKENS: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") return creds.credentials # ── Models ─────────────────────────────────────────────────── class UserCreate(BaseModel): username : str email : str course : str = "Python" score : Optional[float] = None @field_validator("username") @classmethod def name_too_short(cls, v): if len(v) < 3: raise ValueError("username must be at least 3 characters") return v.lower() class UserResponse(BaseModel): id : int username : str email : str course : str score : Optional[float] joined_at: datetime # ── In-memory store ─────────────────────────────────────────── db: list[UserResponse] = [] counter = 0 # ── Routes ─────────────────────────────────────────────────── @app.get("/", tags=["Root"]) def root(): return {"platform": "pynfinity", "author": "santoshtvk", "status": "running"} @app.post("/users", response_model=UserResponse, status_code=201, tags=["Users"]) def create_user(payload: UserCreate, token: str = Depends(verify_token)): global counter counter += 1 user = UserResponse(id=counter, joined_at=datetime.utcnow(), **payload.model_dump()) db.append(user) return user @app.get("/users", response_model=list[UserResponse], tags=["Users"]) def list_users(course: Optional[str] = None): return [u for u in db if (course is None or u.course == course)] @app.get("/users/{user_id}", response_model=UserResponse, tags=["Users"]) def get_user(user_id: int): for u in db: if u.id == user_id: return u raise HTTPException(status_code=404, detail=f"User {user_id} not found") # Run: uvicorn main:app --reload # Docs: http://localhost:8000/docs
Keep exploring and happy coding! 💻