← Back to Tutorials

6. Type Hints

Type hints are at the core of FastAPI. They provide data validation, serialization, and automatic documentation.

Basic Types

# 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}"

Optional & Union

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)

Collections

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}
✏️ Exercise: Write a function with type hints that takes a list of integers and returns the sum. Add an optional multiplier parameter.