Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 50 ยท Pydantic models and validation

Field constraints and validators

Add rules to FastAPI models with Field(), constraints, field_validator, model_validator, computed fields, Annotated types and custom error messages.

A type hint says what kind of value a field holds. Real APIs need more: a username between 3 and 20 characters, a price above zero, an end date after the start date. Pydantic gives you two layers for this. Constraints are declarative limits you attach to a field with Field(). Validators are Python functions for rules that a constraint cannot express.

Because FastAPI builds on Pydantic, every rule you write here is enforced on incoming requests, produces a 422 response with a precise message, and shows up in the generated OpenAPI documentation. If you haven't yet, read Pydantic models for APIs first.

Two layers of rules

Constraints Field(min_length=3, gt=0). Declarative and documented.
Field validators One field, custom Python logic.
Model validators Rules that compare several fields.

Use the simplest layer that can express the rule.

1 / 2

Constraints with Field()

Field() goes in the default position. Use ... (or just omit the default through Annotated, shown later) for a required field.

Python Constraints on a model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each failure has a specific type such as string_too_short, string_pattern_mismatch, greater_than_equal or too_long. Client code can switch on that type instead of parsing messages.

default_factory builds a fresh default for every instance. Use it for lists, dicts and anything that must be computed per object, such as a timestamp.

Field() also carries documentation: title, description and examples end up in the OpenAPI schema, so Swagger UI shows them next to the input.

Annotated types you can reuse

Repeating the same constraints on many fields is tedious. typing.Annotated lets you name a constrained type once and reuse it. This is also the style FastAPI recommends for parameters.

Python Reusable constrained types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line shows how the constraint (exclusiveMinimum) and the description are copied into the schema.

Field validators

When a rule needs real code, add a field_validator. It is a class method that receives the value, returns the (possibly cleaned) value, or raises ValueError (or AssertionError) to reject it.

By default a validator runs after Pydantic's own parsing (mode="after"), so you get a value of the declared type. Use mode="before" to clean raw input first, for example to trim whitespace or accept a comma-separated string.

Python before and after validators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the stacking order: @field_validator sits on top of @classmethod. The message you pass to ValueError becomes part of the error text, prefixed with Value error, .

Rules across fields: model validators

A field validator sees one field. When a rule compares fields, use model_validator. With mode="after" it receives the finished model instance and must return it.

Python A model validator and a computed field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A computed field is a read-only value derived from other fields. It appears in model_dump(), in JSON responses, and in the schema, but clients can't send it. The error loc for a model validator is empty (()), because the problem belongs to the whole object, not one field.

Prefer a constraint over a validator whenever one exists. Constraints are documented in OpenAPI and are reported with a stable type; a validator is opaque to the docs.

Custom error messages

You can shape what clients see in two ways. Raising ValueError("...") sets the message for that rule. For full control, raise PydanticCustomError(type, template) from pydantic_core, which gives the error your own machine-readable type and a message with placeholders.

Python A custom error type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the HTTP response the loc starts with body, because FastAPI knows the value came from the request body. Later, in status codes and error handling, you'll reshape these errors into one consistent format.

Validators run on user input, so keep them fast and free of side effects. Don't query the database inside one; check uniqueness in the endpoint or a service, where you can return a proper 409.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which declaration requires a string of 3 to 12 characters?

    min_length and max_length constrain text length. ge and le are for numbers.
  2. 2. What is mode="before" on a field_validator for?

    A before validator sees the raw value, such as a comma-separated string, and can turn it into something Pydantic then validates normally.
  3. 3. A rule says end must come after start. Which tool fits best?

    A model validator sees the whole instance, so it can compare fields.
  4. 4. Why use default_factory=list instead of = [] in a Field()?

    A factory is called for each new model, which is the right tool for lists, dicts and timestamps.

Summary

  • Field() attaches constraints (gt, ge, min_length, pattern, ...) and documentation to a field.
  • Annotated[type, Field(...)] names a constrained type once for reuse.
  • field_validator handles one field; mode="before" sees raw input, the default sees parsed data.
  • model_validator(mode="after") checks rules across fields; computed_field adds derived read-only values.
  • Raise ValueError for a simple message or PydanticCustomError for your own error type.

Next: shape what the API sends back in response models and nested data.