Pydantic v2 Models from JSON Responses
If you're building Python APIs with FastAPI, Flask, or Django, you need Pydantic models. They validate incoming data, serialize responses, and generate OpenAPI documentation automatically. Writing them from scratch for complex API responses is slow - here's how to generate them from JSON.
Why Pydantic for JSON
Python's built-in json.loads() gives you untyped dictionaries:
Pydantic models give you validated, typed objects:
JSON to Python Type Mapping
| JSON | Python / Pydantic |
|---|---|
"string" | str |
123 | int |
1.5 | float |
true | bool |
null | None (use Optional[str]) |
[1, 2] | list[int] |
{} | Nested BaseModel |
"2026-01-15" | datetime or date |
"ada@dev.io" | EmailStr |
"https://..." | HttpUrl |
Generating Models Automatically
Our JSON to Pydantic converter takes JSON like this:
And generates:
The converter detects nested objects and creates separate model classes for each, with proper type references.
Pydantic v2 vs v1
Pydantic v2 (released 2023) is a major rewrite with significant changes:
| Feature | v1 | v2 |
|---|---|---|
| Validation | Python | Rust core (5-50x faster) |
| Config | class Config | model_config = ConfigDict() |
| Validators | @validator | @field_validator |
| JSON parsing | .parse_raw() | .model_validate_json() |
| Serialization | .dict() | .model_dump() |
FastAPI Integration
Pydantic models plug directly into FastAPI for request validation and response serialization:
FastAPI uses the Pydantic model to validate the request body, generate OpenAPI docs, and serialize the response - all automatically.
Adding Custom Validation
After generating base models, you can add validators:
Workflow
- Get a sample API response (use your browser's network tab or
curl) - Paste it into the JSON to Pydantic converter
- Copy the generated models into your project
- Add custom validators and field descriptions
- Use with FastAPI, Flask, or standalone validation