tezvyn:

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

Source: pydantic.devintermediate

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.

Pydantic automatically coerces raw input data, like strings from a JSON request, into the specific Python types you declare in your models. This is the magic behind FastAPI, where a JSON payload `{"id": "123"}` is seamlessly converted into a model field `id: int = 123`. The footgun: default coercion is very permissive. '1', 1, and 'true' can all become `True`. To prevent this, use Pydantic's `Strict` types (`StrictInt`, `StrictBool`) which forbid coercion.

Read the original → pydantic.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.

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