| 1 |
# Tutorial 1: Serialization |
| 2 |
|
| 3 |
## Introduction |
| 4 |
|
| 5 |
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. |
| 6 |
|
| 7 |
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. |
| 8 |
|
| 9 |
!!! note |
| 10 |
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. |
| 11 |
|
| 12 |
## Setting up a new environment |
| 13 |
|
| 14 |
Before we do anything else we'll create a new virtual environment called `.venv`, using [venv]. This will make sure our package configuration is kept nicely isolated from any other projects we're working on. |
| 15 |
|
| 16 |
=== ":fontawesome-brands-linux: Linux, :fontawesome-brands-apple: macOS" |
| 17 |
|
| 18 |
```bash |
| 19 |
python3 -m venv .venv |
| 20 |
source .venv/bin/activate |
| 21 |
``` |
| 22 |
|
| 23 |
=== ":fontawesome-brands-windows: Windows" |
| 24 |
|
| 25 |
If you use Bash for Windows |
| 26 |
|
| 27 |
```bash |
| 28 |
python3 -m venv .venv |
| 29 |
source .venv\Scripts\activate |
| 30 |
``` |
| 31 |
|
| 32 |
Now that we're inside a virtual environment, we can install our package requirements. |
| 33 |
|
| 34 |
```bash |
| 35 |
pip install django |
| 36 |
pip install djangorestframework |
| 37 |
pip install pygments # We'll be using this for the code highlighting |
| 38 |
``` |
| 39 |
|
| 40 |
!!! tip |
| 41 |
To exit the virtual environment at any time, just type `deactivate`. For more information see the [venv documentation][venv]. |
| 42 |
|
| 43 |
## Getting started |
| 44 |
|
| 45 |
Okay, we're ready to get coding. |
| 46 |
To get started, let's create a new project to work with. |
| 47 |
|
| 48 |
```bash |
| 49 |
cd ~ |
| 50 |
django-admin startproject tutorial |
| 51 |
cd tutorial |
| 52 |
``` |
| 53 |
|
| 54 |
Once that's done we can create an app that we'll use to create a simple Web API. |
| 55 |
|
| 56 |
```bash |
| 57 |
python manage.py startapp snippets |
| 58 |
``` |
| 59 |
|
| 60 |
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: |
| 61 |
|
| 62 |
```text |
| 63 |
INSTALLED_APPS = [ |
| 64 |
... |
| 65 |
'rest_framework', |
| 66 |
'snippets', |
| 67 |
] |
| 68 |
``` |
| 69 |
|
| 70 |
Okay, we're ready to roll. |
| 71 |
|
| 72 |
## Creating a model to work with |
| 73 |
|
| 74 |
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. |
| 75 |
|
| 76 |
```python |
| 77 |
from django.db import models |
| 78 |
from pygments.lexers import get_all_lexers |
| 79 |
from pygments.styles import get_all_styles |
| 80 |
|
| 81 |
LEXERS = [item for item in get_all_lexers() if item[1]] |
| 82 |
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) |
| 83 |
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()]) |
| 84 |
|
| 85 |
|
| 86 |
class Snippet(models.Model): |
| 87 |
created = models.DateTimeField(auto_now_add=True) |
| 88 |
title = models.CharField(max_length=100, blank=True, default="") |
| 89 |
code = models.TextField() |
| 90 |
linenos = models.BooleanField(default=False) |
| 91 |
language = models.CharField( |
| 92 |
choices=LANGUAGE_CHOICES, default="python", max_length=100 |
| 93 |
) |
| 94 |
style = models.CharField(choices=STYLE_CHOICES, default="friendly", max_length=100) |
| 95 |
|
| 96 |
class Meta: |
| 97 |
ordering = ["created"] |
| 98 |
``` |
| 99 |
|
| 100 |
We'll also need to create an initial migration for our snippet model, and sync the database for the first time. |
| 101 |
|
| 102 |
```bash |
| 103 |
python manage.py makemigrations snippets |
| 104 |
python manage.py migrate snippets |
| 105 |
``` |
| 106 |
|
| 107 |
## Creating a Serializer class |
| 108 |
|
| 109 |
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. |
| 110 |
|
| 111 |
```python |
| 112 |
from rest_framework import serializers |
| 113 |
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES |
| 114 |
|
| 115 |
|
| 116 |
class SnippetSerializer(serializers.Serializer): |
| 117 |
id = serializers.IntegerField(read_only=True) |
| 118 |
title = serializers.CharField(required=False, allow_blank=True, max_length=100) |
| 119 |
code = serializers.CharField(style={"base_template": "textarea.html"}) |
| 120 |
linenos = serializers.BooleanField(required=False) |
| 121 |
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default="python") |
| 122 |
style = serializers.ChoiceField(choices=STYLE_CHOICES, default="friendly") |
| 123 |
|
| 124 |
def create(self, validated_data): |
| 125 |
""" |
| 126 |
Create and return a new `Snippet` instance, given the validated data. |
| 127 |
""" |
| 128 |
return Snippet.objects.create(**validated_data) |
| 129 |
|
| 130 |
def update(self, instance, validated_data): |
| 131 |
""" |
| 132 |
Update and return an existing `Snippet` instance, given the validated data. |
| 133 |
""" |
| 134 |
instance.title = validated_data.get("title", instance.title) |
| 135 |
instance.code = validated_data.get("code", instance.code) |
| 136 |
instance.linenos = validated_data.get("linenos", instance.linenos) |
| 137 |
instance.language = validated_data.get("language", instance.language) |
| 138 |
instance.style = validated_data.get("style", instance.style) |
| 139 |
instance.save() |
| 140 |
return instance |
| 141 |
``` |
| 142 |
|
| 143 |
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()` |
| 144 |
|
| 145 |
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`. |
| 146 |
|
| 147 |
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. |
| 148 |
|
| 149 |
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. |
| 150 |
|
| 151 |
## Working with Serializers |
| 152 |
|
| 153 |
Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell. |
| 154 |
|
| 155 |
```bash |
| 156 |
python manage.py shell |
| 157 |
``` |
| 158 |
|
| 159 |
Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with. |
| 160 |
|
| 161 |
```pycon |
| 162 |
>>> from snippets.models import Snippet |
| 163 |
>>> from snippets.serializers import SnippetSerializer |
| 164 |
>>> from rest_framework.renderers import JSONRenderer |
| 165 |
>>> from rest_framework.parsers import JSONParser |
| 166 |
|
| 167 |
>>> snippet = Snippet(code='foo = "bar"\n') |
| 168 |
>>> snippet.save() |
| 169 |
|
| 170 |
>>> snippet = Snippet(code='print("hello, world")\n') |
| 171 |
>>> snippet.save() |
| 172 |
``` |
| 173 |
|
| 174 |
We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances. |
| 175 |
|
| 176 |
```pycon |
| 177 |
>>> serializer = SnippetSerializer(snippet) |
| 178 |
>>> serializer.data |
| 179 |
{'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'} |
| 180 |
``` |
| 181 |
|
| 182 |
At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`. |
| 183 |
|
| 184 |
```pycon |
| 185 |
>>> content = JSONRenderer().render(serializer.data) |
| 186 |
>>> content |
| 187 |
b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}' |
| 188 |
``` |
| 189 |
|
| 190 |
Deserialization is similar. First we parse a stream into Python native datatypes... |
| 191 |
|
| 192 |
```pycon |
| 193 |
>>> import io |
| 194 |
|
| 195 |
>>> stream = io.BytesIO(content) |
| 196 |
>>> data = JSONParser().parse(stream) |
| 197 |
``` |
| 198 |
|
| 199 |
...then we restore those native datatypes into a fully populated object instance. |
| 200 |
|
| 201 |
```pycon |
| 202 |
>>> serializer = SnippetSerializer(data=data) |
| 203 |
>>> serializer.is_valid() |
| 204 |
True |
| 205 |
>>> serializer.validated_data |
| 206 |
{'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'} |
| 207 |
>>> serializer.save() |
| 208 |
<Snippet: Snippet object> |
| 209 |
``` |
| 210 |
|
| 211 |
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. |
| 212 |
|
| 213 |
We can also serialize querysets instead of model instances. To do so we simply add a `many=True` flag to the serializer arguments. |
| 214 |
|
| 215 |
```pycon |
| 216 |
>>> serializer = SnippetSerializer(Snippet.objects.all(), many=True) |
| 217 |
>>> serializer.data |
| 218 |
[{'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'}] |
| 219 |
``` |
| 220 |
|
| 221 |
## Using ModelSerializers |
| 222 |
|
| 223 |
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. |
| 224 |
|
| 225 |
In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes. |
| 226 |
|
| 227 |
Let's look at refactoring our serializer using the `ModelSerializer` class. |
| 228 |
Open the file `snippets/serializers.py` again, and replace the `SnippetSerializer` class with the following. |
| 229 |
|
| 230 |
```python |
| 231 |
from rest_framework import serializers |
| 232 |
from snippets.models import Snippet |
| 233 |
|
| 234 |
|
| 235 |
class SnippetSerializer(serializers.ModelSerializer): |
| 236 |
class Meta: |
| 237 |
model = Snippet |
| 238 |
fields = ["id", "title", "code", "linenos", "language", "style"] |
| 239 |
``` |
| 240 |
|
| 241 |
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: |
| 242 |
|
| 243 |
```pycon |
| 244 |
>>> from snippets.serializers import SnippetSerializer |
| 245 |
|
| 246 |
>>> serializer = SnippetSerializer() |
| 247 |
>>> print(repr(serializer)) |
| 248 |
SnippetSerializer(): |
| 249 |
id = IntegerField(label='ID', read_only=True) |
| 250 |
title = CharField(allow_blank=True, max_length=100, required=False) |
| 251 |
code = CharField(style={'base_template': 'textarea.html'}) |
| 252 |
linenos = BooleanField(required=False) |
| 253 |
language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')... |
| 254 |
style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')... |
| 255 |
``` |
| 256 |
|
| 257 |
It's important to remember that `ModelSerializer` classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes: |
| 258 |
|
| 259 |
* An automatically determined set of fields. |
| 260 |
* Simple default implementations for the `create()` and `update()` methods. |
| 261 |
|
| 262 |
## Writing regular Django views using our Serializer |
| 263 |
|
| 264 |
Let's see how we can write some API views using our new Serializer class. |
| 265 |
For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views. |
| 266 |
|
| 267 |
Edit the `snippets/views.py` file, and add the following. |
| 268 |
|
| 269 |
```python |
| 270 |
from django.http import HttpResponse, JsonResponse |
| 271 |
from django.views.decorators.csrf import csrf_exempt |
| 272 |
from rest_framework.parsers import JSONParser |
| 273 |
from snippets.models import Snippet |
| 274 |
from snippets.serializers import SnippetSerializer |
| 275 |
``` |
| 276 |
|
| 277 |
The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet. |
| 278 |
|
| 279 |
```python |
| 280 |
@csrf_exempt |
| 281 |
def snippet_list(request): |
| 282 |
""" |
| 283 |
List all code snippets, or create a new snippet. |
| 284 |
""" |
| 285 |
if request.method == "GET": |
| 286 |
snippets = Snippet.objects.all() |
| 287 |
serializer = SnippetSerializer(snippets, many=True) |
| 288 |
return JsonResponse(serializer.data, safe=False) |
| 289 |
|
| 290 |
elif request.method == "POST": |
| 291 |
data = JSONParser().parse(request) |
| 292 |
serializer = SnippetSerializer(data=data) |
| 293 |
if serializer.is_valid(): |
| 294 |
serializer.save() |
| 295 |
return JsonResponse(serializer.data, status=201) |
| 296 |
return JsonResponse(serializer.errors, status=400) |
| 297 |
``` |
| 298 |
|
| 299 |
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. |
| 300 |
|
| 301 |
We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet. |
| 302 |
|
| 303 |
```python |
| 304 |
@csrf_exempt |
| 305 |
def snippet_detail(request, pk): |
| 306 |
""" |
| 307 |
Retrieve, update or delete a code snippet. |
| 308 |
""" |
| 309 |
try: |
| 310 |
snippet = Snippet.objects.get(pk=pk) |
| 311 |
except Snippet.DoesNotExist: |
| 312 |
return HttpResponse(status=404) |
| 313 |
|
| 314 |
if request.method == "GET": |
| 315 |
serializer = SnippetSerializer(snippet) |
| 316 |
return JsonResponse(serializer.data) |
| 317 |
|
| 318 |
elif request.method == "PUT": |
| 319 |
data = JSONParser().parse(request) |
| 320 |
serializer = SnippetSerializer(snippet, data=data) |
| 321 |
if serializer.is_valid(): |
| 322 |
serializer.save() |
| 323 |
return JsonResponse(serializer.data) |
| 324 |
return JsonResponse(serializer.errors, status=400) |
| 325 |
|
| 326 |
elif request.method == "DELETE": |
| 327 |
snippet.delete() |
| 328 |
return HttpResponse(status=204) |
| 329 |
``` |
| 330 |
|
| 331 |
Finally we need to wire these views up. Create the `snippets/urls.py` file: |
| 332 |
|
| 333 |
```python |
| 334 |
from django.urls import path |
| 335 |
from snippets import views |
| 336 |
|
| 337 |
urlpatterns = [ |
| 338 |
path("snippets/", views.snippet_list), |
| 339 |
path("snippets/<int:pk>/", views.snippet_detail), |
| 340 |
] |
| 341 |
``` |
| 342 |
|
| 343 |
We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs. |
| 344 |
|
| 345 |
```python |
| 346 |
from django.urls import path, include |
| 347 |
|
| 348 |
urlpatterns = [ |
| 349 |
path("", include("snippets.urls")), |
| 350 |
] |
| 351 |
``` |
| 352 |
|
| 353 |
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. |
| 354 |
|
| 355 |
## Testing our first attempt at a Web API |
| 356 |
|
| 357 |
Now we can start up a sample server that serves our snippets. |
| 358 |
|
| 359 |
Quit out of the shell... |
| 360 |
|
| 361 |
```pycon |
| 362 |
>>> quit() |
| 363 |
``` |
| 364 |
|
| 365 |
...and start up Django's development server. |
| 366 |
|
| 367 |
```bash |
| 368 |
python manage.py runserver |
| 369 |
|
| 370 |
Validating models... |
| 371 |
|
| 372 |
0 errors found |
| 373 |
Django version 5.0, using settings 'tutorial.settings' |
| 374 |
Starting Development server at http://127.0.0.1:8000/ |
| 375 |
Quit the server with CONTROL-C. |
| 376 |
``` |
| 377 |
|
| 378 |
In another terminal window, we can test the server. |
| 379 |
|
| 380 |
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. |
| 381 |
|
| 382 |
You can install HTTPie using pip: |
| 383 |
|
| 384 |
```bash |
| 385 |
pip install httpie |
| 386 |
``` |
| 387 |
|
| 388 |
Finally, we can get a list of all of the snippets: |
| 389 |
|
| 390 |
```bash |
| 391 |
http GET http://127.0.0.1:8000/snippets/ --unsorted |
| 392 |
|
| 393 |
HTTP/1.1 200 OK |
| 394 |
... |
| 395 |
[ |
| 396 |
{ |
| 397 |
"id": 1, |
| 398 |
"title": "", |
| 399 |
"code": "foo = \"bar\"\n", |
| 400 |
"linenos": false, |
| 401 |
"language": "python", |
| 402 |
"style": "friendly" |
| 403 |
}, |
| 404 |
{ |
| 405 |
"id": 2, |
| 406 |
"title": "", |
| 407 |
"code": "print(\"hello, world\")\n", |
| 408 |
"linenos": false, |
| 409 |
"language": "python", |
| 410 |
"style": "friendly" |
| 411 |
}, |
| 412 |
{ |
| 413 |
"id": 3, |
| 414 |
"title": "", |
| 415 |
"code": "print(\"hello, world\")", |
| 416 |
"linenos": false, |
| 417 |
"language": "python", |
| 418 |
"style": "friendly" |
| 419 |
} |
| 420 |
] |
| 421 |
``` |
| 422 |
|
| 423 |
Or we can get a particular snippet by referencing its id: |
| 424 |
|
| 425 |
```bash |
| 426 |
http GET http://127.0.0.1:8000/snippets/2/ --unsorted |
| 427 |
|
| 428 |
HTTP/1.1 200 OK |
| 429 |
... |
| 430 |
{ |
| 431 |
"id": 2, |
| 432 |
"title": "", |
| 433 |
"code": "print(\"hello, world\")\n", |
| 434 |
"linenos": false, |
| 435 |
"language": "python", |
| 436 |
"style": "friendly" |
| 437 |
} |
| 438 |
``` |
| 439 |
|
| 440 |
Similarly, you can have the same json displayed by visiting these URLs in a web browser. |
| 441 |
|
| 442 |
## Where are we now |
| 443 |
|
| 444 |
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. |
| 445 |
|
| 446 |
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. |
| 447 |
|
| 448 |
We'll see how we can start to improve things in [part 2 of the tutorial][tut-2]. |
| 449 |
|
| 450 |
[quickstart]: quickstart.md |
| 451 |
[repo]: https://github.com/encode/rest-framework-tutorial |
| 452 |
[venv]: https://docs.python.org/3/library/venv.html |
| 453 |
[tut-2]: 2-requests-and-responses.md |
| 454 |
[HTTPie]: https://github.com/httpie/httpie#installation |
| 455 |
[curl]: https://curl.haxx.se/ |