Skip to content
tezvyn:

Pydantic's Data Coercion: From Raw Data to Python Types

Source: pydantic.devMediumHow cards are made

Pydantic's Data Coercion: From Raw Data to Python Types

Pydantic automatically converts raw data, like strings from a JSON request, into the Python types you declare. It's how FastAPI turns a JSON body into a typed Python object.

Why it exists

Web APIs and configuration files deal with simple data types, mostly strings. Applications need structured, typed data like integers, dates, and enums. Pydantic was created to bridge this gap, providing a robust way to parse, validate, and convert raw data into clean Python objects.

The mental model

Think of Pydantic's coercion as an automatic type-casting layer for your data. When you define a model like class User(BaseModel): id: int, you're telling Pydantic: "I expect an 'id' field. Whatever you receive, do your best to turn it into a Python integer. If you can't, raise an error." It's a contract for data shape and type.

How it works

Pydantic maintains an internal "conversion table" that defines how to convert from one type to another. For a boolean field, it knows that strings like 'true', 't', '1', or 'yes' (case-insensitive) should all result in True. When data is passed to a model, Pydantic iterates through the fields. For each field, it attempts to coerce the input value according to the field's type annotation. If the input {'age': '30'} is passed to a model with age: int, Pydantic successfully converts the string to the integer 30.

When to use it

Data coercion is a core feature you use anytime you use Pydantic. It's especially powerful in web frameworks like FastAPI for parsing incoming request bodies, query parameters, and path variables. It is also ideal for parsing configuration files (e.g., from JSON or YAML) into strongly-typed settings objects.

When not to use it

You might want to disable coercion when you need to enforce strict data contracts. If an API client must send a number as a JSON number (5) and not a string ("5"), the default permissive coercion is a problem. In these cases, use Pydantic's Strict types, like StrictInt or StrictBool, which forbid type coercion and require the input data type to match the annotated type.

One canonical example

A common use case is creating a reusable, constrained type. Using typing.Annotated, you can define a type that must be an integer and also positive. This shows both coercion (string to int) and validation in one step.

from typing import Annotated
from pydantic import BaseModel, Field, ValidationError
PositiveInt = Annotated[int, Field(gt=0)]
class Item(BaseModel):

item_id: PositiveInt This works: Pydantic coerces the string '123' to an int and validates it.

item = Item(item_id='123')

item.item_id is now the integer 123 This fails validation because -5 is not greater than 0.

try:
Item(item_id=-5)

except ValidationError as e:

print(e)

Interview question

When would a developer choose to disable Pydantic's default data coercion for a field?

  • a.When the data source is known to be highly reliable and already provides data in the correct Python types.
  • b.To allow for more flexible handling of diverse input formats, such as accepting both integers and strings for a numeric field.
  • c.To enforce that the input data's type precisely matches the annotated Python type, preventing automatic conversions.Correct
  • d.When the application needs to process extremely large volumes of data and minimize any potential performance overhead.
Why?

The card states that coercion should be disabled "when you need to enforce strict data contracts" and the input data type must match the annotated type exactly. Option B is incorrect because coercion actually enables more flexible handling of diverse input formats by converting them to the target type, so disabling it would reduce flexibility.

Just read this? Test yourself on what you have been reading.

Read the original → pydantic.dev

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on python — each one lists the topics its interview covers.

See open roles