FastAPI - Beginner to Pro / Project 3: Complete RESTful APIs

Pydantic v1 vs Pydantic v2 in detail

πŸ”„ FastAPI Compatibility with Pydantic v1 and v2

FastAPI is now fully compatible with both Pydantic v1 and Pydantic v2.

Depending on which version of FastAPI you are using, you may encounter small but important differences in method names and configurations.

These changes are especially relevant if you are following older tutorials or upgrading an existing codebase.

⚠️ Key Differences to Be Aware Of

There are three major changes you should pay close attention to when working with Pydantic v2 in FastAPI.


🧩 Model Serialization Changes

In Pydantic v1, model data was commonly converted into dictionaries using:

.dict()

In Pydantic v2, this method has been renamed to:

.model_dump()

If you are using Pydantic v2, calling .dict() will no longer work as expected.


πŸ—οΈ Schema Configuration Changes

Previously, additional schema metadata inside a Pydantic model was defined using:

schema_extra

With Pydantic v2, this has been renamed to:

json_schema_extra

This change applies to the Config class within your Pydantic models and affects how your API documentation is generated.


❓ Optional Field Declaration Changes

When defining optional fields in Pydantic models, it is now required to explicitly provide a default value of None.

For example:

id: Optional[int] = None 

Without assigning = None, the field may still be treated as required, even though it is marked as optional.


🧠 Why These Changes Matter

These updates ensure:

  • Better clarity in model definitions

  • Improved schema generation

  • Clearer separation between required and optional fields

Understanding these differences helps prevent runtime errors and unexpected validation issues when upgrading or maintaining FastAPI applications.


βœ… Summary

FastAPI supports both Pydantic v1 and v2, but newer versions introduce important naming and behavior changes.

The .dict() method has been replaced with .model_dump(), schema_extra is now json_schema_extra, and optional fields must explicitly default to None.

Being aware of these updates ensures smoother upgrades and more reliable FastAPI applications.