If the client sends a value that does not match the expected type (e.g., a non-integer for “rating”), FastAPI returns a validation error. For example, a request with an invalid “rating” field:produces the following response:
new_post in the example), you can access its properties using dot notation (e.g., new_post.title). Additionally, each Pydantic model includes a .dict() method that converts the model into a standard Python dictionary.
Consider the following example:
- Replacing manual extraction of payload data with a Pydantic model.
- Enforcing data types and default values for various fields.
- Handling optional fields using Python’s typing.Optional.
- Accessing validated data and converting the Pydantic model to a dictionary with the
.dict()method.