FastAPI and Python Type Hints
FastAPI heavily relies on Python’s type hints to understand what kind of data your API expects and returns. Python itself is dynamically typed and does not enforce these types at runtime, so type hints alone do not prevent errors. However, FastAPI uses these hints to automatically validate request data, generate OpenAPI schemas, and create API documentation. Separately, tools like MyPy can use the same type hints to catch type errors before the code runs.
1. Python is dynamically typed
- Variable types are decided at runtime
- Wrong types cause
TypeErrorat runtime
def division(a, b):
return a / b
2. Type hints add expectations, not enforcement
def division(a: int, b: int) -> float:
return a / b
- Python does not stop execution for wrong types
- Type hints are used for readability, tooling, and frameworks like FastAPI
3. MyPy checks types before running
- Static type checker that flags mismatches without executing the program
mypy main.py
4. FastAPI uses type hints
- Validates incoming request data
- Converts JSON to Python types automatically
- Rejects invalid requests with 400 errors
- Generates OpenAPI schema (
openapi.json) - Builds Swagger UI (
/docs)
5. Type hints for collections
from typing import List, Dict
cities: List[str] = ['Mumbai', 'Delhi', 'Chennai']
marks: Dict[str, int] = {'Ravi': 61, 'Anil': 72}
Summary
FastAPI leverages Python type hints to perform runtime data validation, automatic API documentation, and schema generation, while tools like MyPy use the same hints for static type checking before execution.