
FastAPI
Designing scalable endpoint structures requires careful consideration of organization, versioning, and consistency.
from fastapi import FastAPI
app = FastAPI()
# Collection endpoints
@app.get("/organizations") # List all
@app.post("/organizations") # Create new
# Resource endpoints
@app.get("/organizations/{org_id}") # Get specific
@app.put("/organizations/{org_id}") # Replace
@app.patch("/organizations/{org_id}") # Update
@app.delete("/organizations/{org_id}") # Delete
# Nested resources
@app.get("/organizations/{org_id}/teams") # List org's teams
@app.get("/organizations/{org_id}/teams/{team_id}") # Get team
# Collection shortcuts
@app.get("/teams/{team_id}") # Direct access if team_id is unique# v1 - Simple
@app.get("/api/v1/users")
async def list_users_v1():
return {"users": []}
# v2 - Enhanced
@app.get("/api/v2/users")
async def list_users_v2(include_metadata: bool = False):
users = []
if include_metadata:
return {"users": users, "total": 0}
return {"users": users}# For non-CRUD operations
@app.post("/search") # Search action
@app.post("/upload") # Upload action
@app.post("/validate") # Validation action
@app.post("/export") # Export actionfrom typing import List
# Consistent parameter naming
@app.get("/items")
async def list_items(
skip: int = 0, # Pagination
limit: int = 10,
sort_by: str = "created" # Sorting
):
return {"items": []}
# Consistent response structure
@app.get("/items/{item_id}")
async def get_item(item_id: int):
return {
"data": {"id": item_id}, # Consistent wrapper
"status": "success"
}from fastapi import APIRouter
# Organize large APIs with routers
router = APIRouter(prefix="/api/v1", tags=["users"])
@router.get("/users")
async def list_users():
return {"users": []}
@router.post("/users")
async def create_user(user: dict):
return user
app = FastAPI()
app.include_router(router) # Include in main app@app.get(
"/items/{item_id}",
summary="Get Item Details",
description="Retrieve detailed information about a specific item",
tags=["items"],
status_code=200
)
async def get_item(item_id: int):
'''Get a single item by ID.'''
return {"id": item_id}from fastapi import HTTPException, status
@app.get("/expensive-operation")
async def expensive_operation():
'''Long-running operations should be background tasks'''
# For quick operations: return directly
result = compute_something()
return result
@app.post("/heavy-task")
async def heavy_task(background_tasks):
'''Use background tasks for long operations'''
from fastapi import BackgroundTasks
background_tasks.add_task(long_running_task)
return {"status": "processing"}Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward