Contenido del Curso
Professional Web API with Flask
Professional Web API with Flask
Schema Handling with Marshmallow
For better organization and maintainability, it's beneficial to create a separate file for working with schemas, typically named schemas.py. This file will house all the schema classes required for our API, enabling us to structure and validate data efficiently.
The Basics of Marshmallow Schemas:
Here's how we import and define our schemas with Marshmallow:
The Schema class from Marshmallow is used to create schema definitions, with various fields types specifying the data types and validation requirements for our API's data models.
Nested Schemas and Avoiding Recursion:
One common challenge in using schemas is avoiding infinite recursion. For instance, when we serialize a team, it includes a list of players, and each player might reference back to their team, creating a loop.
To circumvent this issue, we can introduce 'plain' or simplified schemas, which only include the necessary fields when nested within other schemas.
Implementation of Plain Schemas:
We create plain versions of our schemas to include only the essential fields:
These plain schemas are then used within the original schemas to break the potential infinite loop caused by nested relationships.
Refactoring Our Schemas:
After defining our plain schemas, we refactor our main schemas to inherit from them:
In these refactored schemas, we ensure that nested relationships use the plain schemas, preventing recursive serialization issues.
Testing Our Schemas:
With our schemas refactored, it's crucial to test them to ensure they work as intended. We can serialize sample data to JSON and deserialize JSON payloads to Python objects, checking for any errors or issues.
We've made significant progress in creating and refining our Marshmallow schemas. In the next part of the course, we will integrate these schemas with additional endpoints and functionalities, putting them into practice within our API.
Note
Full code from the video can be checked in GitHub by the link.
¡Gracias por tus comentarios!