docs: Add syntax highlighting to code examples (#9794)

This commit is contained in:
Syed Mehdi 2025-10-14 11:31:35 +05:30 committed by GitHub
parent 9cf6efb4a8
commit c0f3649224
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 898 additions and 703 deletions

View File

@ -16,14 +16,18 @@ The tutorial is fairly in-depth, so you should probably get a cookie and a cup o
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. 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.
```bash
python3 -m venv env python3 -m venv env
source env/bin/activate source env/bin/activate
```
Now that we're inside a virtual environment, we can install our package requirements. Now that we're inside a virtual environment, we can install our package requirements.
```bash
pip install django pip install django
pip install djangorestframework pip install djangorestframework
pip install pygments # We'll be using this for the code highlighting pip install pygments # We'll be using this for the code highlighting
```
**Note:** To exit the virtual environment at any time, just type `deactivate`. For more information see the [venv documentation][venv]. **Note:** To exit the virtual environment at any time, just type `deactivate`. For more information see the [venv documentation][venv].
@ -32,21 +36,27 @@ Now that we're inside a virtual environment, we can install our package requirem
Okay, we're ready to get coding. Okay, we're ready to get coding.
To get started, let's create a new project to work with. To get started, let's create a new project to work with.
```bash
cd ~ cd ~
django-admin startproject tutorial django-admin startproject tutorial
cd tutorial cd tutorial
```
Once that's done we can create an app that we'll use to create a simple Web API. Once that's done we can create an app that we'll use to create a simple Web API.
```bash
python manage.py startapp snippets python manage.py startapp snippets
```
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: 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:
```text
INSTALLED_APPS = [ INSTALLED_APPS = [
... ...
'rest_framework', 'rest_framework',
'snippets', 'snippets',
] ]
```
Okay, we're ready to roll. Okay, we're ready to roll.
@ -54,6 +64,7 @@ Okay, we're ready to roll.
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. 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.
```python
from django.db import models from django.db import models
from pygments.lexers import get_all_lexers from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles from pygments.styles import get_all_styles
@ -65,24 +76,30 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni
class Snippet(models.Model): class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='') title = models.CharField(max_length=100, blank=True, default="")
code = models.TextField() code = models.TextField()
linenos = models.BooleanField(default=False) linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) language = models.CharField(
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) choices=LANGUAGE_CHOICES, default="python", max_length=100
)
style = models.CharField(choices=STYLE_CHOICES, default="friendly", max_length=100)
class Meta: class Meta:
ordering = ['created'] ordering = ["created"]
```
We'll also need to create an initial migration for our snippet model, and sync the database for the first time. We'll also need to create an initial migration for our snippet model, and sync the database for the first time.
```bash
python manage.py makemigrations snippets python manage.py makemigrations snippets
python manage.py migrate snippets python manage.py migrate snippets
```
## Creating a Serializer class ## Creating a Serializer class
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. 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.
```python
from rest_framework import serializers from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
@ -90,10 +107,10 @@ The first thing we need to get started on our Web API is to provide a way of ser
class SnippetSerializer(serializers.Serializer): class SnippetSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True) id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=False, allow_blank=True, max_length=100) title = serializers.CharField(required=False, allow_blank=True, max_length=100)
code = serializers.CharField(style={'base_template': 'textarea.html'}) code = serializers.CharField(style={"base_template": "textarea.html"})
linenos = serializers.BooleanField(required=False) linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default="python")
style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') style = serializers.ChoiceField(choices=STYLE_CHOICES, default="friendly")
def create(self, validated_data): def create(self, validated_data):
""" """
@ -105,13 +122,14 @@ The first thing we need to get started on our Web API is to provide a way of ser
""" """
Update and return an existing `Snippet` instance, given the validated data. Update and return an existing `Snippet` instance, given the validated data.
""" """
instance.title = validated_data.get('title', instance.title) instance.title = validated_data.get("title", instance.title)
instance.code = validated_data.get('code', instance.code) instance.code = validated_data.get("code", instance.code)
instance.linenos = validated_data.get('linenos', instance.linenos) instance.linenos = validated_data.get("linenos", instance.linenos)
instance.language = validated_data.get('language', instance.language) instance.language = validated_data.get("language", instance.language)
instance.style = validated_data.get('style', instance.style) instance.style = validated_data.get("style", instance.style)
instance.save() instance.save()
return instance return instance
```
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()` 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()`
@ -125,57 +143,71 @@ We can actually also save ourselves some time by using the `ModelSerializer` cla
Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell. Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.
```bash
python manage.py shell python manage.py shell
```
Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with. Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.
from snippets.models import Snippet ```pycon
from snippets.serializers import SnippetSerializer >>> from snippets.models import Snippet
from rest_framework.renderers import JSONRenderer >>> from snippets.serializers import SnippetSerializer
from rest_framework.parsers import JSONParser >>> from rest_framework.renderers import JSONRenderer
>>> from rest_framework.parsers import JSONParser
snippet = Snippet(code='foo = "bar"\n') >>> snippet = Snippet(code='foo = "bar"\n')
snippet.save() >>> snippet.save()
snippet = Snippet(code='print("hello, world")\n') >>> snippet = Snippet(code='print("hello, world")\n')
snippet.save() >>> snippet.save()
```
We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances. 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) ```pycon
serializer.data >>> serializer = SnippetSerializer(snippet)
# {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'} >>> serializer.data
{'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
```
At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`. 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) ```pycon
content >>> content = JSONRenderer().render(serializer.data)
# b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}' >>> content
b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}'
```
Deserialization is similar. First we parse a stream into Python native datatypes... Deserialization is similar. First we parse a stream into Python native datatypes...
import io ```pycon
>>> import io
stream = io.BytesIO(content) >>> stream = io.BytesIO(content)
data = JSONParser().parse(stream) >>> data = JSONParser().parse(stream)
```
...then we restore those native datatypes into a fully populated object instance. ...then we restore those native datatypes into a fully populated object instance.
serializer = SnippetSerializer(data=data) ```pycon
serializer.is_valid() >>> serializer = SnippetSerializer(data=data)
# True >>> serializer.is_valid()
serializer.validated_data True
# {'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'} >>> serializer.validated_data
serializer.save() {'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}
# <Snippet: Snippet object> >>> 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. 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. 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) ```pycon
serializer.data >>> serializer = SnippetSerializer(Snippet.objects.all(), many=True)
# [{'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'}] >>> serializer.data
[{'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'}]
```
## Using ModelSerializers ## Using ModelSerializers
@ -186,23 +218,28 @@ In the same way that Django provides both `Form` classes and `ModelForm` classes
Let's look at refactoring our serializer using the `ModelSerializer` class. 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. Open the file `snippets/serializers.py` again, and replace the `SnippetSerializer` class with the following.
```python
class SnippetSerializer(serializers.ModelSerializer): class SnippetSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = Snippet model = Snippet
fields = ['id', 'title', 'code', 'linenos', 'language', 'style'] 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: 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:
from snippets.serializers import SnippetSerializer ```pycon
serializer = SnippetSerializer() >>> from snippets.serializers import SnippetSerializer
print(repr(serializer))
# SnippetSerializer(): >>> serializer = SnippetSerializer()
# id = IntegerField(label='ID', read_only=True) >>> print(repr(serializer))
# title = CharField(allow_blank=True, max_length=100, required=False) SnippetSerializer():
# code = CharField(style={'base_template': 'textarea.html'}) id = IntegerField(label='ID', read_only=True)
# linenos = BooleanField(required=False) title = CharField(allow_blank=True, max_length=100, required=False)
# language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')... code = CharField(style={'base_template': 'textarea.html'})
# style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')... 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')...
```
It's important to remember that `ModelSerializer` classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes: It's important to remember that `ModelSerializer` classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes:
@ -216,36 +253,41 @@ For the moment we won't use any of REST framework's other features, we'll just w
Edit the `snippets/views.py` file, and add the following. Edit the `snippets/views.py` file, and add the following.
```python
from django.http import HttpResponse, JsonResponse from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser from rest_framework.parsers import JSONParser
from snippets.models import Snippet from snippets.models import Snippet
from snippets.serializers import SnippetSerializer from snippets.serializers import SnippetSerializer
```
The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet. The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.
```python
@csrf_exempt @csrf_exempt
def snippet_list(request): def snippet_list(request):
""" """
List all code snippets, or create a new snippet. List all code snippets, or create a new snippet.
""" """
if request.method == 'GET': if request.method == "GET":
snippets = Snippet.objects.all() snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True) serializer = SnippetSerializer(snippets, many=True)
return JsonResponse(serializer.data, safe=False) return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST': elif request.method == "POST":
data = JSONParser().parse(request) data = JSONParser().parse(request)
serializer = SnippetSerializer(data=data) serializer = SnippetSerializer(data=data)
if serializer.is_valid(): if serializer.is_valid():
serializer.save() serializer.save()
return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400) return JsonResponse(serializer.errors, status=400)
```
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. 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. We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.
```python
@csrf_exempt @csrf_exempt
def snippet_detail(request, pk): def snippet_detail(request, pk):
""" """
@ -256,11 +298,11 @@ We'll also need a view which corresponds to an individual snippet, and can be us
except Snippet.DoesNotExist: except Snippet.DoesNotExist:
return HttpResponse(status=404) return HttpResponse(status=404)
if request.method == 'GET': if request.method == "GET":
serializer = SnippetSerializer(snippet) serializer = SnippetSerializer(snippet)
return JsonResponse(serializer.data) return JsonResponse(serializer.data)
elif request.method == 'PUT': elif request.method == "PUT":
data = JSONParser().parse(request) data = JSONParser().parse(request)
serializer = SnippetSerializer(snippet, data=data) serializer = SnippetSerializer(snippet, data=data)
if serializer.is_valid(): if serializer.is_valid():
@ -268,27 +310,32 @@ We'll also need a view which corresponds to an individual snippet, and can be us
return JsonResponse(serializer.data) return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400) return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE': elif request.method == "DELETE":
snippet.delete() snippet.delete()
return HttpResponse(status=204) return HttpResponse(status=204)
```
Finally we need to wire these views up. Create the `snippets/urls.py` file: Finally we need to wire these views up. Create the `snippets/urls.py` file:
```python
from django.urls import path from django.urls import path
from snippets import views from snippets import views
urlpatterns = [ urlpatterns = [
path('snippets/', views.snippet_list), path("snippets/", views.snippet_list),
path('snippets/<int:pk>/', views.snippet_detail), 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. We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs.
```python
from django.urls import path, include from django.urls import path, include
urlpatterns = [ urlpatterns = [
path('', include('snippets.urls')), 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. 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.
@ -298,10 +345,13 @@ Now we can start up a sample server that serves our snippets.
Quit out of the shell... Quit out of the shell...
quit() ```pycon
>>> quit()
```
...and start up Django's development server. ...and start up Django's development server.
```bash
python manage.py runserver python manage.py runserver
Validating models... Validating models...
@ -310,6 +360,7 @@ Quit out of the shell...
Django version 5.0, using settings 'tutorial.settings' Django version 5.0, using settings 'tutorial.settings'
Starting Development server at http://127.0.0.1:8000/ Starting Development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C. Quit the server with CONTROL-C.
```
In another terminal window, we can test the server. In another terminal window, we can test the server.
@ -317,10 +368,13 @@ We can test our API using [curl][curl] or [httpie][httpie]. Httpie is a user fri
You can install httpie using pip: You can install httpie using pip:
```bash
pip install httpie pip install httpie
```
Finally, we can get a list of all of the snippets: Finally, we can get a list of all of the snippets:
```bash
http GET http://127.0.0.1:8000/snippets/ --unsorted http GET http://127.0.0.1:8000/snippets/ --unsorted
HTTP/1.1 200 OK HTTP/1.1 200 OK
@ -351,9 +405,11 @@ Finally, we can get a list of all of the snippets:
"style": "friendly" "style": "friendly"
} }
] ]
```
Or we can get a particular snippet by referencing its id: Or we can get a particular snippet by referencing its id:
```bash
http GET http://127.0.0.1:8000/snippets/2/ --unsorted http GET http://127.0.0.1:8000/snippets/2/ --unsorted
HTTP/1.1 200 OK HTTP/1.1 200 OK
@ -366,6 +422,7 @@ Or we can get a particular snippet by referencing its id:
"language": "python", "language": "python",
"style": "friendly" "style": "friendly"
} }
```
Similarly, you can have the same json displayed by visiting these URLs in a web browser. Similarly, you can have the same json displayed by visiting these URLs in a web browser.

View File

@ -7,14 +7,18 @@ Let's introduce a couple of essential building blocks.
REST framework introduces a `Request` object that extends the regular `HttpRequest`, and provides more flexible request parsing. The core functionality of the `Request` object is the `request.data` attribute, which is similar to `request.POST`, but more useful for working with Web APIs. REST framework introduces a `Request` object that extends the regular `HttpRequest`, and provides more flexible request parsing. The core functionality of the `Request` object is the `request.data` attribute, which is similar to `request.POST`, but more useful for working with Web APIs.
```python
request.POST # Only handles form data. Only works for 'POST' method. request.POST # Only handles form data. Only works for 'POST' method.
request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods. request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
```
## Response objects ## Response objects
REST framework also introduces a `Response` object, which is a type of `TemplateResponse` that takes unrendered content and uses content negotiation to determine the correct content type to return to the client. REST framework also introduces a `Response` object, which is a type of `TemplateResponse` that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.
```python
return Response(data) # Renders to content type as requested by the client. return Response(data) # Renders to content type as requested by the client.
```
## Status codes ## Status codes
@ -35,6 +39,7 @@ The wrappers also provide behavior such as returning `405 Method Not Allowed` re
Okay, let's go ahead and start using these new components to refactor our views slightly. Okay, let's go ahead and start using these new components to refactor our views slightly.
```python
from rest_framework import status from rest_framework import status
from rest_framework.decorators import api_view from rest_framework.decorators import api_view
from rest_framework.response import Response from rest_framework.response import Response
@ -42,28 +47,30 @@ Okay, let's go ahead and start using these new components to refactor our views
from snippets.serializers import SnippetSerializer from snippets.serializers import SnippetSerializer
@api_view(['GET', 'POST']) @api_view(["GET", "POST"])
def snippet_list(request): def snippet_list(request):
""" """
List all code snippets, or create a new snippet. List all code snippets, or create a new snippet.
""" """
if request.method == 'GET': if request.method == "GET":
snippets = Snippet.objects.all() snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True) serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data) return Response(serializer.data)
elif request.method == 'POST': elif request.method == "POST":
serializer = SnippetSerializer(data=request.data) serializer = SnippetSerializer(data=request.data)
if serializer.is_valid(): if serializer.is_valid():
serializer.save() serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
```
Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious. Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.
Here is the view for an individual snippet, in the `views.py` module. Here is the view for an individual snippet, in the `views.py` module.
@api_view(['GET', 'PUT', 'DELETE']) ```python
@api_view(["GET", "PUT", "DELETE"])
def snippet_detail(request, pk): def snippet_detail(request, pk):
""" """
Retrieve, update or delete a code snippet. Retrieve, update or delete a code snippet.
@ -73,20 +80,21 @@ Here is the view for an individual snippet, in the `views.py` module.
except Snippet.DoesNotExist: except Snippet.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND) return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET': if request.method == "GET":
serializer = SnippetSerializer(snippet) serializer = SnippetSerializer(snippet)
return Response(serializer.data) return Response(serializer.data)
elif request.method == 'PUT': elif request.method == "PUT":
serializer = SnippetSerializer(snippet, data=request.data) serializer = SnippetSerializer(snippet, data=request.data)
if serializer.is_valid(): if serializer.is_valid():
serializer.save() serializer.save()
return Response(serializer.data) return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE': elif request.method == "DELETE":
snippet.delete() snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT) return Response(status=status.HTTP_204_NO_CONTENT)
```
This should all feel very familiar - it is not a lot different from working with regular Django views. This should all feel very familiar - it is not a lot different from working with regular Django views.
@ -94,28 +102,27 @@ Notice that we're no longer explicitly tying our requests or responses to a give
## Adding optional format suffixes to our URLs ## Adding optional format suffixes to our URLs
To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [http://example.com/api/items/4.json][json-url]. To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [<http://example.com/api/items/4.json>][json-url].
Start by adding a `format` keyword argument to both of the views, like so. Start by adding a `format` keyword argument to both of the views, like so.
`def snippet_list(request, format=None):`
def snippet_list(request, format=None):
and and
`def snippet_detail(request, pk, format=None):`
def snippet_detail(request, pk, format=None):
Now update the `snippets/urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs. Now update the `snippets/urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs.
```python
from django.urls import path from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views from snippets import views
urlpatterns = [ urlpatterns = [
path('snippets/', views.snippet_list), path("snippets/", views.snippet_list),
path('snippets/<int:pk>/', views.snippet_detail), path("snippets/<int:pk>/", views.snippet_detail),
] ]
urlpatterns = format_suffix_patterns(urlpatterns) urlpatterns = format_suffix_patterns(urlpatterns)
```
We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format. We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.
@ -125,6 +132,7 @@ Go ahead and test the API from the command line, as we did in [tutorial part 1][
We can get a list of all of the snippets, as before. We can get a list of all of the snippets, as before.
```bash
http http://127.0.0.1:8000/snippets/ http http://127.0.0.1:8000/snippets/
HTTP/1.1 200 OK HTTP/1.1 200 OK
@ -147,19 +155,25 @@ We can get a list of all of the snippets, as before.
"style": "friendly" "style": "friendly"
} }
] ]
```
We can control the format of the response that we get back, either by using the `Accept` header: We can control the format of the response that we get back, either by using the `Accept` header:
```bash
http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON
http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML
```
Or by appending a format suffix: Or by appending a format suffix:
```bash
http http://127.0.0.1:8000/snippets.json # JSON suffix http http://127.0.0.1:8000/snippets.json # JSON suffix
http http://127.0.0.1:8000/snippets.api # Browsable API suffix http http://127.0.0.1:8000/snippets.api # Browsable API suffix
```
Similarly, we can control the format of the request that we send, using the `Content-Type` header. Similarly, we can control the format of the request that we send, using the `Content-Type` header.
```bash
# POST using form data # POST using form data
http --form POST http://127.0.0.1:8000/snippets/ code="print(123)" http --form POST http://127.0.0.1:8000/snippets/ code="print(123)"
@ -183,10 +197,11 @@ Similarly, we can control the format of the request that we send, using the `Con
"language": "python", "language": "python",
"style": "friendly" "style": "friendly"
} }
```
If you add a `--debug` switch to the `http` requests above, you will be able to see the request type in request headers. If you add a `--debug` switch to the `http` requests above, you will be able to see the request type in request headers.
Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver]. Now go and open the API in a web browser, by visiting [<http://127.0.0.1:8000/snippets/>][devserver].
### Browsability ### Browsability

View File

@ -6,6 +6,7 @@ We can also write our API views using class-based views, rather than function ba
We'll start by rewriting the root view as a class-based view. All this involves is a little bit of refactoring of `views.py`. We'll start by rewriting the root view as a class-based view. All this involves is a little bit of refactoring of `views.py`.
```python
from snippets.models import Snippet from snippets.models import Snippet
from snippets.serializers import SnippetSerializer from snippets.serializers import SnippetSerializer
from django.http import Http404 from django.http import Http404
@ -18,6 +19,7 @@ We'll start by rewriting the root view as a class-based view. All this involves
""" """
List all snippets, or create a new snippet. List all snippets, or create a new snippet.
""" """
def get(self, request, format=None): def get(self, request, format=None):
snippets = Snippet.objects.all() snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True) serializer = SnippetSerializer(snippets, many=True)
@ -29,13 +31,16 @@ We'll start by rewriting the root view as a class-based view. All this involves
serializer.save() serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
```
So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view in `views.py`. So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view in `views.py`.
```python
class SnippetDetail(APIView): class SnippetDetail(APIView):
""" """
Retrieve, update or delete a snippet instance. Retrieve, update or delete a snippet instance.
""" """
def get_object(self, pk): def get_object(self, pk):
try: try:
return Snippet.objects.get(pk=pk) return Snippet.objects.get(pk=pk)
@ -59,21 +64,24 @@ So far, so good. It looks pretty similar to the previous case, but we've got be
snippet = self.get_object(pk) snippet = self.get_object(pk)
snippet.delete() snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT) return Response(status=status.HTTP_204_NO_CONTENT)
```
That's looking good. Again, it's still pretty similar to the function based view right now. That's looking good. Again, it's still pretty similar to the function based view right now.
We'll also need to refactor our `snippets/urls.py` slightly now that we're using class-based views. We'll also need to refactor our `snippets/urls.py` slightly now that we're using class-based views.
```python
from django.urls import path from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views from snippets import views
urlpatterns = [ urlpatterns = [
path('snippets/', views.SnippetList.as_view()), path("snippets/", views.SnippetList.as_view()),
path('snippets/<int:pk>/', views.SnippetDetail.as_view()), path("snippets/<int:pk>/", views.SnippetDetail.as_view()),
] ]
urlpatterns = format_suffix_patterns(urlpatterns) urlpatterns = format_suffix_patterns(urlpatterns)
```
Okay, we're done. If you run the development server everything should be working just as before. Okay, we're done. If you run the development server everything should be working just as before.
@ -85,14 +93,16 @@ The create/retrieve/update/delete operations that we've been using so far are go
Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again. Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again.
```python
from snippets.models import Snippet from snippets.models import Snippet
from snippets.serializers import SnippetSerializer from snippets.serializers import SnippetSerializer
from rest_framework import mixins from rest_framework import mixins
from rest_framework import generics from rest_framework import generics
class SnippetList(mixins.ListModelMixin,
mixins.CreateModelMixin, class SnippetList(
generics.GenericAPIView): mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView
):
queryset = Snippet.objects.all() queryset = Snippet.objects.all()
serializer_class = SnippetSerializer serializer_class = SnippetSerializer
@ -101,15 +111,19 @@ Let's take a look at how we can compose the views by using the mixin classes. H
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs) return self.create(request, *args, **kwargs)
```
We'll take a moment to examine exactly what's happening here. We're building our view using `GenericAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`. We'll take a moment to examine exactly what's happening here. We're building our view using `GenericAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`.
The base class provides the core functionality, and the mixin classes provide the `.list()` and `.create()` actions. We're then explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far. The base class provides the core functionality, and the mixin classes provide the `.list()` and `.create()` actions. We're then explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far.
class SnippetDetail(mixins.RetrieveModelMixin, ```python
class SnippetDetail(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin, mixins.UpdateModelMixin,
mixins.DestroyModelMixin, mixins.DestroyModelMixin,
generics.GenericAPIView): generics.GenericAPIView,
):
queryset = Snippet.objects.all() queryset = Snippet.objects.all()
serializer_class = SnippetSerializer serializer_class = SnippetSerializer
@ -121,6 +135,7 @@ The base class provides the core functionality, and the mixin classes provide th
def delete(self, request, *args, **kwargs): def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs) return self.destroy(request, *args, **kwargs)
```
Pretty similar. Again we're using the `GenericAPIView` class to provide the core functionality, and adding in mixins to provide the `.retrieve()`, `.update()` and `.destroy()` actions. Pretty similar. Again we're using the `GenericAPIView` class to provide the core functionality, and adding in mixins to provide the `.retrieve()`, `.update()` and `.destroy()` actions.
@ -128,6 +143,7 @@ Pretty similar. Again we're using the `GenericAPIView` class to provide the cor
Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our `views.py` module even more. Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our `views.py` module even more.
```python
from snippets.models import Snippet from snippets.models import Snippet
from snippets.serializers import SnippetSerializer from snippets.serializers import SnippetSerializer
from rest_framework import generics from rest_framework import generics
@ -141,6 +157,7 @@ Using the mixin classes we've rewritten the views to use slightly less code than
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all() queryset = Snippet.objects.all()
serializer_class = SnippetSerializer serializer_class = SnippetSerializer
```
Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django. Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.

View File

@ -14,61 +14,78 @@ First, let's add a couple of fields. One of those fields will be used to repres
Add the following two fields to the `Snippet` model in `models.py`. Add the following two fields to the `Snippet` model in `models.py`.
owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE) ```python
owner = models.ForeignKey(
"auth.User", related_name="snippets", on_delete=models.CASCADE
)
highlighted = models.TextField() highlighted = models.TextField()
```
We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the `pygments` code highlighting library. We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the `pygments` code highlighting library.
We'll need some extra imports: We'll need some extra imports:
```python
from pygments.lexers import get_lexer_by_name from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter from pygments.formatters.html import HtmlFormatter
from pygments import highlight from pygments import highlight
```
And now we can add a `.save()` method to our model class: And now we can add a `.save()` method to our model class:
```python
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
""" """
Use the `pygments` library to create a highlighted HTML Use the `pygments` library to create a highlighted HTML
representation of the code snippet. representation of the code snippet.
""" """
lexer = get_lexer_by_name(self.language) lexer = get_lexer_by_name(self.language)
linenos = 'table' if self.linenos else False linenos = "table" if self.linenos else False
options = {'title': self.title} if self.title else {} options = {"title": self.title} if self.title else {}
formatter = HtmlFormatter(style=self.style, linenos=linenos, formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options)
full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter) self.highlighted = highlight(self.code, lexer, formatter)
super().save(*args, **kwargs) super().save(*args, **kwargs)
```
When that's all done we'll need to update our database tables. When that's all done we'll need to update our database tables.
Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again. Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.
```bash
rm -f db.sqlite3 rm -f db.sqlite3
rm -r snippets/migrations rm -r snippets/migrations
python manage.py makemigrations snippets python manage.py makemigrations snippets
python manage.py migrate python manage.py migrate
```
You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the `createsuperuser` command. You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the `createsuperuser` command.
```bash
python manage.py createsuperuser python manage.py createsuperuser
```
## Adding endpoints for our User models ## Adding endpoints for our User models
Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In `serializers.py` add: Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In `serializers.py` add:
```python
from django.contrib.auth.models import User from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer): class UserSerializer(serializers.ModelSerializer):
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all()) snippets = serializers.PrimaryKeyRelatedField(
many=True, queryset=Snippet.objects.all()
)
class Meta: class Meta:
model = User model = User
fields = ['id', 'username', 'snippets'] fields = ["id", "username", "snippets"]
```
Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we needed to add an explicit field for it. Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we needed to add an explicit field for it.
We'll also add a couple of views to `views.py`. We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class-based views. We'll also add a couple of views to `views.py`. We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class-based views.
```python
from django.contrib.auth.models import User from django.contrib.auth.models import User
@ -80,15 +97,20 @@ We'll also add a couple of views to `views.py`. We'd like to just use read-only
class UserDetail(generics.RetrieveAPIView): class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all() queryset = User.objects.all()
serializer_class = UserSerializer serializer_class = UserSerializer
```
Make sure to also import the `UserSerializer` class Make sure to also import the `UserSerializer` class
```python
from snippets.serializers import UserSerializer from snippets.serializers import UserSerializer
```
Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `snippets/urls.py`. Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `snippets/urls.py`.
path('users/', views.UserList.as_view()), ```python
path('users/<int:pk>/', views.UserDetail.as_view()), path("users/", views.UserList.as_view()),
path("users/<int:pk>/", views.UserDetail.as_view()),
```
## Associating Snippets with Users ## Associating Snippets with Users
@ -98,8 +120,10 @@ The way we deal with that is by overriding a `.perform_create()` method on our s
On the `SnippetList` view class, add the following method: On the `SnippetList` view class, add the following method:
```python
def perform_create(self, serializer): def perform_create(self, serializer):
serializer.save(owner=self.request.user) serializer.save(owner=self.request.user)
```
The `create()` method of our serializer will now be passed an additional `'owner'` field, along with the validated data from the request. The `create()` method of our serializer will now be passed an additional `'owner'` field, along with the validated data from the request.
@ -107,7 +131,9 @@ The `create()` method of our serializer will now be passed an additional `'owner
Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition in `serializers.py`: Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition in `serializers.py`:
owner = serializers.ReadOnlyField(source='owner.username') ```python
owner = serializers.ReadOnlyField(source="owner.username")
```
**Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class. **Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class.
@ -123,11 +149,15 @@ REST framework includes a number of permission classes that we can use to restri
First add the following import in the views module First add the following import in the views module
```python
from rest_framework import permissions from rest_framework import permissions
```
Then, add the following property to **both** the `SnippetList` and `SnippetDetail` view classes. Then, add the following property to **both** the `SnippetList` and `SnippetDetail` view classes.
```python
permission_classes = [permissions.IsAuthenticatedOrReadOnly] permission_classes = [permissions.IsAuthenticatedOrReadOnly]
```
## Adding login to the Browsable API ## Adding login to the Browsable API
@ -137,13 +167,17 @@ We can add a login view for use with the browsable API, by editing the URLconf i
Add the following import at the top of the file: Add the following import at the top of the file:
```python
from django.urls import path, include from django.urls import path, include
```
And, at the end of the file, add a pattern to include the login and logout views for the browsable API. And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
```python
urlpatterns += [ urlpatterns += [
path('api-auth/', include('rest_framework.urls')), path("api-auth/", include("rest_framework.urls")),
] ]
```
The `'api-auth/'` part of pattern can actually be whatever URL you want to use. The `'api-auth/'` part of pattern can actually be whatever URL you want to use.
@ -159,6 +193,7 @@ To do that we're going to need to create a custom permission.
In the snippets app, create a new file, `permissions.py` In the snippets app, create a new file, `permissions.py`
```python
from rest_framework import permissions from rest_framework import permissions
@ -175,15 +210,19 @@ In the snippets app, create a new file, `permissions.py`
# Write permissions are only allowed to the owner of the snippet. # Write permissions are only allowed to the owner of the snippet.
return obj.owner == request.user return obj.owner == request.user
```
Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` view class: Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` view class:
permission_classes = [permissions.IsAuthenticatedOrReadOnly, ```python
IsOwnerOrReadOnly] permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
```
Make sure to also import the `IsOwnerOrReadOnly` class. Make sure to also import the `IsOwnerOrReadOnly` class.
```python
from snippets.permissions import IsOwnerOrReadOnly from snippets.permissions import IsOwnerOrReadOnly
```
Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet. Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.
@ -197,14 +236,17 @@ If we're interacting with the API programmatically we need to explicitly provide
If we try to create a snippet without authenticating, we'll get an error: If we try to create a snippet without authenticating, we'll get an error:
```bash
http POST http://127.0.0.1:8000/snippets/ code="print(123)" http POST http://127.0.0.1:8000/snippets/ code="print(123)"
{ {
"detail": "Authentication credentials were not provided." "detail": "Authentication credentials were not provided."
} }
```
We can make a successful request by including the username and password of one of the users we created earlier. We can make a successful request by including the username and password of one of the users we created earlier.
```bash
http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print(789)" http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print(789)"
{ {
@ -216,6 +258,7 @@ We can make a successful request by including the username and password of one o
"language": "python", "language": "python",
"style": "friendly" "style": "friendly"
} }
```
## Summary ## Summary

View File

@ -6,17 +6,21 @@ At the moment relationships within our API are represented by using primary keys
Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. In your `snippets/views.py` add: Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. In your `snippets/views.py` add:
```python
from rest_framework.decorators import api_view from rest_framework.decorators import api_view
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework.reverse import reverse from rest_framework.reverse import reverse
@api_view(['GET']) @api_view(["GET"])
def api_root(request, format=None): def api_root(request, format=None):
return Response({ return Response(
'users': reverse('user-list', request=request, format=format), {
'snippets': reverse('snippet-list', request=request, format=format) "users": reverse("user-list", request=request, format=format),
}) "snippets": reverse("snippet-list", request=request, format=format),
}
)
```
Two things should be noticed here. First, we're using REST framework's `reverse` function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our `snippets/urls.py`. Two things should be noticed here. First, we're using REST framework's `reverse` function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our `snippets/urls.py`.
@ -30,8 +34,10 @@ The other thing we need to consider when creating the code highlight view is tha
Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets/views.py` add: Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets/views.py` add:
```python
from rest_framework import renderers from rest_framework import renderers
class SnippetHighlight(generics.GenericAPIView): class SnippetHighlight(generics.GenericAPIView):
queryset = Snippet.objects.all() queryset = Snippet.objects.all()
renderer_classes = [renderers.StaticHTMLRenderer] renderer_classes = [renderers.StaticHTMLRenderer]
@ -39,15 +45,20 @@ Instead of using a concrete generic view, we'll use the base class for represent
def get(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
snippet = self.get_object() snippet = self.get_object()
return Response(snippet.highlighted) return Response(snippet.highlighted)
```
As usual we need to add the new views that we've created in to our URLconf. As usual we need to add the new views that we've created in to our URLconf.
We'll add a url pattern for our new API root in `snippets/urls.py`: We'll add a url pattern for our new API root in `snippets/urls.py`:
path('', views.api_root), ```python
path("", views.api_root),
```
And then add a url pattern for the snippet highlights: And then add a url pattern for the snippet highlights:
path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view()), ```python
path("snippets/<int:pk>/highlight/", views.SnippetHighlight.as_view()),
```
## Hyperlinking our API ## Hyperlinking our API
@ -73,22 +84,37 @@ The `HyperlinkedModelSerializer` has the following differences from `ModelSerial
We can easily re-write our existing serializers to use hyperlinking. In your `snippets/serializers.py` add: We can easily re-write our existing serializers to use hyperlinking. In your `snippets/serializers.py` add:
```python
class SnippetSerializer(serializers.HyperlinkedModelSerializer): class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username') owner = serializers.ReadOnlyField(source="owner.username")
highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') highlight = serializers.HyperlinkedIdentityField(
view_name="snippet-highlight", format="html"
)
class Meta: class Meta:
model = Snippet model = Snippet
fields = ['url', 'id', 'highlight', 'owner', fields = [
'title', 'code', 'linenos', 'language', 'style'] "url",
"id",
"highlight",
"owner",
"title",
"code",
"linenos",
"language",
"style",
]
class UserSerializer(serializers.HyperlinkedModelSerializer): class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True) snippets = serializers.HyperlinkedRelatedField(
many=True, view_name="snippet-detail", read_only=True
)
class Meta: class Meta:
model = User model = User
fields = ['url', 'id', 'username', 'snippets'] fields = ["url", "id", "username", "snippets"]
```
Notice that we've also added a new `'highlight'` field. This field is of the same type as the `url` field, except that it points to the `'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url pattern. Notice that we've also added a new `'highlight'` field. This field is of the same type as the `url` field, except that it points to the `'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url pattern.
@ -100,11 +126,15 @@ Because we've included format suffixed URLs such as `'.json'`, we also need to i
When you are manually instantiating these serializers inside your views (e.g., in `SnippetDetail` or `SnippetList`), you **must** pass `context={'request': request}` so the serializer knows how to build absolute URLs. For example, instead of: When you are manually instantiating these serializers inside your views (e.g., in `SnippetDetail` or `SnippetList`), you **must** pass `context={'request': request}` so the serializer knows how to build absolute URLs. For example, instead of:
```python
serializer = SnippetSerializer(snippet) serializer = SnippetSerializer(snippet)
```
You must write: You must write:
serializer = SnippetSerializer(snippet, context={'request': request}) ```python
serializer = SnippetSerializer(snippet, context={"request": request})
```
If your view is a subclass of `GenericAPIView`, you may use the `get_serializer_context()` as a convenience method. If your view is a subclass of `GenericAPIView`, you may use the `get_serializer_context()` as a convenience method.
@ -121,29 +151,29 @@ If we're going to have a hyperlinked API, we need to make sure we name our URL p
After adding all those names into our URLconf, our final `snippets/urls.py` file should look like this: After adding all those names into our URLconf, our final `snippets/urls.py` file should look like this:
```python
from django.urls import path from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views from snippets import views
# API endpoints # API endpoints
urlpatterns = format_suffix_patterns([ urlpatterns = format_suffix_patterns(
path('', views.api_root), [
path('snippets/', path("", views.api_root),
views.SnippetList.as_view(), path("snippets/", views.SnippetList.as_view(), name="snippet-list"),
name='snippet-list'), path(
path('snippets/<int:pk>/', "snippets/<int:pk>/", views.SnippetDetail.as_view(), name="snippet-detail"
views.SnippetDetail.as_view(), ),
name='snippet-detail'), path(
path('snippets/<int:pk>/highlight/', "snippets/<int:pk>/highlight/",
views.SnippetHighlight.as_view(), views.SnippetHighlight.as_view(),
name='snippet-highlight'), name="snippet-highlight",
path('users/', ),
views.UserList.as_view(), path("users/", views.UserList.as_view(), name="user-list"),
name='user-list'), path("users/<int:pk>/", views.UserDetail.as_view(), name="user-detail"),
path('users/<int:pk>/', ]
views.UserDetail.as_view(), )
name='user-detail') ```
])
## Adding pagination ## Adding pagination
@ -151,10 +181,12 @@ The list views for users and code snippets could end up returning quite a lot of
We can change the default list style to use pagination, by modifying our `tutorial/settings.py` file slightly. Add the following setting: We can change the default list style to use pagination, by modifying our `tutorial/settings.py` file slightly. Add the following setting:
```python
REST_FRAMEWORK = { REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
'PAGE_SIZE': 10 "PAGE_SIZE": 10,
} }
```
Note that settings in REST framework are all namespaced into a single dictionary setting, named `REST_FRAMEWORK`, which helps keep them well separated from your other project settings. Note that settings in REST framework are all namespaced into a single dictionary setting, named `REST_FRAMEWORK`, which helps keep them well separated from your other project settings.

View File

@ -12,6 +12,7 @@ Let's take our current set of views, and refactor them into view sets.
First of all let's refactor our `UserList` and `UserDetail` classes into a single `UserViewSet` class. In the `snippets/views.py` file, we can remove the two view classes and replace them with a single ViewSet class: First of all let's refactor our `UserList` and `UserDetail` classes into a single `UserViewSet` class. In the `snippets/views.py` file, we can remove the two view classes and replace them with a single ViewSet class:
```python
from rest_framework import viewsets from rest_framework import viewsets
@ -19,13 +20,16 @@ First of all let's refactor our `UserList` and `UserDetail` classes into a singl
""" """
This viewset automatically provides `list` and `retrieve` actions. This viewset automatically provides `list` and `retrieve` actions.
""" """
queryset = User.objects.all() queryset = User.objects.all()
serializer_class = UserSerializer serializer_class = UserSerializer
```
Here we've used the `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations. We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes. Here we've used the `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations. We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.
Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes. We can remove the three views, and again replace them with a single class. Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes. We can remove the three views, and again replace them with a single class.
```python
from rest_framework import permissions from rest_framework import permissions
from rest_framework import renderers from rest_framework import renderers
from rest_framework.decorators import action from rest_framework.decorators import action
@ -39,10 +43,10 @@ Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl
Additionally we also provide an extra `highlight` action. Additionally we also provide an extra `highlight` action.
""" """
queryset = Snippet.objects.all() queryset = Snippet.objects.all()
serializer_class = SnippetSerializer serializer_class = SnippetSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
IsOwnerOrReadOnly]
@action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer]) @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer])
def highlight(self, request, *args, **kwargs): def highlight(self, request, *args, **kwargs):
@ -51,6 +55,7 @@ Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl
def perform_create(self, serializer): def perform_create(self, serializer):
serializer.save(owner=self.request.user) serializer.save(owner=self.request.user)
```
This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations. This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations.
@ -67,42 +72,40 @@ To see what's going on under the hood let's first explicitly create a set of vie
In the `snippets/urls.py` file we bind our `ViewSet` classes into a set of concrete views. In the `snippets/urls.py` file we bind our `ViewSet` classes into a set of concrete views.
```python
from rest_framework import renderers from rest_framework import renderers
from snippets.views import api_root, SnippetViewSet, UserViewSet from snippets.views import api_root, SnippetViewSet, UserViewSet
snippet_list = SnippetViewSet.as_view({ snippet_list = SnippetViewSet.as_view({"get": "list", "post": "create"})
'get': 'list', snippet_detail = SnippetViewSet.as_view(
'post': 'create' {"get": "retrieve", "put": "update", "patch": "partial_update", "delete": "destroy"}
}) )
snippet_detail = SnippetViewSet.as_view({ snippet_highlight = SnippetViewSet.as_view(
'get': 'retrieve', {"get": "highlight"}, renderer_classes=[renderers.StaticHTMLRenderer]
'put': 'update', )
'patch': 'partial_update', user_list = UserViewSet.as_view({"get": "list"})
'delete': 'destroy' user_detail = UserViewSet.as_view({"get": "retrieve"})
}) ```
snippet_highlight = SnippetViewSet.as_view({
'get': 'highlight'
}, renderer_classes=[renderers.StaticHTMLRenderer])
user_list = UserViewSet.as_view({
'get': 'list'
})
user_detail = UserViewSet.as_view({
'get': 'retrieve'
})
Notice how we're creating multiple views from each `ViewSet` class, by binding the HTTP methods to the required action for each view. Notice how we're creating multiple views from each `ViewSet` class, by binding the HTTP methods to the required action for each view.
Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual. Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.
urlpatterns = format_suffix_patterns([ ```python
path('', api_root), urlpatterns = format_suffix_patterns(
path('snippets/', snippet_list, name='snippet-list'), [
path('snippets/<int:pk>/', snippet_detail, name='snippet-detail'), path("", api_root),
path('snippets/<int:pk>/highlight/', snippet_highlight, name='snippet-highlight'), path("snippets/", snippet_list, name="snippet-list"),
path('users/', user_list, name='user-list'), path("snippets/<int:pk>/", snippet_detail, name="snippet-detail"),
path('users/<int:pk>/', user_detail, name='user-detail') path(
]) "snippets/<int:pk>/highlight/", snippet_highlight, name="snippet-highlight"
),
path("users/", user_list, name="user-list"),
path("users/<int:pk>/", user_detail, name="user-detail"),
]
)
```
## Using Routers ## Using Routers
@ -110,6 +113,7 @@ Because we're using `ViewSet` classes rather than `View` classes, we actually do
Here's our re-wired `snippets/urls.py` file. Here's our re-wired `snippets/urls.py` file.
```python
from django.urls import path, include from django.urls import path, include
from rest_framework.routers import DefaultRouter from rest_framework.routers import DefaultRouter
@ -117,13 +121,14 @@ Here's our re-wired `snippets/urls.py` file.
# Create a router and register our ViewSets with it. # Create a router and register our ViewSets with it.
router = DefaultRouter() router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet, basename='snippet') router.register(r"snippets", views.SnippetViewSet, basename="snippet")
router.register(r'users', views.UserViewSet, basename='user') router.register(r"users", views.UserViewSet, basename="user")
# The API URLs are now determined automatically by the router. # The API URLs are now determined automatically by the router.
urlpatterns = [ urlpatterns = [
path('', include(router.urls)), path("", include(router.urls)),
] ]
```
Registering the ViewSets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the view set itself. Registering the ViewSets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the view set itself.

View File

@ -6,6 +6,7 @@ We're going to create a simple API to allow admin users to view and edit the use
Create a new Django project named `tutorial`, then start a new app called `quickstart`. Create a new Django project named `tutorial`, then start a new app called `quickstart`.
```bash
# Create the project directory # Create the project directory
mkdir tutorial mkdir tutorial
cd tutorial cd tutorial
@ -22,9 +23,11 @@ Create a new Django project named `tutorial`, then start a new app called `quick
cd tutorial cd tutorial
django-admin startapp quickstart django-admin startapp quickstart
cd .. cd ..
```
The project layout should look like: The project layout should look like:
```bash
$ pwd $ pwd
<some path>/tutorial <some path>/tutorial
$ find . $ find .
@ -47,16 +50,21 @@ The project layout should look like:
./env ./env
./env/... ./env/...
./manage.py ./manage.py
```
It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart). It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart).
Now sync your database for the first time: Now sync your database for the first time:
```bash
python manage.py migrate python manage.py migrate
```
We'll also create an initial user named `admin` with a password. We'll authenticate as that user later in our example. We'll also create an initial user named `admin` with a password. We'll authenticate as that user later in our example.
```bash
python manage.py createsuperuser --username admin --email admin@example.com python manage.py createsuperuser --username admin --email admin@example.com
```
Once you've set up a database and the initial user is created and ready to go, open up the app's directory and we'll get coding... Once you've set up a database and the initial user is created and ready to go, open up the app's directory and we'll get coding...
@ -64,6 +72,7 @@ Once you've set up a database and the initial user is created and ready to go, o
First up we're going to define some serializers. Let's create a new module named `tutorial/quickstart/serializers.py` that we'll use for our data representations. First up we're going to define some serializers. Let's create a new module named `tutorial/quickstart/serializers.py` that we'll use for our data representations.
```python
from django.contrib.auth.models import Group, User from django.contrib.auth.models import Group, User
from rest_framework import serializers from rest_framework import serializers
@ -71,13 +80,14 @@ First up we're going to define some serializers. Let's create a new module named
class UserSerializer(serializers.HyperlinkedModelSerializer): class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = User model = User
fields = ['url', 'username', 'email', 'groups'] fields = ["url", "username", "email", "groups"]
class GroupSerializer(serializers.HyperlinkedModelSerializer): class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = Group model = Group
fields = ['url', 'name'] fields = ["url", "name"]
```
Notice that we're using hyperlinked relations in this case with `HyperlinkedModelSerializer`. You can also use primary key and various other relationships, but hyperlinking is good RESTful design. Notice that we're using hyperlinked relations in this case with `HyperlinkedModelSerializer`. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.
@ -85,6 +95,7 @@ Notice that we're using hyperlinked relations in this case with `HyperlinkedMode
Right, we'd better write some views then. Open `tutorial/quickstart/views.py` and get typing. Right, we'd better write some views then. Open `tutorial/quickstart/views.py` and get typing.
```python
from django.contrib.auth.models import Group, User from django.contrib.auth.models import Group, User
from rest_framework import permissions, viewsets from rest_framework import permissions, viewsets
@ -95,7 +106,8 @@ Right, we'd better write some views then. Open `tutorial/quickstart/views.py` a
""" """
API endpoint that allows users to be viewed or edited. API endpoint that allows users to be viewed or edited.
""" """
queryset = User.objects.all().order_by('-date_joined')
queryset = User.objects.all().order_by("-date_joined")
serializer_class = UserSerializer serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated] permission_classes = [permissions.IsAuthenticated]
@ -104,9 +116,11 @@ Right, we'd better write some views then. Open `tutorial/quickstart/views.py` a
""" """
API endpoint that allows groups to be viewed or edited. API endpoint that allows groups to be viewed or edited.
""" """
queryset = Group.objects.all().order_by('name')
queryset = Group.objects.all().order_by("name")
serializer_class = GroupSerializer serializer_class = GroupSerializer
permission_classes = [permissions.IsAuthenticated] permission_classes = [permissions.IsAuthenticated]
```
Rather than write multiple views we're grouping together all the common behavior into classes called `ViewSets`. Rather than write multiple views we're grouping together all the common behavior into classes called `ViewSets`.
@ -116,21 +130,23 @@ We can easily break these down into individual views if we need to, but using vi
Okay, now let's wire up the API URLs. On to `tutorial/urls.py`... Okay, now let's wire up the API URLs. On to `tutorial/urls.py`...
```python
from django.urls import include, path from django.urls import include, path
from rest_framework import routers from rest_framework import routers
from tutorial.quickstart import views from tutorial.quickstart import views
router = routers.DefaultRouter() router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet) router.register(r"users", views.UserViewSet)
router.register(r'groups', views.GroupViewSet) router.register(r"groups", views.GroupViewSet)
# Wire up our API using automatic URL routing. # Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API. # Additionally, we include login URLs for the browsable API.
urlpatterns = [ urlpatterns = [
path('', include(router.urls)), path("", include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),
] ]
```
Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class. Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.
@ -139,21 +155,26 @@ Again, if we need more control over the API URLs we can simply drop down to usin
Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API. Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.
## Pagination ## Pagination
Pagination allows you to control how many objects per page are returned. To enable it add the following lines to `tutorial/settings.py` Pagination allows you to control how many objects per page are returned. To enable it add the following lines to `tutorial/settings.py`
```python
REST_FRAMEWORK = { REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
'PAGE_SIZE': 10 "PAGE_SIZE": 10,
} }
```
## Settings ## Settings
Add `'rest_framework'` to `INSTALLED_APPS`. The settings module will be in `tutorial/settings.py` Add `'rest_framework'` to `INSTALLED_APPS`. The settings module will be in `tutorial/settings.py`
```text
INSTALLED_APPS = [ INSTALLED_APPS = [
... ...
'rest_framework', 'rest_framework',
] ]
```
Okay, we're done. Okay, we're done.
@ -163,10 +184,13 @@ Okay, we're done.
We're now ready to test the API we've built. Let's fire up the server from the command line. We're now ready to test the API we've built. Let's fire up the server from the command line.
```bash
python manage.py runserver python manage.py runserver
```
We can now access our API, both from the command-line, using tools like `curl`... We can now access our API, both from the command-line, using tools like `curl`...
```bash
bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/ bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/
Enter host password for user 'admin': Enter host password for user 'admin':
{ {
@ -182,9 +206,11 @@ We can now access our API, both from the command-line, using tools like `curl`..
} }
] ]
} }
```
Or using the [httpie][httpie], command line tool... Or using the [httpie][httpie], command line tool...
```bash
bash: http -a admin http://127.0.0.1:8000/users/ bash: http -a admin http://127.0.0.1:8000/users/
http: password for admin@127.0.0.1:8000:: http: password for admin@127.0.0.1:8000::
$HTTP/1.1 200 OK $HTTP/1.1 200 OK
@ -202,7 +228,7 @@ Or using the [httpie][httpie], command line tool...
} }
] ]
} }
```
Or directly through the browser, by going to the URL `http://127.0.0.1:8000/users/`... Or directly through the browser, by going to the URL `http://127.0.0.1:8000/users/`...