How to Serialize JSON using Flask SQLAlchemy

Image for post
Image for post
Pearson Scott Foresman / Public domain

Recently I was involved in developing a PPE response network built by The Luminosity Lab at Arizona State University. Its backend was built using Flask. This was my first time working on a Flask application and I was surprised that it is not trivial to elegantly serialize the database model classes to JSON. There are multiple approaches that can be used to serialize the classes. In this post, I will introduce you to the approach that I liked the most.

Using SQLAlchemy-serializer

The SQLAlchemy-serializer library makes serializing objects to JSON quite easy and it has got quite a few customizations that let you handle all of your custom use cases.

Install the library

Install the library using pip.

pip install SQLAlchemy-serializer

Define the Model Class

Define your database’s model class using SQLAlchemy.

Define a Custom Serializer

If your database table uses classes like UUID , Geometry etc., you will need to define a custom serializer for it.

class CustomSerializerMixin(SerializerMixin):
serialize_types = (
(UUID, lambda x: str(x)),

Check out the documentation to see what data types are natively supported by the library.

Define fields to serialize

You can specify the list of fields you want to serialize by using the serialize_only field in your model class.

serialize_only = ('id', 'email_id', 'role_type', '')

Note: In this example, we have a users relationship defined and we want to serialize just the id field of users.

Define fields to exclude

You can exclude the whole relationship object by using a minus(-) symbol before the relationship name.

serialize_rules = ('-merchants')

In this example, we want to exclude all the fields of the merchants field when serializing the JSON.

Avoid circular dependency

If you have a relationship and foreign key defined in your models, you could run into a circular dependency issue. Suppose you have the following model classes defined:

Notice that the login class has users added in its serialize_only field. With this setup you will face a maximum recursion depth exceeded exception. The serializer will find an instance of the same class among the model’s relationships. To avoid this you need to define where the serialization should stop:

serialize_rules = ('-users.login.users',)

Serialize JSON

With the serializer mixin in place, its very simple to serialize your object to JSON.


Written by

Grad Student at ASU | Student Researcher at The Luminosity Lab | Ex Senior Software Engineer, Zeta | Volunteer, Wikimedia Foundation

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store