Serialization

The process of converting a data object into a format for storage or transmission.

For example, we can take a Python object and serialize it into JSON. Then it can be shared with other programs, computers or networks.

The SQLAlchemy-Serializer can be used to generate a dictionary for a model class that will map object attribute names as keys to values. When a model class inherits from SerializerMixin, it will gain the method to_dict(). This method will convert the model object into a dictionary.

Let's first start with models.py and create a model.

#models.py 
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
from sqlalchemy_serializer import SerializerMixin

metadata = MetaData()
db = SQLAlchemy(metadata=metadata)

class Book(db.Model, SerializerMixin):
    __tablename__ = 'books'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String)
    author = db.Column(db.String)

    def __repr__(self):
        return f'<Book {self.id}, {self.title}, {self.author}>'

Next, we will run the following commands in the terminal.

$ pipenv install
$ pipenv shell
$ cd server
$ flask db migrate -m "create Book"
$ flask db upgrade head
$ flask shell

Now that we are in the flask shell, we will create a book. Then use the to_dict() method to make the book into a dictionary.

>>> book1 = Book(title='Pride and Prejudice',author='Jane Austen')
>>> db.session.add(book1)
>>> db.session.commit()
>>> book1
<Book 1, Pride and Prejudice, Jane Austen>
>>> book1.to_dict()
{'id': 1, 'title': 'Pride and Prejudice', author: 'Jane Austen'}

This will be useful when the frontend of an app makes a fetch request to the backend. Here we see a class in app.py that is sending to the frontend, the list of dictionaries for each book.

#app.py
...

class Books(Resource):
    def get(self):
        books = Book.query.all()
        return [book.to_dict() for book in books], 200

api.add_resource(Books, '/api/books')