DEV Community

Cover image for Annotated in Python and FastAPI: Deep Dive
Heba Allah Hashim
Heba Allah Hashim

Posted on

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 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"]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)