DEV Community

Cover image for Python serialization with Marshmallow
Rafael Marques
Rafael Marques

Posted on

Python serialization with Marshmallow

When we are creating a API, we need a solid way to serialize and deserialize our data. The are lots of ways to do it, but in this article, we are going to see how to work with marshmallow.

So, let's take a look on how we start using marshmallow in our projects.

Install Marshmallow

To install marshmallow, we will use pip:

$ pip install -U marshmallow

Note that the -U parameter is used to upgrade all the packages to the newest version.

Now we have:

pip install -U marshmallow
Collecting marshmallow
Using cached marshmallow-3.5.1-py2.py3-none-any.whl (45 kB)
Installing collected packages: marshmallow
Successfully installed marshmallow-3.5.1

Creating our first Schema

To create a schema, we will use basically two imports: Schema and fields

To create a class representing our data, we will make it a subclass of Schema. To represent our fields, we will use the fields.TYPE, as you can see in the example above.

Now, we can serialize and deserialize our data using our schema:

As you can see, we basically use load to deserialize our data into python objects, and dump to serialize it again.

Validating data with Marshmallow

One of the great advantages of using a serialization library, is to be able to validate the incoming data. Marshmallow offers you a simple way of doing it.

As you can see in the code above, we sent an integer to a field expecting a valid UUID. When we use the load method, marshmallow will raise a ValidationError with all the data that are wrong.

You can use the messages property to check all data that failed to validate, and with valid_data property, you can check all data that is valid.

Custom message validations in marshmallow

Although we can use default validation messages provided by Marshmallow, we can provide our own custom messages:

And when we try to load the data, we’ll get our custom message to each cenario:

Top comments (0)