Skip to content

Data Validation

Programming has a saying: garbage in, garbage out. Incorrect inputs rarely produce useful results. A post lookup can find post 3 when given 3, but a value such as python does not identify a numeric post. Checking the input first lets the API tell the client what it expects.

Checking whether input meets predefined rules is called data validation. When we declared post_id: int, FastAPI checked whether the client's value could be converted to an integer.

FastAPI uses Python type hints and the Pydantic validation library to check input. Let's look at how type hints describe expected values and how Pydantic validates them.

Type Hints

Python does not require you to declare types when assigning variables or defining functions. A variable can later hold another type: age can start as integer 20 and then hold string "alex".

age = 20
age = "alex"  # ①
next_age = age + 1  # ②

① successfully reassigns age from 20 to "alex". But adding 1 in ② raises TypeError, because Python cannot add an integer to that string.

Type hints help catch such mistakes before execution. They are annotations describing the expected types. To indicate that age should hold an integer, add : int after its name.

age: int = 20

A reader can now see that age is intended to contain an integer, making an accidental string assignment easier to spot.

Python treats these annotations as hints. A statically typed language such as Java rejects assigning a string to an integer variable at compile time. Python does not enforce a variable's type hint at runtime.

age: int = 20
age = "alex"

The string assignment still runs. However, the annotation exposes the mismatch with the intended type. An IDE with type checking enabled, or a separate type checker, can report it before the code runs.

1. Basic Types

Add : type after a variable name to describe its intended value:

variable: type = value
title: str = "A new post"
views: int = 20
rating: float = 4.5
is_published: bool = True

2. Functions

Functions can annotate their parameters and return values. Parameters use : type after the name; the return type uses -> type after the closing parenthesis.

def add(n1: int, n2: int) -> int:
    return n1 + n2

n1: int and n2: int expect integers, and -> int describes an integer return value.

3. Container Types

Lists and dictionaries are container types: they hold other values. Their annotations can describe both the container and its contents.

tags: list[str] = ["python", "fastapi"]  # ①
views_by_tag: dict[str, int] = {"python": 20, "fastapi": 12}  # ②

① list[str] holds strings. ② A dictionary has keys and values, so its annotation uses dict[key_type, value_type]. Thus dict[str, int] has string keys and integer values.

4. Allowing Multiple Types

Use | to allow more than one type. A | B means type A or type B; int | str allows an integer or string.

score_query: int | str = "max"  # ①
scores: list[int | float] = [90, 87.5]  # ②

① Imagine using score_query to find students by score. Integer 90 selects that score, while "max" and "min" select the highest or lowest score.

② In list[int | float], the union applies to each item. Integer 90 and float 87.5 can both appear in the list.

5. Classes

You can also use your own classes as type hints. A Post class can describe a variable that holds a post object.

class Post:
    def __init__(self, title: str):
        self.title = title


new_post: Post = Post("A new post")

new_post: Post describes a Post instance. The expression Post(...) creates that instance and assigns it to new_post.

Type Hints in FastAPI

FastAPI uses handler parameter annotations to validate client input.

main.py
@app.get("/posts/{post_id}", summary="Get a post")
def get_post_handler(post_id: int):
    return {"post_id": post_id}

For /posts/3, FastAPI reads string "3" and attempts to convert it according to : int. Since conversion succeeds, the handler receives integer 3. An unconvertible value such as python produces an error before the handler runs.

This validation is a feature of FastAPI. Python's type hints do not enforce types by themselves. FastAPI reads them to convert and validate request data. Annotating your handler parameters lets FastAPI handle conversion, validation, and error responses.

Pydantic

Pydantic uses type hints to validate data and ensure that successfully validated values have the declared types. FastAPI uses it for request validation. Path and Query are also built on Pydantic's FieldInfo.

Pydantic lets you express the data structure your program expects as Python code: for example, an integer ID with a string title and content. A class defining this structure is called a model; each declared item is a field.

To start using Pydantic in FastAPI, learn how to define a model with BaseModel. Let's represent our post data:

from pydantic import BaseModel


class Post(BaseModel):
    id: int
    title: str
    content: str

Inherit from BaseModel, declare the fields, and annotate each field with its expected type.

To validate data, pass field values when creating a Post instance. Pydantic validates them during construction. If all pass, it creates the instance.

new_post = Post(id=3, title="A new post", content="Let’s learn FastAPI")

Invalid data raises pydantic.ValidationError. For example, an integer supplied for the string title fails validation:

new_post = Post(id=3, title=123, content="Let’s learn FastAPI")
pydantic_core._pydantic_core.ValidationError: 1 validation error for Post
title
  Input should be a valid string [type=string_type, input_value=123, input_type=int]
    For further information visit https://errors.pydantic.dev/2.12/v/string_type

The error identifies title and explains that integer 123 is not a valid string input.

This may look familiar. Our earlier path validation produced an int_parsing error. Both examples use Pydantic. In the path example, FastAPI sent the error as JSON; here Python displays the exception from directly constructing a model.

With Pydantic, define the expected structure and instantiate the model to validate data. FastAPI uses this to check types and constraints while processing requests and preparing responses.

Check Your Understanding

Decide whether each statement is true or false.

  1. Python's variable type hints reject assignments of another type at runtime.
  2. A list annotated with a union of integer and float types may contain both.
  3. FastAPI can convert a numeric path string to an integer before passing it to a handler.
  4. Defining a Pydantic model class validates incoming values before any instance is created.
  5. Passing an integer to a Pydantic string field can raise a validation error.
Answers and Explanations
  1. False — Type hints alone do not enforce assignment types at runtime.
  2. True — Each item can have either of the allowed types.
  3. True — FastAPI uses the declared type to validate and convert the value.
  4. False — The definition declares rules; validation happens when data is supplied to construct or validate a model.
  5. True — By default, Pydantic string fields do not accept integers as strings.