Motivation
Data that is sent or received by web applications is usually transferred via the HTTP protocol. The data is sent as byte array and therefore needs to be transformed to a standard format like JSON or XML. The transformation of programming language specific objects to byte representations is called serialization. The inverse operation is called deserialization and transforms a byte representation back into a programming language specific object.
In this article I want to show how database entities, which are represented as Python objects using SQLAlchemy, can be (de)serialized. I will show that it is not hard to implement ones own serializer classes. The procedure will be explained by means of a simple Flask application.
(De)serialization in Django
Most of the available web frameworks contain libraries that have support for (de)serialization. Django for example has serialization classes which are accessible via the Django Rest Framework. Especially helpful is the class ModelSerializer
: Inheriting from this class allows the (de)serialization of model instances without having to specify all fields of the model. The serialization class automatically detects all fields in the model class and maps these fields on the serialization class.
(De)serialization in Flask
Flask supports libraries for this feature as well. However, since Flask is a micro framework with minimal functionality out of the box, the necessary extensions have to be installed subsequently, after project initialization.
In the following, I want to show how automatic (de)serialization can be achieved in Flask. I use SQLAlchemy as ORM and
Marshmallow as (de)serialization engine. Since Marshmallow does not support SQLAlchemy out of the box, the installation of the extension
marshmallow-sqlalchemy is necessary.
Example application
A very simple Flask application, which encompasses some REST endpoints and two model classes, is used for demonstration. The model Company
represents companies, the model Product
represents product articles which are mapped on the database. Products can be assigned to companies by using a foreign key relationship.
Products consist basically of a name, a description and a price. Additionally, a discount can be assigned if needed. A database model like this is typically used in webshops, of course in a much more sophisticated form.
The Product
model can be modified via GET/PUT/POST requests as shown below.
The Python models are implemented like this: