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.
Here’s a reminder of the initial setup, including the Flask app instance and our mock database:
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.
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
ValidationError
is raised, and we catch it in theexcept
block, returning the error messages as a JSON response with a 400 status code.
Once the data is validated, we can proceed to add it to our mock database. Here is the complete code snippet:
- If validation is successful, the validated data is added to the mock database.
- A unique
id
is generated and assigned to the new user. - User is appended to the
database
list. - The created user is returned as a JSON response with a 201 status code.
If the incoming request does not meet the validation criteria defined in the UserSchema
, the ValidationError
exception will be raised and the response will detail the specific validation errors.
For example, if both username
and email
are missing, the response will look like this:
This response is returned with a 400 status code, indicating invalid data provided by the client.
Additionally, if the email
field contains an invalid email address, the response will look like this:
This response is also returned with a 400 status code, indicating invalid data provided by the client.
In this lesson, we extended our Marshmallow
skills by focusing on handling incoming data and its validation. Specifically, we:
- Defined a
UserSchema
with required fields usingMarshmallow
. - Demonstrated how to validate incoming JSON data within a Flask route.
With these concepts in mind, you're now ready to tackle the practice exercises ahead. These exercises will provide hands-on experience and help solidify your understanding.
Keep practicing, and happy coding!
