Annotated in Python and FastAPI: Deep Dive
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 h...

Source: DEV Community
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 he