FastAPI Python Type Hints

Type hints are small labels that describe the kind of data a variable or function holds. Picture kitchen jars marked "sugar" and "salt". A label never changes what sits inside the jar, yet every person who opens the cupboard knows what to expect. Python ignores type hints while a program runs. FastAPI reads them and turns each label into validation rules, data conversion, and documentation.

Almost every FastAPI feature builds on type hints. A solid grip on them makes the rest of the tutorial feel natural.

Type Hints for Variables

Write the type after a colon that follows the variable name.

name: str = "Asha"
age: int = 25
price: float = 19.99
is_active: bool = True

The four basic types cover most beginner needs:

  • str holds text such as names and emails.
  • int holds whole numbers such as age or quantity.
  • float holds decimal numbers such as price.
  • bool holds True or False.

Type Hints for Functions

Functions carry two kinds of labels: one for each input and one for the returned value. An arrow marks the return type.

def add_tax(price: float, rate: float) -> float:
    return price + price * rate
  price: float ──┐
                 ├──▶  add_tax()  ──▶  float
  rate:  float ──┘

The diagram shows two float inputs entering the function and one float leaving it.

Collection Types

Square brackets describe what a collection holds.

scores: list[int] = [80, 92, 75]
ages: dict[str, int] = {"Asha": 25, "Ravi": 30}
point: tuple[float, float] = (10.5, 20.5)
tags: set[str] = {"api", "python"}

The label list[int] means a list that contains only integers. The label dict[str, int] means keys are text and values are integers.

Optional Values and Unions

Some values may be missing. A pipe symbol joins two allowed types.

nickname: str | None = None
user_id: int | str = 101

The first line says nickname holds text or nothing. The second line says user_id accepts a number or text. Python 3.10 and newer support the pipe style. Older versions use Optional[str] and Union[int, str] from the typing module.

How FastAPI Reads Type Hints

Take a small route and watch each label at work.

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(item_id: int, verbose: bool = False):
    return {"item_id": item_id, "verbose": verbose}
Request:  GET /items/7?verbose=true

  item_id: int    "7"    becomes   7
  verbose: bool   "true" becomes   True

Response: {"item_id": 7, "verbose": true}


Request:  GET /items/abc

  item_id: int    "abc"  cannot become a number
  Response: 422 error with a clear message

Web requests send everything as text. The labels tell FastAPI how to convert that text, and a failed conversion stops the request before your function runs.

Three Jobs of a Type Hint

Validation

FastAPI rejects data that does not match the label and returns a 422 response that names the faulty field.

Conversion

Text from the URL becomes the proper Python type, so your function receives a real integer or boolean.

Documentation

The interactive docs show every parameter with its type. Developers who call your API see the expected format without reading your code.

Editor Support

Modern editors such as VS Code and PyCharm use type hints to offer autocomplete and flag mistakes while you type. Assigning a string to a variable labelled int earns an instant warning. Fewer bugs reach the running server.

Common Mistakes

Missing Default on Optional Values

A parameter labelled str | None still needs = None to become truly optional in FastAPI. Without the default, the parameter stays required.

Wrong Label for the Real Data

Labelling a price as int rejects values such as 19.99. Pick the type that matches the data you expect.

Expecting Python to Enforce Hints

Plain Python never checks hints. FastAPI performs the checking only for route parameters and models.

Key Points

  • Type hints label the data that variables and functions hold.
  • Python ignores hints at runtime; FastAPI turns them into rules.
  • Use list[int] and dict[str, int] to describe collections.
  • Use | None for values that may be missing.
  • Hints power validation, conversion, and automatic documentation.