aboutsummaryrefslogtreecommitdiffstats
path: root/docs/tutorial
diff options
context:
space:
mode:
Diffstat (limited to 'docs/tutorial')
-rw-r--r--docs/tutorial/1-serialization.md98
-rw-r--r--docs/tutorial/2-requests-and-responses.md47
-rw-r--r--docs/tutorial/3-class-based-views.md20
-rw-r--r--docs/tutorial/4-authentication-and-permissions.md66
-rw-r--r--docs/tutorial/5-relationships-and-hyperlinked-apis.md50
-rw-r--r--docs/tutorial/6-viewsets-and-routers.md151
-rw-r--r--docs/tutorial/quickstart.md95
7 files changed, 348 insertions, 179 deletions
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index e61fb946..ed54a876 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -4,11 +4,11 @@
This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.
-The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started.<!-- If you just want a quick overview, you should head over to the [quickstart] documentation instead. -->
+The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the [quickstart] documentation instead.
---
-**Note**: The final code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. There is also a sandbox version for testing, [available here][sandbox].
+**Note**: The code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. The completed implementation is also online as a sandbox version for testing, [available here][sandbox].
---
@@ -60,7 +60,7 @@ We'll also need to add our new `snippets` app and the `rest_framework` app to `I
INSTALLED_APPS = (
...
'rest_framework',
- 'snippets'
+ 'snippets',
)
We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs.
@@ -73,19 +73,20 @@ Okay, we're ready to roll.
## Creating a model to work with
-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` app's `models.py` file.
+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` app's `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.
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
-
- LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in get_all_lexers()])
- STYLE_CHOICES = sorted((item, item) for item in list(get_all_styles()))
+
+ LEXERS = [item for item in get_all_lexers() if item[1]]
+ LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
+ STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
- title = models.CharField(max_length=100, default='')
+ title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES,
@@ -108,7 +109,7 @@ The first thing we need to get started on our Web API is provide a way of serial
from django.forms import widgets
from rest_framework import serializers
- from snippets import models
+ from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
class SnippetSerializer(serializers.Serializer):
@@ -118,26 +119,30 @@ The first thing we need to get started on our Web API is provide a way of serial
code = serializers.CharField(widget=widgets.Textarea,
max_length=100000)
linenos = serializers.BooleanField(required=False)
- language = serializers.ChoiceField(choices=models.LANGUAGE_CHOICES,
+ language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
default='python')
- style = serializers.ChoiceField(choices=models.STYLE_CHOICES,
+ style = serializers.ChoiceField(choices=STYLE_CHOICES,
default='friendly')
def restore_object(self, attrs, instance=None):
"""
- Create or update a new snippet instance.
+ Create or update a new snippet instance, given a dictionary
+ of deserialized field values.
+
+ Note that if we don't define this method, then deserializing
+ data will simply return a dictionary of items.
"""
if instance:
# Update existing instance
- instance.title = attrs['title']
- instance.code = attrs['code']
- instance.linenos = attrs['linenos']
- instance.language = attrs['language']
- instance.style = attrs['style']
+ instance.title = attrs.get('title', instance.title)
+ instance.code = attrs.get('code', instance.code)
+ instance.linenos = attrs.get('linenos', instance.linenos)
+ instance.language = attrs.get('language', instance.language)
+ instance.style = attrs.get('style', instance.style)
return instance
# Create new instance
- return models.Snippet(**attrs)
+ return Snippet(**attrs)
The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data.
@@ -149,13 +154,16 @@ Before we go any further we'll familiarize ourselves with using our new Serializ
python manage.py shell
-Okay, once we've got a few imports out of the way, let's create a code snippet 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
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
+ snippet = Snippet(code='foo = "bar"\n')
+ snippet.save()
+
snippet = Snippet(code='print "hello, world"\n')
snippet.save()
@@ -163,13 +171,13 @@ We've now got a few snippet instances to play with. Let's take a look at serial
serializer = SnippetSerializer(snippet)
serializer.data
- # {'pk': 1, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
+ # {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'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`.
content = JSONRenderer().render(serializer.data)
content
- # '{"pk": 1, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
+ # '{"pk": 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...
@@ -188,9 +196,15 @@ Deserialization is similar. First we parse a stream into python native datatype
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.
+
+ serializer = SnippetSerializer(Snippet.objects.all(), many=True)
+ serializer.data
+ # [{'pk': 1, 'title': u'', 'code': u'foo = "bar"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}, {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}]
+
## Using ModelSerializers
-Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep out code a bit more concise.
+Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise.
In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes.
@@ -202,8 +216,6 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer`
model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
-
-
## Writing regular Django views using our Serializer
Let's see how we can write some API views using our new Serializer class.
@@ -229,7 +241,6 @@ Edit the `snippet/views.py` file, and add the following.
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
-
The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.
@csrf_exempt
@@ -239,7 +250,7 @@ The root of our API is going to be a view that supports listing all the existing
"""
if request.method == 'GET':
snippets = Snippet.objects.all()
- serializer = SnippetSerializer(snippets)
+ serializer = SnippetSerializer(snippets, many=True)
return JSONResponse(serializer.data)
elif request.method == 'POST':
@@ -288,16 +299,45 @@ Finally we need to wire these views up. Create the `snippets/urls.py` file:
urlpatterns = patterns('snippets.views',
url(r'^snippets/$', 'snippet_list'),
- url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail')
+ url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail'),
)
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.
## Testing our first attempt at a Web API
-**TODO: Describe using runserver and making example requests from console**
+Now we can start up a sample server that serves our snippets.
+
+Quit out of the shell...
+
+ quit()
+
+...and start up Django's development server.
+
+ python manage.py runserver
+
+ Validating models...
+
+ 0 errors found
+ Django version 1.4.3, using settings 'tutorial.settings'
+ Development server is running at http://127.0.0.1:8000/
+ Quit the server with CONTROL-C.
+
+In another terminal window, we can test the server.
+
+We can get a list of all of the snippets.
+
+ curl http://127.0.0.1:8000/snippets/
+
+ [{"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"}]
+
+Or we can get a particular snippet by referencing its id.
+
+ curl http://127.0.0.1:8000/snippets/2/
+
+ {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}
-**TODO: Describe opening in a web browser and viewing json output**
+Similarly, you can have the same json displayed by visiting these URLs in a web browser.
## Where are we now
diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md
index 08cf91cd..260c4d83 100644
--- a/docs/tutorial/2-requests-and-responses.md
+++ b/docs/tutorial/2-requests-and-responses.md
@@ -8,7 +8,7 @@ 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.
request.POST # Only handles form data. Only works for 'POST' method.
- request.DATA # Handles arbitrary data. Works any HTTP request with content.
+ request.DATA # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
## Response objects
@@ -31,7 +31,6 @@ These wrappers provide a few bits of functionality such as making sure you recei
The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.DATA` with malformed input.
-
## Pulling it all together
Okay, let's go ahead and start using these new components to write a few views.
@@ -52,7 +51,7 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On
"""
if request.method == 'GET':
snippets = Snippet.objects.all()
- serializer = SnippetSerializer(snippets)
+ serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
elif request.method == 'POST':
@@ -63,7 +62,6 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On
else:
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.
Here is the view for an individual snippet.
@@ -77,11 +75,11 @@ Here is the view for an individual snippet.
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
-
+
if request.method == 'GET':
serializer = SnippetSerializer(snippet)
return Response(serializer.data)
-
+
elif request.method == 'PUT':
serializer = SnippetSerializer(snippet, data=request.DATA)
if serializer.is_valid():
@@ -117,7 +115,7 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter
urlpatterns = patterns('snippets.views',
url(r'^snippets/$', 'snippet_list'),
- url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail')
+ url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail'),
)
urlpatterns = format_suffix_patterns(urlpatterns)
@@ -128,16 +126,43 @@ We don't necessarily need to add these extra url patterns in, but it gives us a
Go ahead and test the API from the command line, as we did in [tutorial part 1][tut-1]. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.
-**TODO: Describe using accept headers, content-type headers, and format suffixed URLs**
+We can get a list of all of the snippets, as before.
+
+ curl http://127.0.0.1:8000/snippets/
+
+ [{"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"}]
+
+We can control the format of the response that we get back, either by using the `Accept` header:
+
+ curl http://127.0.0.1:8000/snippets/ -H 'Accept: application/json' # Request JSON
+ curl http://127.0.0.1:8000/snippets/ -H 'Accept: text/html' # Request HTML
+
+Or by appending a format suffix:
+
+ curl http://127.0.0.1:8000/snippets/.json # JSON suffix
+ curl 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.
+
+ # POST using form data
+ curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123"
+
+ {"id": 3, "title": "", "code": "123", "linenos": false, "language": "python", "style": "friendly"}
+
+ # POST using JSON
+ curl -X POST http://127.0.0.1:8000/snippets/ -d '{"code": "print 456"}' -H "Content-Type: application/json"
+
+ {"id": 4, "title": "", "code": "print 456", "linenos": true, "language": "python", "style": "friendly"}
Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver].
### Browsability
-Because the API chooses a return format based on what the client asks for, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a browser. This allows for the API to be easily browsable and usable by humans.
+Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.
-See the [browsable api][browseable-api] topic for more information about the browsable API feature and how to customize it.
+Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.
+See the [browsable api][browsable-api] topic for more information about the browsable API feature and how to customize it.
## What's next?
@@ -145,6 +170,6 @@ In [tutorial part 3][tut-3], we'll start using class based views, and see how ge
[json-url]: http://example.com/api/items/4.json
[devserver]: http://127.0.0.1:8000/snippets/
-[browseable-api]: ../topics/browsable-api.md
+[browsable-api]: ../topics/browsable-api.md
[tut-1]: 1-serialization.md
[tut-3]: 3-class-based-views.md
diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md
index b115b022..70cf2c54 100644
--- a/docs/tutorial/3-class-based-views.md
+++ b/docs/tutorial/3-class-based-views.md
@@ -20,7 +20,7 @@ We'll start by rewriting the root view as a class based view. All this involves
"""
def get(self, request, format=None):
snippets = Snippet.objects.all()
- serializer = SnippetSerializer(snippets)
+ serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
def post(self, request, format=None):
@@ -70,7 +70,7 @@ We'll also need to refactor our URLconf slightly now we're using class based vie
urlpatterns = patterns('',
url(r'^snippets/$', views.SnippetList.as_view()),
- url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view())
+ url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
)
urlpatterns = format_suffix_patterns(urlpatterns)
@@ -92,8 +92,8 @@ Let's take a look at how we can compose our views by using the mixin classes.
class SnippetList(mixins.ListModelMixin,
mixins.CreateModelMixin,
- generics.MultipleObjectAPIView):
- model = Snippet
+ generics.GenericAPIView):
+ queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def get(self, request, *args, **kwargs):
@@ -102,15 +102,15 @@ Let's take a look at how we can compose our views by using the mixin classes.
def post(self, 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 `MultipleObjectAPIView`, 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.
class SnippetDetail(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
- generics.SingleObjectAPIView):
- model = Snippet
+ generics.GenericAPIView):
+ queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def get(self, request, *args, **kwargs):
@@ -122,7 +122,7 @@ The base class provides the core functionality, and the mixin classes provide th
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
-Pretty similar. This time we're using the `SingleObjectAPIView` 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.
## Using generic class based views
@@ -134,12 +134,12 @@ Using the mixin classes we've rewritten the views to use slightly less code than
class SnippetList(generics.ListCreateAPIView):
- model = Snippet
+ queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
- model = Snippet
+ queryset = Snippet.objects.all()
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.
diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md
index 9576a7f0..f6c3efb0 100644
--- a/docs/tutorial/4-authentication-and-permissions.md
+++ b/docs/tutorial/4-authentication-and-permissions.md
@@ -22,14 +22,14 @@ We'd also need to make sure that when the model is saved, that we populate the h
We'll need some extra imports:
from pygments.lexers import get_lexer_by_name
- from pygments.formatters import HtmlFormatter
+ from pygments.formatters.html import HtmlFormatter
from pygments import highlight
And now we can add a `.save()` method to our model class:
def save(self, *args, **kwargs):
"""
- Use the `pygments` library to create an highlighted HTML
+ Use the `pygments` library to create a highlighted HTML
representation of the code snippet.
"""
lexer = get_lexer_by_name(self.language)
@@ -54,8 +54,10 @@ You might also want to create a few different users, to use for testing the API.
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:
+ from django.contrib.auth.models import User
+
class UserSerializer(serializers.ModelSerializer):
- snippets = serializers.ManyPrimaryKeyRelatedField()
+ snippets = serializers.PrimaryKeyRelatedField(many=True)
class Meta:
model = User
@@ -66,18 +68,18 @@ Because `'snippets'` is a *reverse* relationship on the User model, it will not
We'll also add a couple of views. 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.
class UserList(generics.ListAPIView):
- model = User
+ queryset = User.objects.all()
serializer_class = UserSerializer
- class UserInstance(generics.RetrieveAPIView):
- model = User
+ class UserDetail(generics.RetrieveAPIView):
+ queryset = User.objects.all()
serializer_class = UserSerializer
Finally we need to add those views into the API, by referencing them from the URL conf.
url(r'^users/$', views.UserList.as_view()),
- url(r'^users/(?P<pk>[0-9]+)/$', views.UserInstance.as_view())
+ url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
## Associating Snippets with Users
@@ -102,8 +104,6 @@ This field is doing something quite interesting. The `source` argument controls
The field we've added is the untyped `Field` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `Field` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized.
-**TODO: Explain the SessionAuthentication and BasicAuthentication classes, and demonstrate using HTTP basic authentication with curl requests**
-
## Adding required permissions to views
Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.
@@ -118,23 +118,21 @@ Then, add the following property to **both** the `SnippetList` and `SnippetDetai
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
-**TODO: Now that the permissions are restricted, demonstrate using HTTP basic authentication with curl requests**
+## Adding login to the Browsable API
-## Adding login to the Browseable API
+If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
-If you open a browser and navigate to the browseable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
-
-We can add a login view for use with the browseable API, by editing our URLconf once more.
+We can add a login view for use with the browsable API, by editing our URLconf once more.
Add the following import at the top of the file:
from django.conf.urls import include
-And, at the end of the file, add a pattern to include the login and logout views for the browseable API.
+And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
urlpatterns += patterns('',
url(r'^api-auth/', include('rest_framework.urls',
- namespace='rest_framework'))
+ namespace='rest_framework')),
)
The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the `'rest_framework'` namespace.
@@ -145,7 +143,7 @@ Once you've created a few code snippets, navigate to the '/users/' endpoint, and
## Object level permissions
-Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able update or delete it.
+Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.
To do that we're going to need to create a custom permission.
@@ -159,12 +157,9 @@ In the snippets app, create a new file, `permissions.py`
Custom permission to only allow owners of an object to edit it.
"""
- def has_permission(self, request, view, obj=None):
- # Skip the check unless this is an object-level test
- if obj is None:
- return True
-
- # Read permissions are allowed to any request
+ def has_object_permission(self, request, view, obj):
+ # Read permissions are allowed to any request,
+ # so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
@@ -182,10 +177,31 @@ Make sure to also import the `IsOwnerOrReadOnly` class.
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.
+## Authenticating with the API
+
+Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any [authentication classes][authentication], so the defaults are currently applied, which are `SessionAuthentication` and `BasicAuthentication`.
+
+When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.
+
+If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.
+
+If we try to create a snippet without authenticating, we'll get an error:
+
+ curl -i -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123"
+
+ {"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.
+
+ curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 789" -u tom:password
+
+ {"id": 5, "owner": "tom", "title": "foo", "code": "print 789", "linenos": false, "language": "python", "style": "friendly"}
+
## Summary
We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.
-In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our hightlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
+In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
-[tut-5]: 5-relationships-and-hyperlinked-apis.md \ No newline at end of file
+[authentication]: ../api-guide/authentication.md
+[tut-5]: 5-relationships-and-hyperlinked-apis.md
diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
index 216ca433..cb2e092c 100644
--- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md
+++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
@@ -1,4 +1,4 @@
-# Tutorial 5 - Relationships & Hyperlinked APIs
+# Tutorial 5: Relationships & Hyperlinked APIs
At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.
@@ -15,8 +15,8 @@ Right now we have endpoints for 'snippets' and 'users', but we don't have a sing
@api_view(('GET',))
def api_root(request, format=None):
return Response({
- 'users': reverse('user-list', request=request),
- 'snippets': reverse('snippet-list', request=request)
+ 'users': reverse('user-list', request=request, format=format),
+ 'snippets': reverse('snippet-list', request=request, format=format)
})
Notice that we're using REST framework's `reverse` function in order to return fully-qualified URLs.
@@ -34,8 +34,8 @@ Instead of using a concrete generic view, we'll use the base class for represent
from rest_framework import renderers
from rest_framework.response import Response
- class SnippetHighlight(generics.SingleObjectAPIView):
- model = Snippet
+ class SnippetHighlight(generics.GenericAPIView):
+ queryset = Snippet.objects.all()
renderer_classes = (renderers.StaticHTMLRenderer,)
def get(self, request, *args, **kwargs):
@@ -70,8 +70,8 @@ The `HyperlinkedModelSerializer` has the following differences from `ModelSerial
* It does not include the `pk` field by default.
* It includes a `url` field, using `HyperlinkedIdentityField`.
-* Relationships use `HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField`,
- instead of `PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField`.
+* Relationships use `HyperlinkedRelatedField`,
+ instead of `PrimaryKeyRelatedField`.
We can easily re-write our existing serializers to use hyperlinking.
@@ -86,7 +86,7 @@ We can easily re-write our existing serializers to use hyperlinking.
class UserSerializer(serializers.HyperlinkedModelSerializer):
- snippets = serializers.ManyHyperlinkedRelatedField(view_name='snippet-detail')
+ snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail')
class Meta:
model = User
@@ -116,21 +116,21 @@ After adding all those names into our URLconf, our final `'urls.py'` file should
url(r'^snippets/(?P<pk>[0-9]+)/$',
views.SnippetDetail.as_view(),
name='snippet-detail'),
- url(r'^snippets/(?P<pk>[0-9]+)/highlight/$'
+ url(r'^snippets/(?P<pk>[0-9]+)/highlight/$',
views.SnippetHighlight.as_view(),
name='snippet-highlight'),
url(r'^users/$',
views.UserList.as_view(),
name='user-list'),
url(r'^users/(?P<pk>[0-9]+)/$',
- views.UserInstance.as_view(),
+ views.UserDetail.as_view(),
name='user-detail')
))
# Login and logout views for the browsable API
urlpatterns += patterns('',
url(r'^api-auth/', include('rest_framework.urls',
- namespace='rest_framework'))
+ namespace='rest_framework')),
)
## Adding pagination
@@ -143,34 +143,16 @@ We can change the default list style to use pagination, by modifying our `settin
'PAGINATE_BY': 10
}
-Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well seperated 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.
We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.
-## Reviewing our work
+## Browsing the API
-If we open a browser and navigate to the browseable API, you'll find that you can now work your way around the API simply by following links.
+If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.
You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.
-We've now got a complete pastebin Web API, which is fully web browseable, and comes complete with authentication, per-object permissions, and multiple renderer formats.
+In [part 6][tut-6] of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.
-We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.
-
-You can review the final [tutorial code][repo] on GitHub, or try out a live example in [the sandbox][sandbox].
-
-## Onwards and upwards
-
-We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here's a few places you can start:
-
-* Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests.
-* Join the [REST framework discussion group][group], and help build the community.
-* [Follow the author on Twitter][twitter] and say hi.
-
-**Now go build awesome things.**
-
-[repo]: https://github.com/tomchristie/rest-framework-tutorial
-[sandbox]: http://restframework.herokuapp.com/
-[github]: https://github.com/tomchristie/django-rest-framework
-[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
-[twitter]: https://twitter.com/_tomchristie \ No newline at end of file
+[tut-6]: 6-viewsets-and-routers.md
diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md
new file mode 100644
index 00000000..277804e2
--- /dev/null
+++ b/docs/tutorial/6-viewsets-and-routers.md
@@ -0,0 +1,151 @@
+# Tutorial 6 - ViewSets & Routers
+
+REST framework includes an abstraction for dealing with `ViewSets`, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.
+
+`ViewSet` classes are almost the same thing as `View` classes, except that they provide operations such as `read`, or `update`, and not method handlers such as `get` or `put`.
+
+A `ViewSet` class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a `Router` class which handles the complexities of defining the URL conf for you.
+
+## Refactoring to use ViewSets
+
+Let's take our current set of views, and refactor them into view sets.
+
+First of all let's refactor our `UserListView` and `UserDetailView` views into a single `UserViewSet`. We can remove the two views, and replace then with a single class:
+
+ class UserViewSet(viewsets.ReadOnlyModelViewSet):
+ """
+ This viewset automatically provides `list` and `detail` actions.
+ """
+ queryset = User.objects.all()
+ serializer_class = UserSerializer
+
+Here we've used `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.
+
+ from rest_framework import viewsets
+ from rest_framework.decorators import link
+
+ class SnippetViewSet(viewsets.ModelViewSet):
+ """
+ This viewset automatically provides `list`, `create`, `retrieve`,
+ `update` and `destroy` actions.
+
+ Additionally we also provide an extra `highlight` action.
+ """
+ queryset = Snippet.objects.all()
+ serializer_class = SnippetSerializer
+ permission_classes = (permissions.IsAuthenticatedOrReadOnly,
+ IsOwnerOrReadOnly,)
+
+ @link(renderer_classes=[renderers.StaticHTMLRenderer])
+ def highlight(self, request, *args, **kwargs):
+ snippet = self.get_object()
+ return Response(snippet.highlighted)
+
+ def pre_save(self, obj):
+ obj.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.
+
+Notice that we've also used the `@link` decorator to create a custom action, named `highlight`. This decorator can be used to add any custom endpoints that don't fit into the standard `create`/`update`/`delete` style.
+
+Custom actions which use the `@link` decorator will respond to `GET` requests. We could have instead used the `@action` decorator if we wanted an action that responded to `POST` requests.
+
+## Binding ViewSets to URLs explicitly
+
+The handler methods only get bound to the actions when we define the URLConf.
+To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.
+
+In the `urls.py` file we bind our `ViewSet` classes into a set of concrete views.
+
+ from snippets.resources import SnippetResource, UserResource
+
+ snippet_list = SnippetViewSet.as_view({
+ 'get': 'list',
+ 'post': 'create'
+ })
+ snippet_detail = SnippetViewSet.as_view({
+ 'get': 'retrieve',
+ 'put': 'update',
+ 'patch': 'partial_update',
+ 'delete': 'destroy'
+ })
+ snippet_highlight = SnippetViewSet.as_view({
+ 'get': 'highlight'
+ })
+ 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.
+
+Now that we've bound our resources into concrete views, that we can register the views with the URL conf as usual.
+
+ urlpatterns = format_suffix_patterns(patterns('snippets.views',
+ url(r'^$', 'api_root'),
+ url(r'^snippets/$', snippet_list, name='snippet-list'),
+ url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail, name='snippet-detail'),
+ url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),
+ url(r'^users/$', user_list, name='user-list'),
+ url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail')
+ ))
+
+## Using Routers
+
+Because we're using `ViewSet` classes rather than `View` classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a `Router` class. All we need to do is register the appropriate view sets with a router, and let it do the rest.
+
+Here's our re-wired `urls.py` file.
+
+ from snippets import views
+ from rest_framework.routers import DefaultRouter
+
+ # Create a router and register our viewsets with it.
+ router = DefaultRouter()
+ router.register(r'snippets', views.SnippetViewSet)
+ router.register(r'users', views.UserViewSet)
+
+ # The API URLs are now determined automatically by the router.
+ # Additionally, we include the login URLs for the browseable API.
+ urlpatterns = patterns('',
+ url(r'^', include(router.urls)),
+ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
+ )
+
+Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself.
+
+The `DefaultRouter` class we're using also automatically creates the API root view for us, so we can now delete the `api_root` method from our `views` module.
+
+## Trade-offs between views vs viewsets
+
+Using viewsets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.
+
+That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function based views. Using viewsets is less explicit than building your views individually.
+
+## Reviewing our work
+
+With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browseable, and comes complete with authentication, per-object permissions, and multiple renderer formats.
+
+We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.
+
+You can review the final [tutorial code][repo] on GitHub, or try out a live example in [the sandbox][sandbox].
+
+## Onwards and upwards
+
+We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here's a few places you can start:
+
+* Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests.
+* Join the [REST framework discussion group][group], and help build the community.
+* Follow [the author][twitter] on Twitter and say hi.
+
+**Now go build awesome things.**
+
+
+[repo]: https://github.com/tomchristie/rest-framework-tutorial
+[sandbox]: http://restframework.herokuapp.com/
+[github]: https://github.com/tomchristie/django-rest-framework
+[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
+[twitter]: https://twitter.com/_tomchristie
diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md
index 74084541..52fe3acf 100644
--- a/docs/tutorial/quickstart.md
+++ b/docs/tutorial/quickstart.md
@@ -8,7 +8,7 @@ Create a new Django project, and start a new app called `quickstart`. Once you'
First up we're going to define some serializers in `quickstart/serializers.py` that we'll use for our data representations.
- from django.contrib.auth.models import User, Group, Permission
+ from django.contrib.auth.models import User, Group
from rest_framework import serializers
@@ -19,109 +19,64 @@ First up we're going to define some serializers in `quickstart/serializers.py` t
class GroupSerializer(serializers.HyperlinkedModelSerializer):
- permissions = serializers.ManySlugRelatedField(
- slug_field='codename',
- queryset=Permission.objects.all()
- )
-
class Meta:
model = Group
- fields = ('url', 'name', 'permissions')
+ 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.
-We've also overridden the `permission` field on the `GroupSerializer`. In this case we don't want to use a hyperlinked representation, but instead use the list of permission codenames associated with the group, so we've used a `ManySlugRelatedField`, using the `codename` field for the representation.
-
## Views
Right, we'd better write some views then. Open `quickstart/views.py` and get typing.
from django.contrib.auth.models import User, Group
- from rest_framework import generics
- from rest_framework.decorators import api_view
- from rest_framework.reverse import reverse
- from rest_framework.response import Response
+ from rest_framework import viewsets
from quickstart.serializers import UserSerializer, GroupSerializer
- @api_view(['GET'])
- def api_root(request, format=None):
- """
- The entry endpoint of our API.
- """
- return Response({
- 'users': reverse('user-list', request=request),
- 'groups': reverse('group-list', request=request),
- })
-
-
- class UserList(generics.ListCreateAPIView):
- """
- API endpoint that represents a list of users.
- """
- model = User
- serializer_class = UserSerializer
-
-
- class UserDetail(generics.RetrieveUpdateDestroyAPIView):
+ class UserViewSet(viewsets.ModelViewSet):
"""
- API endpoint that represents a single user.
+ API endpoint that allows users to be viewed or edited.
"""
- model = User
+ queryset = User.objects.all()
serializer_class = UserSerializer
- class GroupList(generics.ListCreateAPIView):
+ class GroupViewSet(viewsets.ModelViewSet):
"""
- API endpoint that represents a list of groups.
+ API endpoint that allows groups to be viewed or edited.
"""
- model = Group
- serializer_class = GroupSerializer
-
-
- class GroupDetail(generics.RetrieveUpdateDestroyAPIView):
- """
- API endpoint that represents a single group.
- """
- model = Group
+ queryset = Group.objects.all()
serializer_class = GroupSerializer
-Let's take a moment to look at what we've done here before we move on. We have one function-based view representing the root of the API, and four class-based views which map to our database models, and specify which serializers should be used for representing that data. Pretty simple stuff.
+Rather that write multiple views we're grouping together all the common behavior into classes called `ViewSets`.
+
+We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.
## URLs
-Okay, let's wire this baby up. On to `quickstart/urls.py`...
+Okay, now let's wire up the API URLs. On to `quickstart/urls.py`...
from django.conf.urls import patterns, url, include
- from rest_framework.urlpatterns import format_suffix_patterns
- from quickstart.views import UserList, UserDetail, GroupList, GroupDetail
-
-
- urlpatterns = patterns('quickstart.views',
- url(r'^$', 'api_root'),
- url(r'^users/$', UserList.as_view(), name='user-list'),
- url(r'^users/(?P<pk>\d+)/$', UserDetail.as_view(), name='user-detail'),
- url(r'^groups/$', GroupList.as_view(), name='group-list'),
- url(r'^groups/(?P<pk>\d+)/$', GroupDetail.as_view(), name='group-detail'),
- )
-
-
- # Format suffixes
- urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'api'])
+ from rest_framework import routers
+ from quickstart import views
+ router = routers.DefaultRouter()
+ router.register(r'users', views.UserViewSet)
+ router.register(r'groups', views.GroupViewSet)
- # Default login/logout views
- urlpatterns += patterns('',
+ # Wire up our API using automatic URL routing.
+ # Additionally, we include login URLs for the browseable API.
+ urlpatterns = patterns('',
+ url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
)
-There's a few things worth noting here.
-
-Firstly the names `user-detail` and `group-detail` are important. We're using the default hyperlinked relationships without explicitly specifying the view names, so we need to use names of the style `{modelname}-detail` to represent the model instance views.
+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.
-Secondly, we're modifying the urlpatterns using `format_suffix_patterns`, to append optional `.json` style suffixes to our URLs.
+Again, if we need more control over the API URLs we can simply drop down to using regular class based views, and writing the URL conf explicitly.
-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 browseable 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.
## Settings