On this page
article
Getting Started with FastAPI
Install FastAPI, create your first API endpoint, and explore automatic interactive documentation with Swagger UI.
FastAPI is a modern, high-performance web framework for building APIs. It leverages Python type hints for automatic validation, serialization, and OpenAPI documentation.
Installation
pip install "fastapi[standard]" uvicorn
Your First API
# main.py
from fastapi import FastAPI
app = FastAPI(title="My API", version="1.0.0")
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
Run the server:
uvicorn main:app --reload
Visit:
- API:
http://127.0.0.1:8000/items/5?q=test - Auto docs:
http://127.0.0.1:8000/docs(Swagger UI) - ReDoc:
http://127.0.0.1:8000/redoc
Request Body with Pydantic
from pydantic import BaseModel, Field
class Item(BaseModel):
name: str = Field(min_length=1, max_length=100)
price: float = Field(gt=0)
tags: list[str] = []
@app.post("/items/", status_code=201)
def create_item(item: Item):
return {"name": item.name, "price": item.price, "tags": item.tags}
FastAPI automatically validates the request body and returns clear error messages for invalid input.
Path & Query Parameters
from typing import Annotated
from fastapi import Query, Path
@app.get("/users/{user_id}/posts")
def get_user_posts(
user_id: Annotated[int, Path(ge=1)],
skip: Annotated[int, Query(ge=0)] = 0,
limit: Annotated[int, Query(ge=1, le=100)] = 10,
):
return {"user_id": user_id, "skip": skip, "limit": limit}
Response Models
Control what data is returned:
class ItemResponse(BaseModel):
name: str
price: float
class ItemCreate(BaseModel):
name: str
price: float
internal_notes: str # not in response
@app.post("/items/", response_model=ItemResponse)
def create_item(item: ItemCreate):
return item # internal_notes excluded automatically
Project Structure
myapi/
├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── routers/
│ │ ├── items.py
│ │ └── users.py
│ ├── models/
│ │ └── schemas.py
│ └── dependencies.py
├── requirements.txt
└── Dockerfile
APIRouter — Modular Routes
# app/routers/items.py
from fastapi import APIRouter
router = APIRouter(prefix="/items", tags=["items"])
@router.get("/")
def list_items():
return [{"name": "Item 1"}, {"name": "Item 2"}]
@router.get("/{item_id}")
def get_item(item_id: int):
return {"item_id": item_id}
# app/main.py
from fastapi import FastAPI
from app.routers import items
app = FastAPI()
app.include_router(items.router)
FastAPI’s automatic docs and type-driven validation make API development faster and safer.
Next: Database Integration with SQLAlchemy.