2012-08-29 23:57:37 +04:00
# Tutorial 1: Serialization
## Introduction
2013-05-28 19:13:12 +04:00
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.
2012-10-28 23:25:51 +04:00
2013-01-28 11:52:22 +04:00
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.
2012-08-29 23:57:37 +04:00
2012-10-30 16:23:17 +04:00
---
2024-04-08 14:26:02 +03:00
**Note**: The code for this tutorial is available in the [encode/rest-framework-tutorial][repo] repository on GitHub. Feel free to clone the repository and see the code in action.
2012-10-30 16:23:17 +04:00
---
2012-09-03 16:10:39 +04:00
## Setting up a new environment
2012-08-29 23:57:37 +04:00
2019-05-01 08:51:02 +03:00
Before we do anything else we'll create a new virtual environment, using [venv]. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.
2012-09-03 15:41:52 +04:00
2019-05-01 08:51:02 +03:00
python3 -m venv env
2014-01-14 21:13:48 +04:00
source env/bin/activate
2012-09-03 15:41:52 +04:00
2019-05-01 08:51:02 +03:00
Now that we're inside a virtual environment, we can install our package requirements.
2012-09-03 15:41:52 +04:00
pip install django
pip install djangorestframework
2012-10-28 23:25:51 +04:00
pip install pygments # We'll be using this for the code highlighting
2012-09-03 15:41:52 +04:00
2019-05-01 08:51:02 +03:00
**Note:** To exit the virtual environment at any time, just type `deactivate` . For more information see the [venv documentation][venv].
2012-09-03 16:10:39 +04:00
## Getting started
Okay, we're ready to get coding.
2012-08-29 23:57:37 +04:00
To get started, let's create a new project to work with.
2012-10-05 18:22:30 +04:00
cd ~
2018-10-03 18:16:52 +03:00
django-admin startproject tutorial
2012-08-29 23:57:37 +04:00
cd tutorial
Once that's done we can create an app that we'll use to create a simple Web API.
2012-10-28 23:25:51 +04:00
python manage.py startapp snippets
2012-08-29 23:57:37 +04:00
2014-10-09 12:38:03 +04:00
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:
2012-08-29 23:57:37 +04:00
2019-07-13 04:15:36 +03:00
INSTALLED_APPS = [
2012-08-29 23:57:37 +04:00
...
2012-09-20 16:06:27 +04:00
'rest_framework',
2022-01-06 16:55:44 +03:00
'snippets',
2019-07-13 04:15:36 +03:00
]
2012-08-29 23:57:37 +04:00
Okay, we're ready to roll.
## Creating a model to work with
2014-10-09 12:38:03 +04:00
For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets/models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
2012-08-29 23:57:37 +04:00
from django.db import models
2012-10-28 23:25:51 +04:00
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
2013-01-15 13:33:24 +04:00
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
2019-07-04 15:41:15 +03:00
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
2014-08-16 06:45:28 +04:00
2012-10-28 23:25:51 +04:00
class Snippet(models.Model):
2012-08-29 23:57:37 +04:00
created = models.DateTimeField(auto_now_add=True)
2013-02-24 01:29:13 +04:00
title = models.CharField(max_length=100, blank=True, default='')
2012-10-28 23:25:51 +04:00
code = models.TextField()
linenos = models.BooleanField(default=False)
2014-12-05 15:46:08 +03:00
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
2014-08-16 06:45:28 +04:00
2012-10-28 23:25:51 +04:00
class Meta:
2019-07-13 04:15:36 +03:00
ordering = ['created']
2012-08-29 23:57:37 +04:00
2014-10-09 12:38:03 +04:00
We'll also need to create an initial migration for our snippet model, and sync the database for the first time.
2012-08-29 23:57:37 +04:00
2014-10-09 12:38:03 +04:00
python manage.py makemigrations snippets
2022-01-06 16:55:44 +03:00
python manage.py migrate snippets
2012-08-29 23:57:37 +04:00
## Creating a Serializer class
2014-05-05 16:41:10 +04:00
The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as `json` . We can do this by declaring serializers that work very similar to Django's forms. Create a file in the `snippets` directory named `serializers.py` and add the following.
2012-08-29 23:57:37 +04:00
2012-09-20 16:06:27 +04:00
from rest_framework import serializers
2013-02-14 15:21:54 +04:00
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
2012-10-28 23:25:51 +04:00
class SnippetSerializer(serializers.Serializer):
2016-10-10 15:03:46 +03:00
id = serializers.IntegerField(read_only=True)
2014-12-05 15:46:08 +03:00
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
2015-02-01 23:18:02 +03:00
code = serializers.CharField(style={'base_template': 'textarea.html'})
2012-10-28 23:25:51 +04:00
linenos = serializers.BooleanField(required=False)
2014-12-05 15:46:08 +03:00
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
2014-08-16 06:45:28 +04:00
2014-12-04 01:52:35 +03:00
def create(self, validated_data):
2012-08-29 23:57:37 +04:00
"""
2014-10-09 12:38:03 +04:00
Create and return a new `Snippet` instance, given the validated data.
"""
2014-12-04 01:52:35 +03:00
return Snippet.objects.create(**validated_data)
2014-08-16 06:45:28 +04:00
2014-12-04 01:52:35 +03:00
def update(self, instance, validated_data):
2014-10-09 12:38:03 +04:00
"""
Update and return an existing `Snippet` instance, given the validated data.
2012-08-29 23:57:37 +04:00
"""
2014-12-04 01:52:35 +03:00
instance.title = validated_data.get('title', instance.title)
instance.code = validated_data.get('code', instance.code)
instance.linenos = validated_data.get('linenos', instance.linenos)
instance.language = validated_data.get('language', instance.language)
instance.style = validated_data.get('style', instance.style)
2014-10-09 12:38:03 +04:00
instance.save()
return instance
2012-10-28 23:25:51 +04:00
2014-10-09 12:38:03 +04:00
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()`
2012-08-29 23:57:37 +04:00
2014-10-09 12:38:03 +04:00
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` .
2012-08-29 23:57:37 +04:00
2015-04-07 19:40:23 +03:00
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.
2013-05-30 14:34:09 +04:00
2014-10-31 20:03:39 +03:00
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.
2012-08-29 23:57:37 +04:00
## Working with Serializers
2012-12-05 15:31:38 +04:00
Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.
2012-08-29 23:57:37 +04:00
python manage.py shell
2013-02-12 12:57:23 +04:00
Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.
2012-08-29 23:57:37 +04:00
2012-10-28 23:25:51 +04:00
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
2012-09-20 16:06:27 +04:00
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
2012-08-29 23:57:37 +04:00
2013-02-12 12:57:23 +04:00
snippet = Snippet(code='foo = "bar"\n')
snippet.save()
2019-02-16 17:47:13 +03:00
snippet = Snippet(code='print("hello, world")\n')
2012-10-28 23:25:51 +04:00
snippet.save()
2012-08-29 23:57:37 +04:00
2012-10-28 23:25:51 +04:00
We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.
2012-08-29 23:57:37 +04:00
2012-11-05 14:53:20 +04:00
serializer = SnippetSerializer(snippet)
2012-08-29 23:57:37 +04:00
serializer.data
2019-02-16 17:47:13 +03:00
# {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
2012-08-29 23:57:37 +04:00
2013-06-13 00:53:39 +04:00
At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json` .
2012-08-29 23:57:37 +04:00
2012-10-18 01:07:56 +04:00
content = JSONRenderer().render(serializer.data)
content
2024-06-02 07:14:37 +03:00
# b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}'
2012-08-29 23:57:37 +04:00
2014-08-16 06:45:28 +04:00
Deserialization is similar. First we parse a stream into Python native datatypes...
2012-08-29 23:57:37 +04:00
2018-09-09 13:53:41 +03:00
import io
2012-10-18 01:07:56 +04:00
2018-09-09 13:53:41 +03:00
stream = io.BytesIO(content)
2012-08-29 23:57:37 +04:00
data = JSONParser().parse(stream)
2016-02-03 12:55:31 +03:00
...then we restore those native datatypes into a fully populated object instance.
2012-08-29 23:57:37 +04:00
2012-11-05 14:53:20 +04:00
serializer = SnippetSerializer(data=data)
2012-08-29 23:57:37 +04:00
serializer.is_valid()
# True
2014-12-05 15:48:12 +03:00
serializer.validated_data
2024-06-02 07:14:37 +03:00
# {'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}
2014-12-05 01:34:55 +03:00
serializer.save()
2012-10-28 23:25:51 +04:00
# < Snippet: Snippet object >
2014-08-16 06:45:28 +04:00
2012-08-29 23:57:37 +04:00
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.
2013-02-12 12:57:23 +04:00
We can also serialize querysets instead of model instances. To do so we simply add a `many=True` flag to the serializer arguments.
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data
2024-06-02 07:14:37 +03:00
# [{'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'}, {'id': 3, 'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}]
2013-02-12 12:57:23 +04:00
2012-10-28 23:25:51 +04:00
## Using ModelSerializers
2022-10-19 13:20:11 +03:00
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.
2012-10-28 23:25:51 +04:00
In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes.
Let's look at refactoring our serializer using the `ModelSerializer` class.
2015-01-09 22:36:21 +03:00
Open the file `snippets/serializers.py` again, and replace the `SnippetSerializer` class with the following.
2012-10-28 23:25:51 +04:00
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
2012-10-30 16:50:07 +04:00
model = Snippet
2019-07-13 04:15:36 +03:00
fields = ['id', 'title', 'code', 'linenos', 'language', 'style']
2012-10-28 23:25:51 +04:00
2015-01-20 01:49:36 +03:00
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:
2014-10-09 12:38:03 +04:00
2016-01-03 00:15:25 +03:00
from snippets.serializers import SnippetSerializer
serializer = SnippetSerializer()
print(repr(serializer))
# SnippetSerializer():
# id = IntegerField(label='ID', read_only=True)
# title = CharField(allow_blank=True, max_length=100, required=False)
# code = CharField(style={'base_template': 'textarea.html'})
# linenos = BooleanField(required=False)
# language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...
# style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...
2014-10-09 12:38:03 +04:00
2014-11-26 18:51:28 +03:00
It's important to remember that `ModelSerializer` classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes:
2014-10-09 12:38:03 +04:00
* An automatically determined set of fields.
* Simple default implementations for the `create()` and `update()` methods.
2012-10-28 23:25:51 +04:00
## Writing regular Django views using our Serializer
2012-08-29 23:57:37 +04:00
Let's see how we can write some API views using our new Serializer class.
2012-10-28 23:25:51 +04:00
For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.
2013-10-06 03:29:25 +04:00
Edit the `snippets/views.py` file, and add the following.
2012-08-29 23:57:37 +04:00
2017-03-03 17:04:41 +03:00
from django.http import HttpResponse, JsonResponse
2012-09-25 15:27:46 +04:00
from django.views.decorators.csrf import csrf_exempt
2012-09-20 16:06:27 +04:00
from rest_framework.parsers import JSONParser
2012-10-28 23:25:51 +04:00
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
2012-08-29 23:57:37 +04:00
2012-10-28 23:25:51 +04:00
The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.
2012-08-29 23:57:37 +04:00
2012-09-25 15:27:46 +04:00
@csrf_exempt
2012-10-28 23:25:51 +04:00
def snippet_list(request):
2012-08-29 23:57:37 +04:00
"""
2012-10-28 23:25:51 +04:00
List all code snippets, or create a new snippet.
2012-08-29 23:57:37 +04:00
"""
if request.method == 'GET':
2012-10-28 23:25:51 +04:00
snippets = Snippet.objects.all()
2013-02-12 12:57:23 +04:00
serializer = SnippetSerializer(snippets, many=True)
2017-03-03 17:04:41 +03:00
return JsonResponse(serializer.data, safe=False)
2012-08-29 23:57:37 +04:00
elif request.method == 'POST':
data = JSONParser().parse(request)
2012-11-05 14:53:20 +04:00
serializer = SnippetSerializer(data=data)
2012-08-29 23:57:37 +04:00
if serializer.is_valid():
2012-10-28 23:25:51 +04:00
serializer.save()
2017-03-03 17:04:41 +03:00
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
2012-08-29 23:57:37 +04:00
2014-08-16 06:45:28 +04:00
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.
2012-09-25 15:27:46 +04:00
2012-10-28 23:25:51 +04:00
We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.
2012-08-29 23:57:37 +04:00
2012-09-25 15:27:46 +04:00
@csrf_exempt
2016-10-20 11:42:40 +03:00
def snippet_detail(request, pk):
2012-08-29 23:57:37 +04:00
"""
2012-10-28 23:25:51 +04:00
Retrieve, update or delete a code snippet.
2012-08-29 23:57:37 +04:00
"""
try:
2016-10-20 11:42:40 +03:00
snippet = Snippet.objects.get(pk=pk)
2012-10-28 23:25:51 +04:00
except Snippet.DoesNotExist:
2012-08-29 23:57:37 +04:00
return HttpResponse(status=404)
2014-08-16 06:45:28 +04:00
2012-08-29 23:57:37 +04:00
if request.method == 'GET':
2012-11-05 14:53:20 +04:00
serializer = SnippetSerializer(snippet)
2017-03-03 17:04:41 +03:00
return JsonResponse(serializer.data)
2014-08-16 06:45:28 +04:00
2012-08-29 23:57:37 +04:00
elif request.method == 'PUT':
data = JSONParser().parse(request)
2012-11-05 14:53:20 +04:00
serializer = SnippetSerializer(snippet, data=data)
2012-08-29 23:57:37 +04:00
if serializer.is_valid():
2012-10-28 23:25:51 +04:00
serializer.save()
2017-03-03 17:04:41 +03:00
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
2012-08-29 23:57:37 +04:00
elif request.method == 'DELETE':
2012-10-28 23:25:51 +04:00
snippet.delete()
2012-08-29 23:57:37 +04:00
return HttpResponse(status=204)
2013-05-28 19:13:12 +04:00
Finally we need to wire these views up. Create the `snippets/urls.py` file:
2012-08-29 23:57:37 +04:00
2018-05-08 11:06:14 +03:00
from django.urls import path
2014-09-24 01:08:38 +04:00
from snippets import views
2012-08-29 23:57:37 +04:00
2014-09-24 01:08:38 +04:00
urlpatterns = [
2018-05-08 11:06:14 +03:00
path('snippets/', views.snippet_list),
path('snippets/< int:pk > /', views.snippet_detail),
2014-09-24 01:08:38 +04:00
]
2016-02-25 16:27:57 +03:00
2015-12-16 05:17:52 +03:00
We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs.
2016-02-25 16:27:57 +03:00
2018-05-08 11:06:14 +03:00
from django.urls import path, include
2016-02-25 16:27:57 +03:00
2015-12-16 05:17:52 +03:00
urlpatterns = [
2018-05-08 11:06:14 +03:00
path('', include('snippets.urls')),
2015-12-16 05:17:52 +03:00
]
2012-08-29 23:57:37 +04:00
2012-12-05 15:31:38 +04:00
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.
2012-08-29 23:57:37 +04:00
## Testing our first attempt at a Web API
2013-01-09 21:19:12 +04:00
Now we can start up a sample server that serves our snippets.
2012-08-29 23:57:37 +04:00
2013-02-24 01:52:26 +04:00
Quit out of the shell...
2013-01-09 21:19:12 +04:00
2018-07-06 12:28:18 +03:00
quit()
2013-01-09 21:19:12 +04:00
2013-02-24 01:52:26 +04:00
...and start up Django's development server.
2013-01-09 21:19:12 +04:00
2018-07-06 12:28:18 +03:00
python manage.py runserver
2013-01-09 21:19:12 +04:00
2018-07-06 12:28:18 +03:00
Validating models...
2013-01-09 21:19:12 +04:00
2018-07-06 12:28:18 +03:00
0 errors found
2024-04-08 14:26:02 +03:00
Django version 5.0, using settings 'tutorial.settings'
2022-01-06 16:55:44 +03:00
Starting Development server at http://127.0.0.1:8000/
2018-07-06 12:28:18 +03:00
Quit the server with CONTROL-C.
2013-01-09 21:19:12 +04:00
In another terminal window, we can test the server.
2016-02-25 21:32:38 +03:00
We can test our API using [curl][curl] or [httpie][httpie]. Httpie is a user friendly http client that's written in Python. Let's install that.
2013-01-09 21:19:12 +04:00
2014-12-04 14:20:33 +03:00
You can install httpie using pip:
2013-01-09 21:19:12 +04:00
2014-12-01 16:39:53 +03:00
pip install httpie
2013-01-09 21:19:12 +04:00
2014-12-01 16:39:53 +03:00
Finally, we can get a list of all of the snippets:
2024-06-02 07:14:37 +03:00
http http://127.0.0.1:8000/snippets/ --unsorted
2014-12-01 16:39:53 +03:00
2014-12-08 18:41:01 +03:00
HTTP/1.1 200 OK
...
[
2024-06-02 07:14:37 +03:00
{
"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"
},
{
"id": 3,
"title": "",
"code": "print(\"hello, world\")",
"linenos": false,
"language": "python",
"style": "friendly"
}
2014-12-01 16:39:53 +03:00
]
2013-01-09 21:19:12 +04:00
2014-12-01 16:39:53 +03:00
Or we can get a particular snippet by referencing its id:
2013-01-09 21:19:12 +04:00
2024-06-02 07:14:37 +03:00
http http://127.0.0.1:8000/snippets/2/ --unsorted
2013-01-09 21:19:12 +04:00
2014-12-04 14:20:33 +03:00
HTTP/1.1 200 OK
...
2014-12-08 18:41:01 +03:00
{
2024-06-02 07:14:37 +03:00
"id": 2,
"title": "",
"code": "print(\"hello, world\")\n",
"linenos": false,
"language": "python",
"style": "friendly"
2014-12-01 16:39:53 +03:00
}
2013-01-09 21:19:12 +04:00
2013-02-12 12:57:23 +04:00
Similarly, you can have the same json displayed by visiting these URLs in a web browser.
2012-08-29 23:57:37 +04:00
## Where are we now
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.
2012-12-05 15:31:38 +04:00
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.
2012-08-29 23:57:37 +04:00
2012-09-03 15:41:52 +04:00
We'll see how we can start to improve things in [part 2 of the tutorial][tut-2].
2012-08-29 23:57:37 +04:00
2012-10-28 23:25:51 +04:00
[quickstart]: quickstart.md
2017-04-07 17:28:35 +03:00
[repo]: https://github.com/encode/rest-framework-tutorial
2019-05-01 08:51:02 +03:00
[venv]: https://docs.python.org/3/library/venv.html
2012-09-20 16:06:27 +04:00
[tut-2]: 2-requests-and-responses.md
2021-08-06 18:49:41 +03:00
[httpie]: https://github.com/httpie/httpie#installation
2018-01-08 18:22:32 +03:00
[curl]: https://curl.haxx.se/