Handling Incoming Data with Marshmallow
Handling Incoming Data with Marshmallow
Welcome back! In the previous lesson, we explored defining schemas and serializing data with Marshmallow. Now, we will take it a step further by handling incoming data from a request and automatically validating it using Marshmallow. This is crucial for ensuring that the data your application receives adheres to expected formats and standards.
By the end of this lesson, you will be able to create a Flask endpoint that handles incoming user data, validates it using Marshmallow schemas, and adds it to a mock database.
Recap of Previous Lesson
Here’s a reminder of the initial setup, including the Flask app instance and our mock database:
Defining Required Schema Fields
To handle incoming data properly, we need to specify what valid data looks like using a Marshmallow schema. Let's focus on making certain fields mandatory, like username and email.
Here's an updated version of our schema that enforces these requirements:
In this schema, setting required=True for the username and email fields ensures that both fields must be provided and follow their respective data types (string and email format).
On the other hand, the id field is not marked as required because it will be generated automatically when a new user is added. This setup helps keep our user data accurate and complete.
Validating Incoming Data
Now that we've defined our schema, we need to validate incoming data against this schema!
We'll use Marshmallow's load method to load and validate incoming JSON data. If the data is invalid, Marshmallow will raise a ValidationError. Let's see how this works in the context of a Flask route:
request.get_json()retrieves the incoming JSON data from the request body.user_schema.load(request.get_json())attempts to load and validate this data against theUserSchema.- If validation fails, a
ValidationErroris raised, and we catch it in theexceptblock, returning the error messages as a JSON response with a 400 status code.
