What is Annotated in Python?
Annotated is a feature in Python’s type hints system (introduced in Python 3.9 with PEP 593).
It allows you to:
- Define the type of a variable
- Add extra metadata about how that variable should be handled
Python itself ignores this metadata at runtime, but tools (like FastAPI, Pydantic, or linters) can use it.
Example
from typing import Annotated
age: Annotated[int, "must be positive"]
Breakdown:
-
int: the core type -
"must be positive": metadata for tools to interpret
Python itself doesn’t enforce "must be positive", but other libraries could use it for validation.
FastAPI and Annotated
FastAPI uses Annotated to inject request data (like query params, headers, cookies) into your function parameters.
from typing import Annotated
from fastapi import Header
async def get_token_header(
x_token: Annotated[str, Header()]
):
return x_token
How it works
-
x_token: The parameter name -
str: The type (must be a string) -
Header(): Metadata telling FastAPI: “Look in the HTTP headers for X-Token”
FastAPI uses this metadata to extract values from the HTTP request automatically.
Why Annotated matters in FastAPI
It helps FastAPI:
- Separate type definition from request metadata
- Improve readability
- Make dependencies explicit
- Enable powerful dependency injection patterns
Top comments (0)