Type hints are at the core of FastAPI. They provide data validation, serialization, and automatic documentation.
# Python type hints
name: str = "FastAPI"
count: int = 42
price: float = 19.99
is_active: bool = True
# Function signatures
def greet(name: str) -> str:
return f"Hello {name}"
from typing import Optional, Union, List, Dict
# Optional (can be None)
def get_item(item_id: int, q: Optional[str] = None):
...
# Union (multiple possible types)
def process(value: Union[int, str]) -> str:
return str(value)
from typing import List, Dict, Set, Tuple
items: List[int] = [1, 2, 3]
metadata: Dict[str, str] = {"key": "value"}
unique: Set[int] = {1, 2, 3}
pair: Tuple[int, str] = (1, "one")
# FastAPI uses these for query params
@app.get("/items/")
def list_items(ids: List[int] = None):
return {"ids": ids}