aboutsummaryrefslogtreecommitdiffstats
path: root/docs/tutorial
diff options
context:
space:
mode:
Diffstat (limited to 'docs/tutorial')
-rw-r--r--docs/tutorial/1-serialization.md32
-rw-r--r--docs/tutorial/2-requests-and-responses.md32
-rw-r--r--docs/tutorial/3-class-based-views.md51
-rw-r--r--docs/tutorial/4-authentication-permissions-and-throttling.md6
-rw-r--r--docs/tutorial/5-relationships-and-hyperlinked-apis.md6
-rw-r--r--docs/tutorial/6-resource-orientated-projects.md57
6 files changed, 114 insertions, 70 deletions
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index 610d8ed1..cd4b7558 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -45,11 +45,11 @@ The simplest way to get up and running will probably be to use an `sqlite3` data
}
}
-We'll also need to add our new `blog` app and the `djangorestframework` app to `INSTALLED_APPS`.
+We'll also need to add our new `blog` app and the `rest_framework` app to `INSTALLED_APPS`.
INSTALLED_APPS = (
...
- 'djangorestframework',
+ 'rest_framework',
'blog'
)
@@ -67,7 +67,7 @@ For the purposes of this tutorial we're going to start by creating a simple `Com
from django.db import models
- class Comment(models.Model):
+ class Comment(models.Model):
email = models.EmailField()
content = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
@@ -81,10 +81,11 @@ Don't forget to sync the database for the first time.
We're going to create a simple Web API that we can use to edit these comment objects with. The first thing we need is a way of serializing and deserializing the objects into representations such as `json`. We do this by declaring serializers, that work very similarly to Django's forms. Create a file in the project named `serializers.py` and add the following.
from blog import models
- from djangorestframework import serializers
+ from rest_framework import serializers
class CommentSerializer(serializers.Serializer):
+ id = serializers.IntegerField(readonly=True)
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
@@ -114,8 +115,8 @@ Okay, once we've got a few imports out of the way, we'd better create a few comm
from blog.models import Comment
from blog.serializers import CommentSerializer
- from djangorestframework.renderers import JSONRenderer
- from djangorestframework.parsers import JSONParser
+ from rest_framework.renderers import JSONRenderer
+ from rest_framework.parsers import JSONParser
c1 = Comment(email='leila@example.com', content='nothing to say')
c2 = Comment(email='tom@example.com', content='foo bar')
@@ -128,13 +129,13 @@ We've now got a few comment instances to play with. Let's take a look at serial
serializer = CommentSerializer(instance=c1)
serializer.data
- # {'email': u'leila@example.com', 'content': u'nothing to say', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774, tzinfo=<UTC>)}
+ # {'id': 1, 'email': u'leila@example.com', 'content': u'nothing to say', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774, tzinfo=<UTC>)}
At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`.
stream = JSONRenderer().render(serializer.data)
stream
- # '{"email": "leila@example.com", "content": "nothing to say", "created": "2012-08-22T16:20:09.822"}'
+ # '{"id": 1, "email": "leila@example.com", "content": "nothing to say", "created": "2012-08-22T16:20:09.822"}'
Deserialization is similar. First we parse a stream into python native datatypes...
@@ -159,9 +160,10 @@ Edit the `blog/views.py` file, and add the following.
from blog.models import Comment
from blog.serializers import CommentSerializer
- from djangorestframework.renderers import JSONRenderer
- from djangorestframework.parsers import JSONParser
from django.http import HttpResponse
+ from django.views.decorators.csrf import csrf_exempt
+ from rest_framework.renderers import JSONRenderer
+ from rest_framework.parsers import JSONParser
class JSONResponse(HttpResponse):
@@ -177,6 +179,7 @@ Edit the `blog/views.py` file, and add the following.
The root of our API is going to be a view that supports listing all the existing comments, or creating a new comment.
+ @csrf_exempt
def comment_root(request):
"""
List all comments, or create a new comment.
@@ -194,10 +197,13 @@ The root of our API is going to be a view that supports listing all the existing
comment.save()
return JSONResponse(serializer.data, status=201)
else:
- return JSONResponse(serializer.error_data, 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.
We'll also need a view which corrosponds to an individual comment, and can be used to retrieve, update or delete the comment.
+ @csrf_exempt
def comment_instance(request, pk):
"""
Retrieve, update or delete a comment instance.
@@ -219,7 +225,7 @@ We'll also need a view which corrosponds to an individual comment, and can be us
comment.save()
return JSONResponse(serializer.data)
else:
- return JSONResponse(serializer.error_data, status=400)
+ return JSONResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
comment.delete()
@@ -251,4 +257,4 @@ Our API views don't do anything particularly special at the moment, beyond serve
We'll see how we can start to improve things in [part 2 of the tutorial][tut-2].
[virtualenv]: http://www.virtualenv.org/en/latest/index.html
-[tut-2]: 2-requests-and-responses.md \ No newline at end of file
+[tut-2]: 2-requests-and-responses.md
diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md
index 89f92c4b..d889b1e0 100644
--- a/docs/tutorial/2-requests-and-responses.md
+++ b/docs/tutorial/2-requests-and-responses.md
@@ -40,9 +40,9 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On
from blog.models import Comment
from blog.serializers import CommentSerializer
- from djangorestframework import status
- from djangorestframework.decorators import api_view
- from djangorestframework.response import Response
+ from rest_framework import status
+ from rest_framework.decorators import api_view
+ from rest_framework.response import Response
@api_view(['GET', 'POST'])
def comment_root(request):
@@ -61,7 +61,7 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On
comment.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
- return Response(serializer.error_data, 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.
@@ -87,7 +87,7 @@ Our instance view is an improvement over the previous example. It's a little mo
comment.save()
return Response(serializer.data)
else:
- return Response(serializer.error_data, status=status.HTTP_400_BAD_REQUEST)
+ return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
comment.delete()
@@ -112,7 +112,7 @@ and
Now update the `urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs.
from django.conf.urls import patterns, url
- from djangorestframework.urlpatterns import format_suffix_patterns
+ from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = patterns('blogpost.views',
url(r'^$', 'comment_root'),
@@ -125,21 +125,27 @@ We don't necessarily need to add these extra url patterns in, but it gives us a
## How's it looking?
-Go ahead and test the API from the command line, as we did in [tutorial part 1][2]. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.
+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**
-Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/][3]."
+Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/][devserver]."
**Note: Right now the Browseable API only works with the CBV's. Need to fix that.**
-**TODO: Describe browseable API awesomeness**
+### 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.
+
+See the [browsable api][browseable-api] topic for more information about the browsable API feature and how to customize it.
+
## What's next?
-In [tutorial part 3][4], we'll start using class based views, and see how generic views reduce the amount of code we need to write.
+In [tutorial part 3][tut-3], we'll start using class based views, and see how generic views reduce the amount of code we need to write.
[json-url]: http://example.com/api/items/4.json
-[2]: 1-serialization.md
-[3]: http://127.0.0.1:8000/
-[4]: 3-class-based-views.md \ No newline at end of file
+[devserver]: http://127.0.0.1:8000/
+[browseable-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 24785179..25d5773f 100644
--- a/docs/tutorial/3-class-based-views.md
+++ b/docs/tutorial/3-class-based-views.md
@@ -1,6 +1,6 @@
# Tutorial 3: Class Based Views
-We can also write our API views using class based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code [DRY][1].
+We can also write our API views using class based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code [DRY][dry].
## Rewriting our API using class based views
@@ -9,9 +9,9 @@ We'll start by rewriting the root view as a class based view. All this involves
from blog.models import Comment
from blog.serializers import CommentSerializer
from django.http import Http404
- from djangorestframework.views import APIView
- from djangorestframework.response import Response
- from djangorestframework import status
+ from rest_framework.views import APIView
+ from rest_framework.response import Response
+ from rest_framework import status
class CommentRoot(APIView):
@@ -31,8 +31,6 @@ We'll start by rewriting the root view as a class based view. All this involves
return Response(serializer.serialized, status=status.HTTP_201_CREATED)
return Response(serializer.serialized_errors, status=status.HTTP_400_BAD_REQUEST)
- comment_root = CommentRoot.as_view()
-
So far, so good. It looks pretty similar to the previous case, but we've got better seperation between the different HTTP methods. We'll also need to update the instance view.
class CommentInstance(APIView):
@@ -55,19 +53,31 @@ So far, so good. It looks pretty similar to the previous case, but we've got be
comment = self.get_object(pk)
serializer = CommentSerializer(request.DATA, instance=comment)
if serializer.is_valid():
- comment = serializer.deserialized
+ comment = serializer.object
comment.save()
return Response(serializer.data)
- return Response(serializer.error_data, status=status.HTTP_400_BAD_REQUEST)
+ return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
comment = self.get_object(pk)
comment.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
- comment_instance = CommentInstance.as_view()
-
That's looking good. Again, it's still pretty similar to the function based view right now.
+
+We'll also need to refactor our URLconf slightly now we're using class based views.
+
+ from django.conf.urls import patterns, url
+ from rest_framework.urlpatterns import format_suffix_patterns
+ from blogpost import views
+
+ urlpatterns = patterns('',
+ url(r'^$', views.CommentRoot.as_view()),
+ url(r'^(?P<pk>[0-9]+)$', views.CommentInstance.as_view())
+ )
+
+ urlpatterns = format_suffix_patterns(urlpatterns)
+
Okay, we're done. If you run the development server everything should be working just as before.
## Using mixins
@@ -80,8 +90,8 @@ Let's take a look at how we can compose our views by using the mixin classes.
from blog.models import Comment
from blog.serializers import CommentSerializer
- from djangorestframework import mixins
- from djangorestframework import generics
+ from rest_framework import mixins
+ from rest_framework import generics
class CommentRoot(mixins.ListModelMixin,
mixins.CreateModelMixin,
@@ -95,8 +105,6 @@ 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)
- comment_root = CommentRoot.as_view()
-
We'll take a moment to examine exactly what's happening here - We're building our view using `MultipleObjectBaseView`, 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 explictly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far.
@@ -117,8 +125,6 @@ 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)
- comment_instance = CommentInstance.as_view()
-
Pretty similar. This time we're using the `SingleObjectBaseView` class to provide the core functionality, and adding in mixins to provide the `.retrieve()`, `.update()` and `.destroy()` actions.
## Using generic class based views
@@ -127,26 +133,21 @@ Using the mixin classes we've rewritten the views to use slightly less code than
from blog.models import Comment
from blog.serializers import CommentSerializer
- from djangorestframework import generics
+ from rest_framework import generics
class CommentRoot(generics.RootAPIView):
model = Comment
serializer_class = CommentSerializer
- comment_root = CommentRoot.as_view()
-
class CommentInstance(generics.InstanceAPIView):
model = Comment
serializer_class = CommentSerializer
- comment_instance = CommentInstance.as_view()
-
-
Wow, that's pretty concise. We've got a huge amount for free, and our code looks like good, clean, idomatic Django.
-Next we'll move onto [part 4 of the tutorial][2], where we'll take a look at how we can customize the behavior of our views to support a range of authentication, permissions, throttling and other aspects.
+Next we'll move onto [part 4 of the tutorial][tut-4], where we'll take a look at how we can customize the behavior of our views to support a range of authentication, permissions, throttling and other aspects.
-[1]: http://en.wikipedia.org/wiki/Don't_repeat_yourself
-[2]: 4-authentication-permissions-and-throttling.md
+[dry]: http://en.wikipedia.org/wiki/Don't_repeat_yourself
+[tut-4]: 4-authentication-permissions-and-throttling.md
diff --git a/docs/tutorial/4-authentication-permissions-and-throttling.md b/docs/tutorial/4-authentication-permissions-and-throttling.md
index 5c37ae13..c8d7cbd3 100644
--- a/docs/tutorial/4-authentication-permissions-and-throttling.md
+++ b/docs/tutorial/4-authentication-permissions-and-throttling.md
@@ -1,3 +1,5 @@
-[part 5][5]
+# Tutorial 4: Authentication & Permissions
-[5]: 5-relationships-and-hyperlinked-apis.md \ No newline at end of file
+Nothing to see here. Onwards to [part 5][tut-5].
+
+[tut-5]: 5-relationships-and-hyperlinked-apis.md \ No newline at end of file
diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
index 3d9598d7..a76f81e8 100644
--- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md
+++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
@@ -1,9 +1,11 @@
+# Tutorial 5 - Relationships & Hyperlinked APIs
+
**TODO**
* Create BlogPost model
* Demonstrate nested relationships
* Demonstrate and describe hyperlinked relationships
-[part 6][1]
+Onwards to [part 6][tut-6].
-[1]: 6-resource-orientated-projects.md
+[tut-6]: 6-resource-orientated-projects.md
diff --git a/docs/tutorial/6-resource-orientated-projects.md b/docs/tutorial/6-resource-orientated-projects.md
index 4282c25d..3c3e7fed 100644
--- a/docs/tutorial/6-resource-orientated-projects.md
+++ b/docs/tutorial/6-resource-orientated-projects.md
@@ -1,31 +1,56 @@
-serializers.py
+# Tutorial 6 - Resources
- class BlogPostSerializer(URLModelSerializer):
- class Meta:
- model = BlogPost
+Resource classes are just View classes that don't have any handler methods bound to them. The actions on a resource are defined,
- class CommentSerializer(URLModelSerializer):
- class Meta:
- model = Comment
+This allows us to:
+
+* Encapsulate common behaviour accross a class of views, in a single Resource class.
+* Seperate out the actions of a Resource from the specfics of how those actions should be bound to a particular set of URLs.
+
+## Refactoring to use Resources, not Views
+
+For instance, we can re-write our 4 sets of views into something more compact...
resources.py
class BlogPostResource(ModelResource):
serializer_class = BlogPostSerializer
model = BlogPost
- permissions = [AdminOrAnonReadonly()]
- throttles = [AnonThrottle(rate='5/min')]
+ permissions_classes = (permissions.IsAuthenticatedOrReadOnly,)
+ throttle_classes = (throttles.UserRateThrottle,)
class CommentResource(ModelResource):
serializer_class = CommentSerializer
model = Comment
- permissions = [AdminOrAnonReadonly()]
- throttles = [AnonThrottle(rate='5/min')]
+ permissions_classes = (permissions.IsAuthenticatedOrReadOnly,)
+ throttle_classes = (throttles.UserRateThrottle,)
+
+## Binding Resources to URLs explicitly
+The handler methods only get bound to the actions when we define the URLConf. Here's our urls.py:
-Now that we're using Resources rather than Views, we don't need to design the urlconf ourselves. The conventions for wiring up resources into views and urls are handled automatically. All we need to do is register the appropriate resources with a router, and let it do the rest. Here's our re-wired `urls.py` file.
+ comment_root = CommentResource.as_view(actions={
+ 'get': 'list',
+ 'post': 'create'
+ })
+ comment_instance = CommentInstance.as_view(actions={
+ 'get': 'retrieve',
+ 'put': 'update',
+ 'delete': 'destroy'
+ })
+ ... # And for blog post
+
+ urlpatterns = patterns('blogpost.views',
+ url(r'^$', comment_root),
+ url(r'^(?P<pk>[0-9]+)$', comment_instance)
+ ... # And for blog post
+ )
+
+## Using Routers
+
+Right now that hasn't really saved us a lot of code. However, now that we're using Resources rather than Views, we actually don't need to design the urlconf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using `Router` classes. All we need to do is register the appropriate resources with a router, and let it do the rest. Here's our re-wired `urls.py` file.
from blog import resources
- from djangorestframework.routers import DefaultRouter
+ from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(resources.BlogPostResource)
@@ -44,6 +69,8 @@ We've reached the end of our tutorial. If you want to get more involved in the
* Contribute on GitHub by reviewing issues, and submitting issues or pull requests.
* Join the REST framework group, and help build the community.
-* Follow me [on Twitter](https://twitter.com/_tomchristie) and say hi.
+* Follow me [on Twitter][twitter] and say hi.
+
+**Now go build some awesome things.**
-Now go build something great. \ No newline at end of file
+[twitter]: https://twitter.com/_tomchristie