FastAPI is a modern Python framework for building APIs quickly, using standard Python type hints to validate data and auto-generate interactive documentation.

Why FastAPI?

FastAPI combines Python type hints with async support, giving you request validation, serialization and interactive docs with almost no boilerplate.

Installing FastAPI

bash
pip install fastapi uvicorn

Request Models with Pydantic

Pydantic models describe the shape of incoming and outgoing data. FastAPI uses them to validate requests automatically.

python
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    in_stock: bool = True

Building Endpoints

python
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

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

Type hints aren't just for readability here — FastAPI uses them at runtime to validate incoming JSON and reject malformed requests automatically.

Automatic Docs

Run the app with Uvicorn and visit /docs for an interactive Swagger UI generated directly from your code:

bash
uvicorn main:app --reload
PythonFastAPIAPIBeginner