Tutorial 1: Serialization: Django REST Framework
Tutorial 1: Serialization: Django REST Framework
Tutorial 1: Serialization: Django REST Framework
Tutorial 1: Serialization
Introduction
Setting up a new environment
Getting started
Creating a model to work with
Creating a Serializer class
Working with Serializers
Using ModelSerializers
Writing regular Django views using our Serializer
Testing our first attempt at a Web API
Where are we now
Tutorial 1: Serialization
Introduction
This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce
the various components that make up REST framework, and give you a comprehensive understanding of
how everything fits together.
The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before
getting started. If you just want a quick overview, you should head over to the quickstart documentation
instead.
Note: The code for this tutorial is available in the encode/rest-framework-tutorial repository on GitHub. The
completed implementation is also online as a sandbox version for testing, available here.
Now that we're inside a virtual environment, we can install our package requirements.
https://www.django-rest-framework.org/tutorial/1-serialization/ 1/10
9/20/2019 1 - Serialization - Django REST framework
Note: To exit the virtual environment at any time, just type deactivate . For more information see the venv
documentation.
Getting started
Okay, we're ready to get coding. To get started, let's create a new project to work with.
cd ~
django-admin startproject tutorial
cd tutorial
Once that's done we can create an app that we'll use to create a simple Web API.
We'll need to add our new snippets app and the rest_framework app to INSTALLED_APPS . Let's edit the
tutorial/settings.py file:
INSTALLED_APPS = [
...
'rest_framework',
'snippets.apps.SnippetsConfig',
]
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
class Meta:
ordering = ['created']
We'll also need to create an initial migration for our snippet model, and sync the database for the first time.
class SnippetSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
code = serializers.CharField(style={'base_template': 'textarea.html'})
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
https://www.django-rest-framework.org/tutorial/1-serialization/ 3/10
9/20/2019 1 - Serialization - Django REST framework
The first part of the serializer class defines the fields that get serialized/deserialized. The create() and
update() methods define how fully fledged instances are created or modified when calling
serializer.save()
A serializer class is very similar to a Django Form class, and includes similar validation flags on the various
fields, such as required , max_length and default .
The field flags can also control how the serializer should be displayed in certain circumstances, such as when
rendering to HTML. The {'base_template': 'textarea.html'} flag above is equivalent to using
widget=widgets.Textarea on a Django Form class. This is particularly useful for controlling how the
browsable API should be displayed, as we'll see later in the tutorial.
We can actually also save ourselves some time by using the ModelSerializer class, as we'll see later, but
for now we'll keep our serializer definition explicit.
Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.
We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.
serializer = SnippetSerializer(snippet)
serializer.data
# {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python',
https://www.django-rest-framework.org/tutorial/1-serialization/ 4/10
9/20/2019 1 - Serialization - Django REST framework
At this point we've translated the model instance into Python native datatypes. To finalize the serialization
process we render the data into json .
content = JSONRenderer().render(serializer.data)
content
# b'{"id": 2, "title": "", "code": "print(\\"hello, world\\")\\n", "linenos": false, "language": "py
import io
stream = io.BytesIO(content)
data = JSONParser().parse(stream)
...then we restore those native datatypes into a fully populated object instance.
serializer = SnippetSerializer(data=data)
serializer.is_valid()
# True
serializer.validated_data
# OrderedDict([('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language',
serializer.save()
# <Snippet: Snippet object>
Notice how similar the API is to working with forms. The similarity should become even more apparent when
we start writing views that use our serializer.
We can also serialize querysets instead of model instances. To do so we simply add a many=True flag to the
serializer arguments.
Using ModelSerializers
Our SnippetSerializer class is replicating a lot of information that's also contained in the Snippet model. It
would be nice if we could keep our code a bit more concise.
In the same way that Django provides both Form classes and ModelForm classes, REST framework includes
both Serializer classes, and ModelSerializer classes.
https://www.django-rest-framework.org/tutorial/1-serialization/ 5/10
9/20/2019 1 - Serialization - Django REST framework
Let's look at refactoring our serializer using the ModelSerializer class. Open the file
snippets/serializers.py again, and replace the SnippetSerializer class with the following.
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ['id', 'title', 'code', 'linenos', 'language', 'style']
One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing
its representation. Open the Django shell with python manage.py shell , then try the following:
It's important to remember that ModelSerializer classes don't do anything particularly magical, they are
simply a shortcut for creating serializer classes:
The root of our API is going to be a view that supports listing all the existing snippets, or creating a new
snippet.
@csrf_exempt
def snippet_list(request):
https://www.django-rest-framework.org/tutorial/1-serialization/ 6/10
9/20/2019 1 - Serialization - Django REST framework
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return JsonResponse(serializer.data, safe=False)
Note that because we want to be able to POST to this view from clients that won't have a CSRF token we
need to mark the view as csrf_exempt . This isn't something that you'd normally want to do, and REST
framework views actually use more sensible behavior than this, but it'll do for our purposes right now.
We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or
delete the snippet.
@csrf_exempt
def snippet_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = SnippetSerializer(snippet)
return JsonResponse(serializer.data)
Finally we need to wire these views up. Create the snippets/urls.py file:
https://www.django-rest-framework.org/tutorial/1-serialization/ 7/10
9/20/2019 1 - Serialization - Django REST framework
urlpatterns = [
path('snippets/', views.snippet_list),
path('snippets/<int:pk>/', views.snippet_detail),
]
We also need to wire up the root urlconf, in the tutorial/urls.py file, to include our snippet app's URLs.
urlpatterns = [
path('', include('snippets.urls')),
]
It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we
send malformed json , or if a request is made with a method that the view doesn't handle, then we'll end up
with a 500 "server error" response. Still, this'll do for now.
quit()
Validating models...
0 errors found
Django version 1.11, using settings 'tutorial.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
We can test our API using curl or httpie. Httpie is a user friendly http client that's written in Python. Let's
install that.
https://www.django-rest-framework.org/tutorial/1-serialization/ 8/10
9/20/2019 1 - Serialization - Django REST framework
http http://127.0.0.1:8000/snippets/
HTTP/1.1 200 OK
...
[
{
"id": 1,
"title": "",
"code": "foo = \"bar\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
},
{
"id": 2,
"title": "",
"code": "print(\"hello, world\")\n",
"linenos": false,
"language": "python",
"style": "friendly"
}
]
http http://127.0.0.1:8000/snippets/2/
HTTP/1.1 200 OK
...
{
"id": 2,
"title": "",
"code": "print(\"hello, world\")\n",
"linenos": false,
"language": "python",
"style": "friendly"
}
Similarly, you can have the same json displayed by visiting these URLs in a web browser.
We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and
some regular Django views.
Our API views don't do anything particularly special at the moment, beyond serving json responses, and
there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.
We'll see how we can start to improve things in part 2 of the tutorial.
https://www.django-rest-framework.org/tutorial/1-serialization/ 10/10