Skillversitas

Python Type Hints

Type hints are annotations that describe the expected type of a variable or parameter. In FastAPI they are load-bearing: the framework reads your function signatures to build validation, documentation, and serialization. Learning the hint syntax is the highest-leverage skill for productive FastAPI development.

Basic Hints

def greet(name: str, age: int) -> dict:
    return {"name": name, "age": age}

def optional_value(x: str | None = None):  # optional (None allowed)
    return x

FastAPI treats str | None parameters as optional query parameters, and validates their type when present.

Collection Hints

from typing import Annotated

def tags(tag_list: list[str]) -> dict:
    return {"tags": tag_list}

def ids(id_list: list[int]) -> dict:
    return {"ids": id_list}

Pydantic Types for Constraints

For anything beyond plain types, use Pydantic types or Annotated. These show up as constraints in the generated docs:

from typing import Annotated
from pydantic import Field

def read_item(skip: Annotated[int, Field(gt=0, le=100)] = 0):
    return {"skip": skip}

def search(q: Annotated[str, Field(min_length=1, max_length=50)]):
    return {"q": q}

Why Hints Pay Off

  • Validation for free: wrong types produce a 422 with an itemized error list.
  • Documentation for free: /docs renders types, constraints, and defaults.
  • IDE support: autocompletion and static analysis catch mistakes before runtime.
  • Self-documenting code: the signature is the contract.

Summary

Type hints in FastAPI are the interface contract: str | None makes parameters optional, list and dict types validate collections, and Annotated with Field adds range, length, and pattern constraints. Write hints on every parameter and return type and the framework does the validation and documentation for you.