Django Rest API Serialization

created:

updated:

tags: django rest api

When I first started with web development, I was confused with serialization and deserialization. It took me a while to grasp what they mean in the REST API.

What is Serialization?

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types.

What is De-serialization?

Deserialization allows validating the incoming data and converting it back into complex types such as querysets and model instances.

How Django does Serialization/Deserialization?

The following snippets is from Django Rest Framework’s documentation:

Serialization

# To get into Django Shell
python manage.py shell

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

# Created a model instance
snippet = Snippet(code='foo = "bar"\n')
snippet.save()

# Converted to Python data object
serializer = SnippetSerializer(snippet)
serializer.data
# {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}

# Converted to JSON string
content = JSONRenderer().render(serializer.data)
content
# b'{"id": 2, "title": "", "code": "print(\\"hello, world\\")\\n", "linenos": false, "language": "python", "style": "friendly"}'

Deserialization

import io

# Convert incoming JSON string into Python object
stream = io.BytesIO(content)
data = JSONParser().parse(stream)

# Validate the data with Serializer
serializer = SnippetSerializer(data=data)
serializer.is_valid()
# True

# Serialized data in Python's OrderedDict
serializer.validated_data
# OrderedDict([('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])

# Save the model instance based on validated data from serializer
serializer.save()
# <Snippet: Snippet object>

# Serialized querysets data
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data
# [OrderedDict([('id', 1), ('title', ''), ('code', 'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', ''), ('code', 'print("hello, world")'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]

References