Advanced Marshmallow Usage — JSON field(Part 4)

Waqqas Jabbar
2 min readNov 8, 2021

This is continuation of series of posts on how to use Marshmallow package in REST API development.

In this post we will look at how to use JSON database field to store user’s profile data. Earlier, our DB model had two fields (“first_name” and “last_name”) that is part of user’s profile. Later on, we might want to store more information in user’s profile. In anticipation for that, instead of adding more columns in “user” model, we move these columns into a JSON field. Thus, when we have to add more data in user’s profile, we would just add another property in the JSON data stored in the “profile” field.

We change our DB model as follows:

Since we are storing JSON data, it’s a good to define it’s schema. We again use marshmallow to validate the data before storing it in the “profile” field. For that we create the following schema.

We don’t want to change our API DTO.

Create Scenario

Thus, we need to convert the data after validation (post_load) in the form that is acceptable to the model. Similarly, when we need to dump the payload, we need to convert the data in the profile back. This is done as follows, when we are creating a new user. (POST API)

Line 6–10: we create a “profile” key and move the fields from main DTO to this key using the ProfileDto.

Update Scenario

Next scenario to handle is the updating an existing user model (PUT/PATCH API call). We do similar to what we have done in “create”, taking into consideration the case that if the user has not specified any field.

Line 6–14: We move the data into the “profile” attribute.

The is no change in the controller code.

This is a lot of code. We will make further improvements to this in the next post.

Conclusion

Using JSON DB field, we can declutter our main model and also allow more fields to be added to the “user’s profile” without changing the model.

--

--