Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Custom Validators and Types

Custom Types and Validation Context

Create your own Pydantic types with __get_pydantic_core_schema__, control JSON Schema and serialization, and pass runtime data to validators with the context argument.

Annotated validators cover most reusable rules. Sometimes you want a real class as a field type: a PhoneNumber, a Money amount, a UserId. Pydantic does not know your class, so you teach it how to validate (and optionally how to serialize and describe) instances. There are three levels of effort, and this lesson takes them in turn. At the end you will also see validation context, which lets validators read data supplied by the caller at run time, such as the current user or a list of reserved names.

Level 1: arbitrary_types_allowed

If all you need is "this must be an instance of my class", set arbitrary_types_allowed=True. Pydantic checks with isinstance and does no conversion and no JSON handling.

Python isinstance checks for foreign classes

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.

It is quick, but you cannot validate from a dictionary or JSON, and model_dump_json fails on such fields. For types that should travel as data, go further.

Level 2: a type with a core schema

A class can describe itself to Pydantic by defining __get_pydantic_core_schema__. You build a core schema, a small description of the validation steps, from pydantic_core.core_schema. The common recipe is: validate the input with a simple schema first (for example a string), then call your function to construct the object, and say how to serialize it.

Python A PhoneNumber class

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.

Read the schema from the inside out. For JSON input, str_schema() accepts a string and no_info_after_validator_function calls _parse on it. For Python input, no_info_plain_validator_function calls _parse directly, which also accepts a ready PhoneNumber. json_or_python_schema picks the right branch. The serialization part writes the object back as its digits, so JSON output is a plain string.

For JSON Schema (what FastAPI shows in its docs), add __get_pydantic_json_schema__ to describe the type; otherwise generating a schema for a field of this type raises an error because Pydantic cannot guess.

Python Describing the type in JSON Schema

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.

Level 3: Annotated markers with schema hooks

You often cannot edit the class (it comes from a library). Instead of a method on the class, put the same hook on a small marker object in Annotated. Pydantic calls the marker's __get_pydantic_core_schema__, and you may call handler(source) to get the schema Pydantic would have built, then wrap it.

Python A marker that wraps the usual schema

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 marker is configurable (Multiple(12)), and handler(source) keeps all the standard behavior of int (such as accepting "24"), so you add a rule without rewriting the base parse.

Validation context

Sometimes a rule depends on data that is not in the input and is not a constant: the set of usernames already taken, the current user's role, the current date for testing. Pass it as context when you validate, and read it in a validator from info.context.

Python Passing context to 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.

Always handle a missing context (info.context or {}), because models are also created without it, for example by NewUser(username=...), which takes no context. The context is available to model_validate, model_validate_json and TypeAdapter.validate_python, and it reaches nested models.

Context is a good way to keep validators pure and testable: instead of a validator calling a database, the caller looks up the data once and passes it in.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does arbitrary_types_allowed=True do for a field of your own class?

    It is the quickest option, but you still need a core schema if the type should be parsed from data or serialized.
  2. 2. In get_pydantic_core_schema, what does handler(source) return?

    Calling the handler gives you the standard schema, so you add behavior without rewriting the base validation.
  3. 3. How does a validator read the caller's context?

    context is an optional argument to the validate methods and shows up on ValidationInfo.
  4. 4. Why should a validator use (info.context or {}) instead of info.context directly?

    Plain construction such as NewUser(username=...) passes no context, so the validator must cope with None.

Summary

  • Three levels: arbitrary_types_allowed for isinstance checks; __get_pydantic_core_schema__ for real parsing and serialization; Annotated markers when you cannot edit the class.
  • Core schemas are built with pydantic_core.core_schema; handler(source) gives the normal schema to wrap.
  • __get_pydantic_json_schema__ describes the type for JSON Schema and API docs.
  • context= passes run-time data to validators through info.context; always handle None.

Next: FastAPI Request Models