PYTHON APPLIEDChapter 12 · Python for Web Development
FastAPI and REST APIs
FastAPI is a modern Python framework built on type hints. It generates interactive API documentation automatically, validates request data using Pydantic models, and supports async handlers natively.
Worked example
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Star(BaseModel):
name: str
magnitude: float
@app.get("/api/stars")
async def list_stars():
return [
{"name": "Vega", "magnitude": 0.03},
{"name": "Sirius", "magnitude": -1.46},
]
@app.post("/api/stars")
async def create_star(star: Star):
return {"created": star.name}How it reads
- @app.get and @app.post map HTTP methods to handler functions
- BaseModel validates incoming JSON against the type hints automatically
- async def lets FastAPI handle concurrent requests efficiently

Cloud tip: Visit /docs on a running FastAPI server to see auto-generated Swagger UI documentation for every endpoint.


