From 578017e01d1da4746ae0045268043cfd74d41b42 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 29 Aug 2012 20:57:37 +0100 Subject: New docs --- docs/tutorial/1-serialization.md | 236 +++++++++++++++++++++ docs/tutorial/2-requests-and-responses.md | 137 ++++++++++++ docs/tutorial/3-class-based-views.md | 137 ++++++++++++ .../4-authentication-permissions-and-throttling.md | 3 + .../5-relationships-and-hyperlinked-apis.md | 9 + docs/tutorial/6-resource-orientated-projects.md | 49 +++++ 6 files changed, 571 insertions(+) create mode 100644 docs/tutorial/1-serialization.md create mode 100644 docs/tutorial/2-requests-and-responses.md create mode 100644 docs/tutorial/3-class-based-views.md create mode 100644 docs/tutorial/4-authentication-permissions-and-throttling.md create mode 100644 docs/tutorial/5-relationships-and-hyperlinked-apis.md create mode 100644 docs/tutorial/6-resource-orientated-projects.md (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md new file mode 100644 index 00000000..55a9f679 --- /dev/null +++ b/docs/tutorial/1-serialization.md @@ -0,0 +1,236 @@ +# Tutorial 1: Serialization + +## Introduction + +This tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together. + +## Getting started + +To get started, let's create a new project to work with. + + django-admin.py startproject tutorial + cd tutorial + +Once that's done we can create an app that we'll use to create a simple Web API. + + python manage.py startapp blog + +The simplest way to get up and running will probably be to use an `sqlite3` database for the tutorial. Edit the `tutorial/settings.py` file, and set the default database `"ENGINE"` to `"sqlite3"`, and `"NAME"` to `"tmp.db"`. + + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': 'tmp.db', + 'USER': '', + 'PASSWORD': '', + 'HOST': '', + 'PORT': '', + } + } + +We'll also need to add our new `blog` app and the `djangorestframework` app to `INSTALLED_APPS`. + + INSTALLED_APPS = ( + ... + 'djangorestframework', + 'blog' + ) + +We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our blog views. + + urlpatterns = patterns('', + url(r'^', include('blog.urls')), + ) + +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 `Comment` model that is used to store comments against a blog post. Go ahead and edit the `blog` app's `models.py` file. + + from django.db import models + + class Comment(models.Model): + email = models.EmailField() + content = models.CharField(max_length=200) + created = models.DateTimeField(auto_now_add=True) + +Don't forget to sync the database for the first time. + + python manage.py syncdb + +## Creating a Serializer class + +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 + + + class CommentSerializer(serializers.Serializer): + email = serializers.EmailField() + content = serializers.CharField(max_length=200) + created = serializers.DateTimeField() + + def restore_object(self, attrs, instance=None): + """ + Create or update a new comment instance. + """ + if instance: + instance.email = attrs['email'] + instance.content = attrs['content'] + instance.created = attrs['created'] + return instance + return models.Comment(**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. + +We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit. + +## Working with Serializers + +Before we go any further we'll familiarise ourselves with using our new Serializer class. Let's drop into the Django shell. + + python manage.py shell + +Okay, once we've got a few imports out of the way, we'd better create a few comments to work with. + + from blog.models import Comment + from blog.serializers import CommentSerializer + from djangorestframework.renderers import JSONRenderer + from djangorestframework.parsers import JSONParser + + c1 = Comment(email='leila@example.com', content='nothing to say') + c2 = Comment(email='tom@example.com', content='foo bar') + c3 = Comment(email='anna@example.com', content='LOLZ!') + c1.save() + c2.save() + c3.save() + +We've now got a few comment instances to play with. Let's take a look at serializing one of those instances. + + 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)} + +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"}' + +Deserialization is similar. First we parse a stream into python native datatypes... + + data = JSONParser().parse(stream) + +...then we restore those native datatypes into to a fully populated object instance. + + serializer = CommentSerializer(data) + serializer.is_valid() + # True + serializer.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. + +## Writing regular Django views using our Serializers + +Let's see how we can write some API views using our new Serializer class. +We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into `json`. + +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 + + + class JSONResponse(HttpResponse): + """ + An HttpResponse that renders it's content into JSON. + """ + + def __init__(self, data, **kwargs): + content = JSONRenderer().render(data) + 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 comments, or creating a new comment. + + def comment_root(request): + """ + List all comments, or create a new comment. + """ + if request.method == 'GET': + comments = Comment.objects.all() + serializer = CommentSerializer(instance=comments) + return JSONResponse(serializer.data) + + elif request.method == 'POST': + data = JSONParser().parse(request) + serializer = CommentSerializer(data) + if serializer.is_valid(): + comment = serializer.object + comment.save() + return JSONResponse(serializer.data, status=201) + else: + return JSONResponse(serializer.error_data, status=400) + +We'll also need a view which corrosponds to an individual comment, and can be used to retrieve, update or delete the comment. + + def comment_instance(request, pk): + """ + Retrieve, update or delete a comment instance. + """ + try: + comment = Comment.objects.get(pk=pk) + except Comment.DoesNotExist: + return HttpResponse(status=404) + + if request.method == 'GET': + serializer = CommentSerializer(instance=comment) + return JSONResponse(serializer.data) + + elif request.method == 'PUT': + data = JSONParser().parse(request) + serializer = CommentSerializer(data, instance=comment) + if serializer.is_valid(): + comment = serializer.object + comment.save() + return JSONResponse(serializer.data) + else: + return JSONResponse(serializer.error_data, status=400) + + elif request.method == 'DELETE': + comment.delete() + return HttpResponse(status=204) + +Finally we need to wire these views up, in the `tutorial/urls.py` file. + + from django.conf.urls import patterns, url + + urlpatterns = patterns('blog.views', + url(r'^$', 'comment_root'), + url(r'^(?P[0-9]+)$', 'comment_instance') + ) + +It's worth noting that there's 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** + +**TODO: Describe opening in a web browser and viewing json output** + +## Where are we now + +We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views. + +Our API views don't do anything particularly special at the moment, beyond serve `json` responses, and there's some error handling edge cases we'd still like to clean up, but it's a functioning Web API. + +We'll see how we can start to improve things in [part 2 of the tutorial][1]. + +[1]: 2-requests-and-responses.md \ No newline at end of file diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md new file mode 100644 index 00000000..2bb6c20e --- /dev/null +++ b/docs/tutorial/2-requests-and-responses.md @@ -0,0 +1,137 @@ +# Tutorial 2: Request and Response objects + +From this point we're going to really start covering the core of REST framework. +Let's introduce a couple of essential building blocks. + +## Request objects + +REST framework intoduces 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. + +## 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. + + return Response(data) # Renders to content type as requested by the client. + +## Status codes + +Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as `HTTP_400_BAD_REQUEST` in the `status` module. It's a good idea to use these throughout rather than using numeric identifiers. + +## Wrapping API views + +REST framework provides two wrappers you can use to write API views. + +1. The `@api_view` decorator for working with function based views. +2. The `APIView` class for working with class based views. + +These wrappers provide a few bits of functionality such as making sure you recieve `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed. + +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. + + from djangorestframework.decorators import api_view + from djangorestframework.status import * + + @api_view(allow=['GET', 'POST']) + def comment_root(request): + """ + List all comments, or create a new comment. + """ + if request.method == 'GET': + comments = Comment.objects.all() + serializer = CommentSerializer(instance=comments) + return Response(serializer.data) + + elif request.method == 'POST': + serializer = CommentSerializer(request.DATA) + if serializer.is_valid(): + comment = serializer.object + comment.save() + return Response(serializer.data, status=HTTP_201_CREATED) + else: + return Response(serializer.error_data, status=HTTP_400_BAD_REQUEST) + + +Our instance view is an improvement over the previous example. It's slightly more concise, and the code now feels very similar to if we were working with the Forms API. + + @api_view(allow=['GET', 'PUT', 'DELETE']) + def comment_instance(request, pk): + """ + Retrieve, update or delete a comment instance. + """ + try: + comment = Comment.objects.get(pk=pk) + except Comment.DoesNotExist: + return Response(status=HTTP_404_NOT_FOUND) + + if request.method == 'GET': + serializer = CommentSerializer(instance=comment) + return Response(serializer.data) + + elif request.method == 'PUT': + serializer = CommentSerializer(request.DATA, instance=comment) + if serializer.is_valid(): + comment = serializer.object + comment.save() + return Response(serializer.data) + else: + return Response(serializer.error_data, status=HTTP_400_BAD_REQUEST) + + elif request.method == 'DELETE': + comment.delete() + return Response(status=HTTP_204_NO_CONTENT) + +This should all feel very familiar - it looks a lot like working with forms in regular Django views. + +Notice that we're no longer explicitly tying our requests or responses to a given content type. `request.DATA` can handle incoming `json` requests, but it can also handle `yaml` and other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us. + +## Adding optional format suffixes to our URLs + +To take advantage of that, let's add support for format suffixes to our API endpoints, so that we can use URLs that explicitly refer to a given format. That means our API will be able to handle URLs such as [http://example.com/api/items/4.json][1]. + +Start by adding a `format` keyword argument to both of the views, like so. + + def comment_root(request, format=None): + +and + + def comment_instance(request, pk, format=None): + +Now update the `urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs. + + from djangorestframework.urlpatterns import format_suffix_patterns + + urlpatterns = patterns('blogpost.views', + url(r'^$', 'comment_root'), + url(r'^(?P[0-9]+)$', 'comment_instance') + ) + + 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 refering to a specific format. + +## 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. + +**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]. + +**TODO: Describe browseable API awesomeness** + +## 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. + +[1]: 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 diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md new file mode 100644 index 00000000..e56c7847 --- /dev/null +++ b/docs/tutorial/3-class-based-views.md @@ -0,0 +1,137 @@ +# Tutorial 3: Using 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]. + +## Rewriting our API using class based views + +We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring. + + from blog.models import Comment + from blog.serializers import ComentSerializer + from django.http import Http404 + from djangorestframework.views import APIView + from djangorestframework.response import Response + from djangorestframework.status import * + + class CommentRoot(views.APIView): + """ + List all comments, or create a new comment. + """ + def get(self, request, format=None): + comments = Comment.objects.all() + serializer = ComentSerializer(instance=comments) + return Response(serializer.data) + + def post(self, request, format=None) + serializer = ComentSerializer(request.DATA) + if serializer.is_valid(): + comment = serializer.object + comment.save() + return Response(serializer.serialized, status=HTTP_201_CREATED) + else: + return Response(serializer.serialized_errors, status=HTTP_400_BAD_REQUEST) + +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(views.APIView): + """ + Retrieve, update or delete a comment instance. + """ + + def get_object(self, pk): + try: + return Poll.objects.get(pk=pk) + except Poll.DoesNotExist: + raise Http404 + + def get(self, request, pk, format=None): + comment = self.get_object(pk) + serializer = CommentSerializer(instance=comment) + return Response(serializer.data) + + def put(self, request, pk, format=None): + comment = self.get_object(pk) + serializer = CommentSerializer(request.DATA, instance=comment) + if serializer.is_valid(): + comment = serializer.deserialized + comment.save() + return Response(serializer.data) + else: + return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) + + def delete(self, request, pk, format=None): + comment = self.get_object(pk) + comment.delete() + return Response(status=HTTP_204_NO_CONTENT) + +That's looking good. Again, it's still pretty similar to the function based view right now. + +Since we're now working with class based views, rather than function based views, we'll also need to update our urlconf slightly. + + from blogpost import views + from djangorestframework.urlpatterns import format_suffix_patterns + + urlpatterns = patterns('', + url(r'^$', views.CommentRoot.as_view()), + url(r'^(?P[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 + +One of the big wins of using class based views is that it allows us to easily compose reusable bits of behaviour. + +The create/retrieve/update/delete operations that we've been using so far is going to be pretty simliar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes. + +We can compose those mixin classes, to recreate our existing API behaviour with less code. + + from blog.models import Comment + from blog.serializers import CommentSerializer + from djangorestframework import mixins, views + + class CommentRoot(mixins.ListModelQuerysetMixin, + mixins.CreateModelInstanceMixin, + views.BaseRootAPIView): + model = Comment + serializer_class = CommentSerializer + + get = list + post = create + + class CommentInstance(mixins.RetrieveModelInstanceMixin, + mixins.UpdateModelInstanceMixin, + mixins.DestroyModelInstanceMixin, + views.BaseInstanceAPIView): + model = Comment + serializer_class = CommentSerializer + + get = retrieve + put = update + delete = destroy + +## Reusing generic class based views + +That's a lot less code than before, but we can go one step further still. REST framework also provides a set of already mixed-in views. + + from blog.models import Comment + from blog.serializers import CommentSerializer + from djangorestframework import views + + class CommentRoot(views.RootAPIView): + model = Comment + serializer_class = CommentSerializer + + class CommentInstance(views.InstanceAPIView): + model = Comment + serializer_class = CommentSerializer + +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. + +[1]: http://en.wikipedia.org/wiki/Don't_repeat_yourself +[2]: 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 new file mode 100644 index 00000000..5c37ae13 --- /dev/null +++ b/docs/tutorial/4-authentication-permissions-and-throttling.md @@ -0,0 +1,3 @@ +[part 5][5] + +[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 new file mode 100644 index 00000000..3d9598d7 --- /dev/null +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -0,0 +1,9 @@ +**TODO** + +* Create BlogPost model +* Demonstrate nested relationships +* Demonstrate and describe hyperlinked relationships + +[part 6][1] + +[1]: 6-resource-orientated-projects.md diff --git a/docs/tutorial/6-resource-orientated-projects.md b/docs/tutorial/6-resource-orientated-projects.md new file mode 100644 index 00000000..ce51cce5 --- /dev/null +++ b/docs/tutorial/6-resource-orientated-projects.md @@ -0,0 +1,49 @@ +serializers.py + + class BlogPostSerializer(URLModelSerializer): + class Meta: + model = BlogPost + + class CommentSerializer(URLModelSerializer): + class Meta: + model = Comment + +resources.py + + class BlogPostResource(ModelResource): + serializer_class = BlogPostSerializer + model = BlogPost + permissions = [AdminOrAnonReadonly()] + throttles = [AnonThrottle(rate='5/min')] + + class CommentResource(ModelResource): + serializer_class = CommentSerializer + model = Comment + permissions = [AdminOrAnonReadonly()] + throttles = [AnonThrottle(rate='5/min')] + +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. + + from blog import resources + from djangorestframework.routers import DefaultRouter + + router = DefaultRouter() + router.register(resources.BlogPostResource) + router.register(resources.CommentResource) + urlpatterns = router.urlpatterns + +## Trade-offs between views vs resources. + +Writing resource-orientated code can be a good thing. It helps ensure that URL conventions will be consistent across your APIs, and minimises the amount of code you need to write. + +The trade-off is that the behaviour is less explict. It can be more difficult to determine what code path is being followed, or where to override some behaviour. + +## 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 by reviewing issues, and submitting issues or pull requests. +* Join the REST framework group, and help build the community. +* Follow me on Twitter and say hi. + +Now go build something great. \ No newline at end of file -- cgit v1.2.3 From 247a422a64378c968f0972b1797b919ae03296bb Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Sep 2012 12:41:52 +0100 Subject: Add virtualenv to start of tutorial --- docs/tutorial/1-serialization.md | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 55a9f679..6a97f779 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -6,6 +6,18 @@ This tutorial will walk you through the building blocks that make up REST framew ## Getting started +Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is keep nicely isolated from any other projects we're working on. + + mkdir -p ~/.env + virtualenv --no-site-packages ~/.env/djangorestframework + source ~/.env/djangorestframework/env/bin/activate + +Now that we're inside a virtualenv environment, we can install our packages requirements. + + pip install django + pip install djangorestframework + +Now we're ready to get coding. To get started, let's create a new project to work with. django-admin.py startproject tutorial @@ -231,6 +243,7 @@ We're doing okay so far, we've got a serialization API that feels pretty similar Our API views don't do anything particularly special at the moment, beyond serve `json` responses, and there's some error handling edge cases we'd still like to clean up, but it's a functioning Web API. -We'll see how we can start to improve things in [part 2 of the tutorial][1]. +We'll see how we can start to improve things in [part 2 of the tutorial][tut-2]. -[1]: 2-requests-and-responses.md \ No newline at end of file +[virtualenv]: http://www.virtualenv.org/en/latest/index.html +[tut-2]: 2-requests-and-responses.md \ No newline at end of file -- cgit v1.2.3 From ebbaff0853d49cd436b416beeb28220922bfc977 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Sep 2012 13:10:39 +0100 Subject: Update virtualenv notes --- docs/tutorial/1-serialization.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 6a97f779..3cfcf871 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -4,20 +4,24 @@ This tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together. -## Getting started +## Setting up a new environment Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is keep nicely isolated from any other projects we're working on. - mkdir -p ~/.env - virtualenv --no-site-packages ~/.env/djangorestframework - source ~/.env/djangorestframework/env/bin/activate + mkdir ~/env + virtualenv --no-site-packages ~/env/djangorestframework + source ~/env/djangorestframework/bin/activate -Now that we're inside a virtualenv environment, we can install our packages requirements. +Now that we're inside a virtualenv environment, we can install our package requirements. pip install django pip install djangorestframework -Now we're ready to get coding. +***Note:** To exit the virtualenv environment at any time, just type `deactivate`. For more information see the [virtualenv documentation][virtualenv].* + +## Getting started + +Okay, we're ready to get coding. To get started, let's create a new project to work with. django-admin.py startproject tutorial -- cgit v1.2.3 From a25b4be4418a2a94e38a77b13cc234ca68e8322c Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Sep 2012 13:30:20 +0100 Subject: Support generators --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 3cfcf871..13dcb9cc 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -17,7 +17,7 @@ Now that we're inside a virtualenv environment, we can install our package requi pip install django pip install djangorestframework -***Note:** To exit the virtualenv environment at any time, just type `deactivate`. For more information see the [virtualenv documentation][virtualenv].* +**Note:** To exit the virtualenv environment at any time, just type `deactivate`. For more information see the [virtualenv documentation][virtualenv]. ## Getting started -- cgit v1.2.3 From d180e984e9779673c2d8aab3c65b4763432ba6b5 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Sep 2012 13:44:49 +0100 Subject: Neater virtualenv in tutorial --- docs/tutorial/1-serialization.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 13dcb9cc..0b6eac9d 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -9,8 +9,8 @@ This tutorial will walk you through the building blocks that make up REST framew Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is keep nicely isolated from any other projects we're working on. mkdir ~/env - virtualenv --no-site-packages ~/env/djangorestframework - source ~/env/djangorestframework/bin/activate + virtualenv --no-site-packages ~/env/tutorial + source ~/env/tutorial/bin/activate Now that we're inside a virtualenv environment, we can install our package requirements. -- cgit v1.2.3 From 7abef9ac3b3fb20a6cdef5d52c640e5725c93437 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Sep 2012 14:28:40 +0100 Subject: Parsers may return raw data, or a DataAndFiles object --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 0b6eac9d..34bac155 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -127,7 +127,7 @@ 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)} + # {'email': u'leila@example.com', 'content': u'nothing to say', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774, tzinfo=)} At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`. -- cgit v1.2.3 From 149b00a070fcbfd44feee5b37096081e18356f93 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Sep 2012 15:57:43 +0100 Subject: Added the api_view decorator --- docs/tutorial/1-serialization.md | 2 +- docs/tutorial/2-requests-and-responses.md | 31 ++++++++++++++++++------------- 2 files changed, 19 insertions(+), 14 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 34bac155..3d6615d9 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -145,7 +145,7 @@ Deserialization is similar. First we parse a stream into python native datatype serializer.is_valid() # True serializer.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. diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 2bb6c20e..9309f6e0 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -36,14 +36,19 @@ The wrappers also provide behaviour such as returning `405 Method Not Allowed` r Okay, let's go ahead and start using these new components to write a few views. +We don't need our `JSONResponse` class anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly. + + from blog.models import Comment + from blog.serializers import CommentSerializer + from djangorestframework import status from djangorestframework.decorators import api_view - from djangorestframework.status import * + from djangorestframework.response import Response - @api_view(allow=['GET', 'POST']) + @api_view(['GET', 'POST']) def comment_root(request): """ List all comments, or create a new comment. - """ + """ if request.method == 'GET': comments = Comment.objects.all() serializer = CommentSerializer(instance=comments) @@ -54,14 +59,14 @@ Okay, let's go ahead and start using these new components to write a few views. if serializer.is_valid(): comment = serializer.object comment.save() - return Response(serializer.data, status=HTTP_201_CREATED) + return Response(serializer.data, status=status.HTTP_201_CREATED) else: - return Response(serializer.error_data, status=HTTP_400_BAD_REQUEST) + return Response(serializer.error_data, status=status.HTTP_400_BAD_REQUEST) -Our instance view is an improvement over the previous example. It's slightly more concise, and the code now feels very similar to if we were working with the Forms API. +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. - @api_view(allow=['GET', 'PUT', 'DELETE']) + @api_view(['GET', 'PUT', 'DELETE']) def comment_instance(request, pk): """ Retrieve, update or delete a comment instance. @@ -69,7 +74,7 @@ Our instance view is an improvement over the previous example. It's slightly mo try: comment = Comment.objects.get(pk=pk) except Comment.DoesNotExist: - return Response(status=HTTP_404_NOT_FOUND) + return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = CommentSerializer(instance=comment) @@ -82,19 +87,19 @@ Our instance view is an improvement over the previous example. It's slightly mo comment.save() return Response(serializer.data) else: - return Response(serializer.error_data, status=HTTP_400_BAD_REQUEST) + return Response(serializer.error_data, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': comment.delete() - return Response(status=HTTP_204_NO_CONTENT) + return Response(status=status.HTTP_204_NO_CONTENT) -This should all feel very familiar - it looks a lot like working with forms in regular Django views. +This should all feel very familiar - there's not a lot different to working with regular Django views. Notice that we're no longer explicitly tying our requests or responses to a given content type. `request.DATA` can handle incoming `json` requests, but it can also handle `yaml` and other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us. ## Adding optional format suffixes to our URLs -To take advantage of that, let's add support for format suffixes to our API endpoints, so that we can use URLs that explicitly refer to a given format. That means our API will be able to handle URLs such as [http://example.com/api/items/4.json][1]. +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. @@ -131,7 +136,7 @@ Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/][3 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. -[1]: http://example.com/api/items/4.json +[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 -- cgit v1.2.3 From 93189ec27d53d3216d452abdc2711e973a888d0c Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Sep 2012 16:06:17 +0100 Subject: Added format_suffix_patterns, and fix up settings --- docs/tutorial/2-requests-and-responses.md | 1 + 1 file changed, 1 insertion(+) (limited to 'docs/tutorial') diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 9309f6e0..4ff303ae 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -111,6 +111,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 urlpatterns = patterns('blogpost.views', -- cgit v1.2.3 From 1a1ccf94c2c0cadee8b0bd1c8f85c591c650d763 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Sep 2012 16:42:57 +0100 Subject: Fixes to APIView --- docs/tutorial/3-class-based-views.md | 35 ++++++++++++----------------------- 1 file changed, 12 insertions(+), 23 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index e56c7847..616a6058 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -11,9 +11,9 @@ We'll start by rewriting the root view as a class based view. All this involves from django.http import Http404 from djangorestframework.views import APIView from djangorestframework.response import Response - from djangorestframework.status import * + from djangorestframework.status import status - class CommentRoot(views.APIView): + class CommentRoot(APIView): """ List all comments, or create a new comment. """ @@ -28,20 +28,21 @@ We'll start by rewriting the root view as a class based view. All this involves comment = serializer.object comment.save() return Response(serializer.serialized, status=HTTP_201_CREATED) - else: - return Response(serializer.serialized_errors, status=HTTP_400_BAD_REQUEST) + return Response(serializer.serialized_errors, 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(views.APIView): + class CommentInstance(APIView): """ Retrieve, update or delete a comment instance. """ def get_object(self, pk): try: - return Poll.objects.get(pk=pk) - except Poll.DoesNotExist: + return Comment.objects.get(pk=pk) + except Comment.DoesNotExist: raise Http404 def get(self, request, pk, format=None): @@ -56,28 +57,16 @@ So far, so good. It looks pretty similar to the previous case, but we've got be comment = serializer.deserialized comment.save() return Response(serializer.data) - else: - return Response(serializer.errors, 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=HTTP_204_NO_CONTENT) - -That's looking good. Again, it's still pretty similar to the function based view right now. - -Since we're now working with class based views, rather than function based views, we'll also need to update our urlconf slightly. + return Response(status=status.HTTP_204_NO_CONTENT) - from blogpost import views - from djangorestframework.urlpatterns import format_suffix_patterns - - urlpatterns = patterns('', - url(r'^$', views.CommentRoot.as_view()), - url(r'^(?P[0-9]+)$', views.CommentInstance.as_view()) - ) - - urlpatterns = format_suffix_patterns(urlpatterns) + comment_instance = CommentInstance.as_view() +That's looking good. Again, it's still pretty similar to the function based view right now. Okay, we're done. If you run the development server everything should be working just as before. ## Using mixins -- cgit v1.2.3 From 6e21915934686cc7d46c8144403c933fa6fd2375 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 3 Sep 2012 17:49:22 +0100 Subject: First pass at mixins & generic views --- docs/tutorial/3-class-based-views.md | 43 ++++++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 16 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 616a6058..21255a68 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -57,7 +57,7 @@ So far, so good. It looks pretty similar to the previous case, but we've got be comment = serializer.deserialized comment.save() return Response(serializer.data) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + return Response(serializer.error_data, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): comment = self.get_object(pk) @@ -79,27 +79,38 @@ We can compose those mixin classes, to recreate our existing API behaviour with from blog.models import Comment from blog.serializers import CommentSerializer - from djangorestframework import mixins, views + from djangorestframework import mixins + from djangorestframework import views + - class CommentRoot(mixins.ListModelQuerysetMixin, - mixins.CreateModelInstanceMixin, - views.BaseRootAPIView): + class CommentRoot(mixins.ListModelMixin, + mixins.CreateModelMixin, + views.MultipleObjectBaseView): model = Comment serializer_class = CommentSerializer - get = list - post = create + def get(self, request, *args, **kwargs): + return self.list(request, *args, **kwargs) + + def post(self, request, *args, **kwargs): + return self.create(request, *args, **kwargs) - class CommentInstance(mixins.RetrieveModelInstanceMixin, - mixins.UpdateModelInstanceMixin, - mixins.DestroyModelInstanceMixin, - views.BaseInstanceAPIView): + + class CommentInstance(mixins.RetrieveModelMixin, + mixins.UpdateModelMixin, + mixins.DestroyModelMixin, + views.SingleObjectBaseView): model = Comment serializer_class = CommentSerializer - get = retrieve - put = update - delete = destroy + def get(self, request, *args, **kwargs): + return self.retrieve(request, *args, **kwargs) + + def put(self, request, *args, **kwargs): + return self.update(request, *args, **kwargs) + + def delete(self, request, *args, **kwargs): + return self.destroy(request, *args, **kwargs) ## Reusing generic class based views @@ -109,11 +120,11 @@ That's a lot less code than before, but we can go one step further still. REST from blog.serializers import CommentSerializer from djangorestframework import views - class CommentRoot(views.RootAPIView): + class CommentRoot(views.RootModelView): model = Comment serializer_class = CommentSerializer - class CommentInstance(views.InstanceAPIView): + class CommentInstance(views.InstanceModelView): model = Comment serializer_class = CommentSerializer -- cgit v1.2.3 From da5a6243f30b274441bed9a6736566ca68c40e67 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 7 Sep 2012 09:37:06 +0100 Subject: Filling out docs a bit more --- docs/tutorial/2-requests-and-responses.md | 2 +- docs/tutorial/3-class-based-views.md | 42 ++++++++++++++++++++----------- 2 files changed, 29 insertions(+), 15 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 4ff303ae..9d23c9b2 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -1,4 +1,4 @@ -# Tutorial 2: Request and Response objects +# Tutorial 2: Requests and Responses From this point we're going to really start covering the core of REST framework. Let's introduce a couple of essential building blocks. diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 21255a68..b3000ad9 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -1,4 +1,4 @@ -# Tutorial 3: Using Class Based Views +# 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]. @@ -73,19 +73,18 @@ Okay, we're done. If you run the development server everything should be workin One of the big wins of using class based views is that it allows us to easily compose reusable bits of behaviour. -The create/retrieve/update/delete operations that we've been using so far is going to be pretty simliar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes. +The create/retrieve/update/delete operations that we've been using so far are going to be pretty simliar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes. -We can compose those mixin classes, to recreate our existing API behaviour with less code. +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 views - + from djangorestframework import generics class CommentRoot(mixins.ListModelMixin, mixins.CreateModelMixin, - views.MultipleObjectBaseView): + generics.MultipleObjectBaseView): model = Comment serializer_class = CommentSerializer @@ -95,11 +94,16 @@ We can compose those mixin classes, to recreate our existing API behaviour with 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. class CommentInstance(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, - views.SingleObjectBaseView): + generics.SingleObjectBaseView): model = Comment serializer_class = CommentSerializer @@ -112,24 +116,34 @@ We can compose those mixin classes, to recreate our existing API behaviour with def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) -## Reusing generic class based views + 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 -That's a lot less code than before, but we can go one step further still. REST framework also provides a set of already mixed-in views. +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. from blog.models import Comment from blog.serializers import CommentSerializer - from djangorestframework import views + from djangorestframework import generics - class CommentRoot(views.RootModelView): + + class CommentRoot(generics.RootAPIView): model = Comment serializer_class = CommentSerializer - class CommentInstance(views.InstanceModelView): + comment_root = CommentRoot.as_view() + + + class CommentInstance(generics.InstanceAPIView): model = Comment serializer_class = CommentSerializer -Wow, that's pretty concise. We've got a huge amount for free, and our code looks like -good, clean, idomatic Django. + 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. -- cgit v1.2.3 From a01d6153547980f12034b6e872019e1ac94b5b78 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 7 Sep 2012 13:55:02 +0100 Subject: Add note re. browseable API and @api_view decorator --- docs/tutorial/2-requests-and-responses.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 9d23c9b2..89f92c4b 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -129,7 +129,9 @@ Go ahead and test the API from the command line, as we did in [tutorial part 1][ **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/][3]." + +**Note: Right now the Browseable API only works with the CBV's. Need to fix that.** **TODO: Describe browseable API awesomeness** -- cgit v1.2.3 From f95f96aba7c7f1ea26af09b9e768d5c8997bac98 Mon Sep 17 00:00:00 2001 From: Alec Perkins Date: Fri, 7 Sep 2012 14:31:24 -0400 Subject: [docs] Fix typo, add link to Tom's Twitter profile --- docs/tutorial/3-class-based-views.md | 2 +- docs/tutorial/6-resource-orientated-projects.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index b3000ad9..d5ba045e 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -7,7 +7,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. from blog.models import Comment - from blog.serializers import ComentSerializer + from blog.serializers import CommentSerializer from django.http import Http404 from djangorestframework.views import APIView from djangorestframework.response import Response diff --git a/docs/tutorial/6-resource-orientated-projects.md b/docs/tutorial/6-resource-orientated-projects.md index ce51cce5..4282c25d 100644 --- a/docs/tutorial/6-resource-orientated-projects.md +++ b/docs/tutorial/6-resource-orientated-projects.md @@ -44,6 +44,6 @@ 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 and say hi. +* Follow me [on Twitter](https://twitter.com/_tomchristie) and say hi. Now go build something great. \ No newline at end of file -- cgit v1.2.3 From 8ee763739d66bbaaa9c0f78fa05bbc17dce3de13 Mon Sep 17 00:00:00 2001 From: Marko Tibold Date: Fri, 7 Sep 2012 22:53:02 +0200 Subject: Add some missing imports. Fix some typos. Fix some indentation errors. --- docs/tutorial/3-class-based-views.md | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index b3000ad9..24785179 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -7,30 +7,31 @@ 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. from blog.models import Comment - from blog.serializers import ComentSerializer + from blog.serializers import CommentSerializer from django.http import Http404 from djangorestframework.views import APIView from djangorestframework.response import Response - from djangorestframework.status import status + from djangorestframework import status + class CommentRoot(APIView): """ List all comments, or create a new comment. - """ + """ def get(self, request, format=None): comments = Comment.objects.all() - serializer = ComentSerializer(instance=comments) + serializer = CommentSerializer(instance=comments) return Response(serializer.data) - def post(self, request, format=None) - serializer = ComentSerializer(request.DATA) + def post(self, request, format=None): + serializer = CommentSerializer(request.DATA) if serializer.is_valid(): comment = serializer.object comment.save() - return Response(serializer.serialized, status=HTTP_201_CREATED) - return Response(serializer.serialized_errors, status=HTTP_400_BAD_REQUEST) + 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() + 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. @@ -38,18 +39,18 @@ So far, so good. It looks pretty similar to the previous case, but we've got be """ Retrieve, update or delete a comment instance. """ - + def get_object(self, pk): try: return Comment.objects.get(pk=pk) except Comment.DoesNotExist: raise Http404 - + def get(self, request, pk, format=None): comment = self.get_object(pk) serializer = CommentSerializer(instance=comment) return Response(serializer.data) - + def put(self, request, pk, format=None): comment = self.get_object(pk) serializer = CommentSerializer(request.DATA, instance=comment) @@ -64,7 +65,7 @@ So far, so good. It looks pretty similar to the previous case, but we've got be comment.delete() return Response(status=status.HTTP_204_NO_CONTENT) - comment_instance = CommentInstance.as_view() + comment_instance = CommentInstance.as_view() That's looking good. Again, it's still pretty similar to the function based view right now. Okay, we're done. If you run the development server everything should be working just as before. -- cgit v1.2.3 From 5d9dfcd8ae10db37f0cca043d3b9977e27197487 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 8 Sep 2012 20:23:32 +0100 Subject: Code highlighting in docs --- docs/tutorial/1-serialization.md | 1 + 1 file changed, 1 insertion(+) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 3d6615d9..610d8ed1 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -8,6 +8,7 @@ This tutorial will walk you through the building blocks that make up REST framew Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is keep nicely isolated from any other projects we're working on. + :::bash mkdir ~/env virtualenv --no-site-packages ~/env/tutorial source ~/env/tutorial/bin/activate -- cgit v1.2.3 From 60e6bba12b6843b01194b6534fb56129ec0b2140 Mon Sep 17 00:00:00 2001 From: Alec Perkins Date: Sun, 9 Sep 2012 16:46:05 -0400 Subject: Browsable API doc topic --- docs/tutorial/2-requests-and-responses.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 89f92c4b..2c11d5ef 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -133,7 +133,12 @@ Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/][3 **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][4] topic for more information about the browsable API feature and how to customize it. + ## What's next? @@ -142,4 +147,5 @@ In [tutorial part 3][4], we'll start using class based views, and see how generi [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 +[4]: ../topics/browsable-api.md +[5]: 3-class-based-views.md \ No newline at end of file -- cgit v1.2.3 From eb761be9d058dbfb9214f200b941496524dc0ded Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 14 Sep 2012 12:43:14 +0100 Subject: Flesh out resources/routers part of tutorial --- docs/tutorial/6-resource-orientated-projects.md | 37 +++++++++++++++++++++---- 1 file changed, 32 insertions(+), 5 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/6-resource-orientated-projects.md b/docs/tutorial/6-resource-orientated-projects.md index 4282c25d..0d0cfac5 100644 --- a/docs/tutorial/6-resource-orientated-projects.md +++ b/docs/tutorial/6-resource-orientated-projects.md @@ -1,3 +1,7 @@ +In REST framework Resources classes are just View classes that don't have any handler methods bound to them. This allows us to seperate out the behaviour of the classes from how that behaviour should be bound to a set of URLs. + +For instance, given our serializers + serializers.py class BlogPostSerializer(URLModelSerializer): @@ -8,21 +12,44 @@ serializers.py class Meta: model = Comment +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,) + +The handler methods only get bound to the actions when we define the URLConf. Here's our urls.py: + + 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[0-9]+)$', comment_instance) + ... # And for blog post + ) + +## Using Routers -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. +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 -- cgit v1.2.3 From 308677037f1b1f2edbd2527beac8505033c98bdc Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 17 Sep 2012 20:19:45 +0100 Subject: Tweak docs, fix .error_data -> .errors --- docs/tutorial/1-serialization.md | 4 ++-- docs/tutorial/2-requests-and-responses.md | 4 ++-- docs/tutorial/3-class-based-views.md | 29 +++++++++++++++-------------- 3 files changed, 19 insertions(+), 18 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 610d8ed1..34990084 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -194,7 +194,7 @@ 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) We'll also need a view which corrosponds to an individual comment, and can be used to retrieve, update or delete the comment. @@ -219,7 +219,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() diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 2c11d5ef..ffc5f269 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -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() diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 24785179..3c8f1207 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -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): @@ -58,16 +56,28 @@ So far, so good. It looks pretty similar to the previous case, but we've got be comment = serializer.deserialized 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 djangorestframework.urlpatterns import format_suffix_patterns + from blogpost import views + + urlpatterns = patterns('', + url(r'^$', views.CommentRoot.as_view()), + url(r'^(?P[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 @@ -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 @@ -134,16 +140,11 @@ Using the mixin classes we've rewritten the views to use slightly less code than 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. -- cgit v1.2.3 From 575630d7c34b8ee23dad379c4bbd01eba477e4a2 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 19 Sep 2012 13:02:10 +0100 Subject: Use named links in tutorial docs --- docs/tutorial/2-requests-and-responses.md | 16 +++++++-------- docs/tutorial/3-class-based-views.md | 8 ++++---- .../4-authentication-permissions-and-throttling.md | 6 ++++-- .../5-relationships-and-hyperlinked-apis.md | 6 ++++-- docs/tutorial/6-resource-orientated-projects.md | 24 +++++++++++----------- 5 files changed, 32 insertions(+), 28 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index ffc5f269..906f11d0 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -125,11 +125,11 @@ 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.** @@ -137,15 +137,15 @@ Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/][3 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][4] topic for more information about the browsable API feature and how to customize it. +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]: ../topics/browsable-api.md -[5]: 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 \ No newline at end of file diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 3c8f1207..79866f0d 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 @@ -147,7 +147,7 @@ Using the mixin classes we've rewritten the views to use slightly less code than 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 0d0cfac5..7da409fb 100644 --- a/docs/tutorial/6-resource-orientated-projects.md +++ b/docs/tutorial/6-resource-orientated-projects.md @@ -1,18 +1,15 @@ -In REST framework Resources classes are just View classes that don't have any handler methods bound to them. This allows us to seperate out the behaviour of the classes from how that behaviour should be bound to a set of URLs. +# Tutorial 6 - Resources -For instance, given our serializers +Resource classes are just View classes that don't have any handler methods bound to them. The actions on a resource are defined, -serializers.py +This allows us to: - class BlogPostSerializer(URLModelSerializer): - class Meta: - model = BlogPost +* 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. - class CommentSerializer(URLModelSerializer): - class Meta: - model = Comment +## Refactoring to use Resources, not Views -We can re-write our 4 sets of views into something more compact... +For instance, we can re-write our 4 sets of views into something more compact... resources.py @@ -28,6 +25,7 @@ resources.py 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: comment_root = CommentResource.as_view(actions={ @@ -71,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 something great. \ No newline at end of file +**Now go build some awesome things.** + +[twitter]: https://twitter.com/_tomchristie \ No newline at end of file -- cgit v1.2.3 From 4b691c402707775c3048a90531024f3bc5be6f91 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 20 Sep 2012 13:06:27 +0100 Subject: Change package name: djangorestframework -> rest_framework --- docs/tutorial/1-serialization.md | 16 ++++++++-------- docs/tutorial/2-requests-and-responses.md | 10 +++++----- docs/tutorial/3-class-based-views.md | 14 +++++++------- docs/tutorial/6-resource-orientated-projects.md | 4 ++-- 4 files changed, 22 insertions(+), 22 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 34990084..e3656bd0 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' ) @@ -81,7 +81,7 @@ 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): @@ -114,8 +114,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') @@ -159,8 +159,8 @@ 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 rest_framework.renderers import JSONRenderer + from rest_framework.parsers import JSONParser from django.http import HttpResponse @@ -251,4 +251,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 906f11d0..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): @@ -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'), @@ -148,4 +148,4 @@ In [tutorial part 3][tut-3], we'll start using class based views, and see how ge [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 \ No newline at end of file +[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 79866f0d..8db29308 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -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): @@ -68,7 +68,7 @@ That's looking good. Again, it's still pretty similar to the function based vie We'll also need to refactor our URLconf slightly now we're using class based views. from django.conf.urls import patterns, url - from djangorestframework.urlpatterns import format_suffix_patterns + from rest_framework.urlpatterns import format_suffix_patterns from blogpost import views urlpatterns = patterns('', @@ -90,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, @@ -133,7 +133,7 @@ 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): diff --git a/docs/tutorial/6-resource-orientated-projects.md b/docs/tutorial/6-resource-orientated-projects.md index 7da409fb..3c3e7fed 100644 --- a/docs/tutorial/6-resource-orientated-projects.md +++ b/docs/tutorial/6-resource-orientated-projects.md @@ -50,7 +50,7 @@ The handler methods only get bound to the actions when we define the URLConf. He 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) @@ -73,4 +73,4 @@ We've reached the end of our tutorial. If you want to get more involved in the **Now go build some awesome things.** -[twitter]: https://twitter.com/_tomchristie \ No newline at end of file +[twitter]: https://twitter.com/_tomchristie -- cgit v1.2.3 From 921c5840aa64c184bcfa6cc2344d0fdca406548b Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 25 Sep 2012 12:21:35 +0100 Subject: Fix incorrect bit of tutorial --- docs/tutorial/3-class-based-views.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 8db29308..25d5773f 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -53,7 +53,7 @@ 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.errors, status=status.HTTP_400_BAD_REQUEST) -- cgit v1.2.3 From 4fb57d28e60c02593f14ba7cdebed4e478371512 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 25 Sep 2012 12:27:46 +0100 Subject: Add csrf note --- docs/tutorial/1-serialization.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index e3656bd0..04942834 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -159,9 +159,10 @@ Edit the `blog/views.py` file, and add the following. from blog.models import Comment from blog.serializers import CommentSerializer + 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 - from django.http import HttpResponse class JSONResponse(HttpResponse): @@ -177,6 +178,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. @@ -196,8 +198,11 @@ The root of our API is going to be a view that supports listing all the existing else: 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. -- cgit v1.2.3 From 6fc5581a8fba45fe22920e65b2d0790d483a8378 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 25 Sep 2012 13:40:16 +0100 Subject: Add readonly 'id' field --- docs/tutorial/1-serialization.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 04942834..cd4b7558 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -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) @@ -85,6 +85,7 @@ We're going to create a simple Web API that we can use to edit these comment obj class CommentSerializer(serializers.Serializer): + id = serializers.IntegerField(readonly=True) email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() @@ -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=)} + # {'id': 1, 'email': u'leila@example.com', 'content': u'nothing to say', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774, tzinfo=)} 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... -- cgit v1.2.3 From 934492ebd02dfc580fd0dbd9d8a57ca123adb46d Mon Sep 17 00:00:00 2001 From: Matt Bosworth Date: Tue, 2 Oct 2012 22:41:03 -0700 Subject: Fixed references to serializer.serialized and serializer.serialized_errors in part 3 of the tutorial. Altered part 1 to use blogs/urls.py since it was specified at the beginning. Also caught some spelling errors while I was at it. --- docs/tutorial/1-serialization.md | 6 +++--- docs/tutorial/2-requests-and-responses.md | 4 ++-- docs/tutorial/3-class-based-views.md | 8 ++++---- docs/tutorial/6-resource-orientated-projects.md | 6 +++--- 4 files changed, 12 insertions(+), 12 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index cd4b7558..5d830315 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -78,7 +78,7 @@ Don't forget to sync the database for the first time. ## Creating a Serializer class -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. +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 rest_framework import serializers @@ -201,7 +201,7 @@ The root of our API is going to be a view that supports listing all the existing 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. +We'll also need a view which corresponds to an individual comment, and can be used to retrieve, update or delete the comment. @csrf_exempt def comment_instance(request, pk): @@ -231,7 +231,7 @@ We'll also need a view which corrosponds to an individual comment, and can be us comment.delete() return HttpResponse(status=204) -Finally we need to wire these views up, in the `tutorial/urls.py` file. +Finally we need to wire these views up. Create the `blog/urls.py` file: from django.conf.urls import patterns, url diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index d889b1e0..13feb254 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -27,7 +27,7 @@ REST framework provides two wrappers you can use to write API views. 1. The `@api_view` decorator for working with function based views. 2. The `APIView` class for working with class based views. -These wrappers provide a few bits of functionality such as making sure you recieve `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed. +These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed. 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. @@ -121,7 +121,7 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter 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 refering 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. ## How's it looking? diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 25d5773f..b2b6443c 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -28,10 +28,10 @@ We'll start by rewriting the root view as a class based view. All this involves if serializer.is_valid(): comment = serializer.object comment.save() - return Response(serializer.serialized, status=status.HTTP_201_CREATED) - return Response(serializer.serialized_errors, status=status.HTTP_400_BAD_REQUEST) + return Response(serializer.data, status=status.HTTP_201_CREATED) + 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 seperation between the different HTTP methods. We'll also need to update the instance view. +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. class CommentInstance(APIView): """ @@ -145,7 +145,7 @@ Using the mixin classes we've rewritten the views to use slightly less code than model = Comment serializer_class = CommentSerializer -Wow, that's pretty concise. We've got a huge amount for free, and our code looks like good, clean, idomatic Django. +Wow, that's pretty concise. We've got a huge amount for free, and our code looks like good, clean, idiomatic Django. 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. diff --git a/docs/tutorial/6-resource-orientated-projects.md b/docs/tutorial/6-resource-orientated-projects.md index 3c3e7fed..e7190a77 100644 --- a/docs/tutorial/6-resource-orientated-projects.md +++ b/docs/tutorial/6-resource-orientated-projects.md @@ -4,8 +4,8 @@ Resource classes are just View classes that don't have any handler methods bound 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. +* Encapsulate common behaviour across a class of views, in a single Resource class. +* Separate 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 @@ -59,7 +59,7 @@ Right now that hasn't really saved us a lot of code. However, now that we're us ## Trade-offs between views vs resources. -Writing resource-orientated code can be a good thing. It helps ensure that URL conventions will be consistent across your APIs, and minimises the amount of code you need to write. +Writing resource-oriented code can be a good thing. It helps ensure that URL conventions will be consistent across your APIs, and minimises the amount of code you need to write. The trade-off is that the behaviour is less explict. It can be more difficult to determine what code path is being followed, or where to override some behaviour. -- cgit v1.2.3 From c30e0795bebd9980a66ae7db1a0d8c43f77d4c11 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 3 Oct 2012 09:26:15 +0100 Subject: Rename generic views --- docs/tutorial/3-class-based-views.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 25d5773f..663138bd 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -136,12 +136,12 @@ Using the mixin classes we've rewritten the views to use slightly less code than from rest_framework import generics - class CommentRoot(generics.RootAPIView): + class CommentRoot(generics.ListCreateAPIView): model = Comment serializer_class = CommentSerializer - class CommentInstance(generics.InstanceAPIView): + class CommentInstance(generics.RetrieveUpdateDestroyAPIView): model = Comment serializer_class = CommentSerializer -- cgit v1.2.3 From 84958d131a29d80acea94dec5260b484556e73d0 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 5 Oct 2012 15:22:30 +0100 Subject: Doc style tweaks --- docs/tutorial/1-serialization.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 5d830315..6744eafe 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -25,6 +25,7 @@ Now that we're inside a virtualenv environment, we can install our package requi Okay, we're ready to get coding. To get started, let's create a new project to work with. + cd ~ django-admin.py startproject tutorial cd tutorial @@ -78,7 +79,7 @@ Don't forget to sync the database for the first time. ## Creating a Serializer class -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. +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 `blog` directory named `serializers.py` and add the following. from blog import models from rest_framework import serializers -- cgit v1.2.3 From b581ffe323d88b6740abfed0fd552cc436fd2dcc Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 8 Oct 2012 15:46:52 +0100 Subject: Docs tweaks --- docs/tutorial/1-serialization.md | 2 +- docs/tutorial/2-requests-and-responses.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 6744eafe..e21433ba 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -89,7 +89,7 @@ We're going to create a simple Web API that we can use to edit these comment obj id = serializers.IntegerField(readonly=True) email = serializers.EmailField() content = serializers.CharField(max_length=200) - created = serializers.DateTimeField() + created = serializers.DateTimeField(readonly=True) def restore_object(self, attrs, instance=None): """ diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 13feb254..7c8fc044 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -114,7 +114,7 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter from django.conf.urls import patterns, url from rest_framework.urlpatterns import format_suffix_patterns - urlpatterns = patterns('blogpost.views', + urlpatterns = patterns('blog.views', url(r'^$', 'comment_root'), url(r'^(?P[0-9]+)$', 'comment_instance') ) -- cgit v1.2.3 From 115e61be0900b3d5dd93ff84f20629311aceff9f Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 9 Oct 2012 12:01:17 +0100 Subject: Added quickstart guide --- docs/tutorial/quickstart.md | 133 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 docs/tutorial/quickstart.md (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md new file mode 100644 index 00000000..1e9ed725 --- /dev/null +++ b/docs/tutorial/quickstart.md @@ -0,0 +1,133 @@ +# Quickstart + +We're going to create a simple API to allow admin users to view and edit the users and groups in the system. + +Create a new Django project, and start a new app called `quickstart`. Once you've set up a database and got everything synced and ready to go open up the app's directory and we'll get coding... + +## Serializers + +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 + from rest_framework import serializers + + + class UserSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = User + fields = ('url', 'username', 'email', 'groups') + + + class GroupSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = Group + fields = ('url', 'name', 'permissions') + +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. + +## Views + +Right, we'd better right 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 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): + """ + API endpoint that represents a single user. + """ + model = User + serializer_class = UserSerializer + + + class GroupList(generics.ListCreateAPIView): + """ + API endpoint that represents a list of groups. + """ + model = Group + serializer_class = GroupSerializer + + + class GroupDetail(generics.RetrieveUpdateDestroyAPIView): + """ + API endpoint that represents a single group. + """ + model = Group + 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. + +## URLs + +Okay, let's wire this baby up. 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\d+)/$', UserDetail.as_view(), name='user-detail'), + url(r'^groups/$', GroupList.as_view(), name='group-list'), + url(r'^groups/(?P\d+)/$', GroupDetail.as_view(), name='group-detail'), + ) + + + # Format suffixes + urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'api']) + + + # Default login/logout views + urlpatterns += patterns('', + 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. + +Secondly, we're modifying the urlpatterns using `format_suffix_patterns`, to append optional `.json` style suffixes to our URLs. + +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. + +## Settings + +We'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. + + INSTALLED_APPS = ( + ... + 'rest_framework', + ) + + REST_FRAMEWORK = { + 'PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser'), + 'PAGINATE_BY': 10 + } + +Okay, that's us done. -- cgit v1.2.3 From e9475d036ff2fa0244ca0f947192ffa842391784 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 9 Oct 2012 12:03:29 +0100 Subject: Tweak settings in quickstart guide --- docs/tutorial/quickstart.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 1e9ed725..62338160 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -126,7 +126,7 @@ We'd also like to set a few global settings. We'd like to turn on pagination, a ) REST_FRAMEWORK = { - 'PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser'), + 'DEFAULT_PERMISSIONS': ('rest_framework.permissions.IsAdminUser',), 'PAGINATE_BY': 10 } -- cgit v1.2.3 From 94401b43d2a1be81304ddcd91e3a97e7d2a42c4c Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 9 Oct 2012 13:50:26 +0100 Subject: Flesh out quickstart guide and make some style tweaks --- docs/tutorial/quickstart.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 62338160..cf5933ad 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -131,3 +131,42 @@ We'd also like to set a few global settings. We'd like to turn on pagination, a } Okay, that's us done. + +--- + +## Testing our API + +We can now access our API, both from the command-line, using tools like `curl`... + + bash: curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/ + { + "count": 2, + "next": null, + "previous": null, + "results": [ + { + "email": "admin@example.com", + "groups": [], + "url": "http://127.0.0.1:8000/users/1/", + "username": "admin" + }, + { + "email": "tom@example.com", + "groups": [], + "url": "http://127.0.0.1:8000/users/2/", + "username": "tom" + } + ] + } + +Or directly through the browser... + +![Quick start image][image] + +Great, that was easy! + +If you want to get a more in depth understanding of how REST framework fits together head on over to [the tutorial][tutorial], or start browsing the [API guide][guide]. + +[image]: ../images/quickstart.png +[tutorial]: 1-serialization.md +[guide]: ../#api-guide \ No newline at end of file -- cgit v1.2.3 From ce21fa1dc6dd8c941b71d9219360b3e9083051d4 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 9 Oct 2012 14:12:38 +0100 Subject: Tweak static files with docs --- docs/tutorial/quickstart.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index cf5933ad..85411378 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -167,6 +167,6 @@ Great, that was easy! If you want to get a more in depth understanding of how REST framework fits together head on over to [the tutorial][tutorial], or start browsing the [API guide][guide]. -[image]: ../images/quickstart.png +[image]: ../img/quickstart.png [tutorial]: 1-serialization.md [guide]: ../#api-guide \ No newline at end of file -- cgit v1.2.3 From 44281c39961a7fd2131a516f905cd28c0c95efcc Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 10 Oct 2012 09:36:18 +0100 Subject: Remove 'tut 6 - resources' from the docs, since it doesn't exist yet --- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index a76f81e8..8600d5ed 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -6,6 +6,6 @@ * Demonstrate nested relationships * Demonstrate and describe hyperlinked relationships -Onwards to [part 6][tut-6]. + -- cgit v1.2.3 From 7367bd53a908474f14f0f44f3744f2fcb1f4111c Mon Sep 17 00:00:00 2001 From: Jamie Matthews Date: Fri, 12 Oct 2012 10:02:21 +0200 Subject: Fix tiny typo --- docs/tutorial/quickstart.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 85411378..851db3c7 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -27,7 +27,7 @@ Notice that we're using hyperlinked relations in this case, with `HyperlinkedMod ## Views -Right, we'd better right some views then. Open `quickstart/views.py` and get typing. +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 -- cgit v1.2.3 From 99d48f90030d174ef80498b48f56af6489865f0d Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Oct 2012 22:07:56 +0100 Subject: Drop .parse_string_or_stream() - keep API minimal. --- docs/tutorial/1-serialization.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index e21433ba..5b58f293 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -134,12 +134,15 @@ We've now got a few comment instances to play with. Let's take a look at serial 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 + content = JSONRenderer().render(serializer.data) + content # '{"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... + import StringIO + + stream = StringIO.StringIO(content) data = JSONParser().parse(stream) ...then we restore those native datatypes into to a fully populated object instance. -- cgit v1.2.3 From fed235dd0135c3eb98bb218a51f01ace5ddd3782 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Oct 2012 23:09:11 +0100 Subject: Make settings consistent with corrosponding view attributes --- docs/tutorial/quickstart.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 851db3c7..6bde725b 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -126,7 +126,7 @@ We'd also like to set a few global settings. We'd like to turn on pagination, a ) REST_FRAMEWORK = { - 'DEFAULT_PERMISSIONS': ('rest_framework.permissions.IsAdminUser',), + 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',), 'PAGINATE_BY': 10 } @@ -169,4 +169,4 @@ If you want to get a more in depth understanding of how REST framework fits toge [image]: ../img/quickstart.png [tutorial]: 1-serialization.md -[guide]: ../#api-guide \ No newline at end of file +[guide]: ../#api-guide -- cgit v1.2.3 From 71a93930fd4df7a1f5f92c67633b813a26a5e938 Mon Sep 17 00:00:00 2001 From: Marko Tibold Date: Sun, 21 Oct 2012 16:34:07 +0200 Subject: Fixing spelling errors. --- docs/tutorial/2-requests-and-responses.md | 2 +- docs/tutorial/3-class-based-views.md | 2 +- docs/tutorial/6-resource-orientated-projects.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 7c8fc044..fc37322a 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -5,7 +5,7 @@ Let's introduce a couple of essential building blocks. ## Request objects -REST framework intoduces 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. request.POST # Only handles form data. Only works for 'POST' method. request.DATA # Handles arbitrary data. Works any HTTP request with content. diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 2f273364..0ee81ea3 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -107,7 +107,7 @@ Let's take a look at how we can compose our views by using the mixin classes. 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. +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 CommentInstance(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, diff --git a/docs/tutorial/6-resource-orientated-projects.md b/docs/tutorial/6-resource-orientated-projects.md index e7190a77..9ee599ae 100644 --- a/docs/tutorial/6-resource-orientated-projects.md +++ b/docs/tutorial/6-resource-orientated-projects.md @@ -5,7 +5,7 @@ Resource classes are just View classes that don't have any handler methods bound This allows us to: * Encapsulate common behaviour across a class of views, in a single Resource class. -* Separate out the actions of a Resource from the specfics of how those actions should be bound to a particular set of URLs. +* Separate out the actions of a Resource from the specifics of how those actions should be bound to a particular set of URLs. ## Refactoring to use Resources, not Views -- cgit v1.2.3 From 04ae32c9340b0782014bd61ef9ee3196af22ebce Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 25 Oct 2012 17:01:00 +0100 Subject: remove no-site-packages since that's now the default --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 5b58f293..d1ae0ba5 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -10,7 +10,7 @@ Before we do anything else we'll create a new virtual environment, using [virtua :::bash mkdir ~/env - virtualenv --no-site-packages ~/env/tutorial + virtualenv ~/env/tutorial source ~/env/tutorial/bin/activate Now that we're inside a virtualenv environment, we can install our package requirements. -- cgit v1.2.3 From 195006bbc36c21f0154fe1ab7c46f339b2efe559 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 26 Oct 2012 09:27:59 +0100 Subject: Drop resources from codebase since implementation is only partial (Created resoorces-routers branch for future reference) --- docs/tutorial/6-resource-orientated-projects.md | 76 ------------------------- 1 file changed, 76 deletions(-) delete mode 100644 docs/tutorial/6-resource-orientated-projects.md (limited to 'docs/tutorial') diff --git a/docs/tutorial/6-resource-orientated-projects.md b/docs/tutorial/6-resource-orientated-projects.md deleted file mode 100644 index 9ee599ae..00000000 --- a/docs/tutorial/6-resource-orientated-projects.md +++ /dev/null @@ -1,76 +0,0 @@ -# Tutorial 6 - Resources - -Resource classes are just View classes that don't have any handler methods bound to them. The actions on a resource are defined, - -This allows us to: - -* Encapsulate common behaviour across a class of views, in a single Resource class. -* Separate out the actions of a Resource from the specifics 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_classes = (permissions.IsAuthenticatedOrReadOnly,) - throttle_classes = (throttles.UserRateThrottle,) - - class CommentResource(ModelResource): - serializer_class = CommentSerializer - model = Comment - 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: - - 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[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 rest_framework.routers import DefaultRouter - - router = DefaultRouter() - router.register(resources.BlogPostResource) - router.register(resources.CommentResource) - urlpatterns = router.urlpatterns - -## Trade-offs between views vs resources. - -Writing resource-oriented code can be a good thing. It helps ensure that URL conventions will be consistent across your APIs, and minimises the amount of code you need to write. - -The trade-off is that the behaviour is less explict. It can be more difficult to determine what code path is being followed, or where to override some behaviour. - -## 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 by reviewing issues, and submitting issues or pull requests. -* Join the REST framework group, and help build the community. -* Follow me [on Twitter][twitter] and say hi. - -**Now go build some awesome things.** - -[twitter]: https://twitter.com/_tomchristie -- cgit v1.2.3 From fde79376f323708d9f7b80ee830fe63060fb335f Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 28 Oct 2012 19:25:51 +0000 Subject: Pastebin tutorial --- docs/tutorial/1-serialization.md | 180 ++++++++++++-------- docs/tutorial/2-requests-and-responses.md | 45 +++-- docs/tutorial/3-class-based-views.md | 88 +++++----- docs/tutorial/4-authentication-and-permissions.md | 183 +++++++++++++++++++++ .../4-authentication-permissions-and-throttling.md | 5 - .../5-relationships-and-hyperlinked-apis.md | 158 +++++++++++++++++- 6 files changed, 512 insertions(+), 147 deletions(-) create mode 100644 docs/tutorial/4-authentication-and-permissions.md delete mode 100644 docs/tutorial/4-authentication-permissions-and-throttling.md (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index d1ae0ba5..fc052202 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -2,7 +2,9 @@ ## Introduction -This tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together. +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. ## Setting up a new environment @@ -17,6 +19,7 @@ Now that we're inside a virtualenv environment, we can install our package requi pip install django pip install djangorestframework + pip install pygments # We'll be using this for the code highlighting **Note:** To exit the virtualenv environment at any time, just type `deactivate`. For more information see the [virtualenv documentation][virtualenv]. @@ -30,8 +33,9 @@ To get started, let's create a new project to work with. cd tutorial Once that's done we can create an app that we'll use to create a simple Web API. +We're going to create a project that - python manage.py startapp blog + python manage.py startapp snippets The simplest way to get up and running will probably be to use an `sqlite3` database for the tutorial. Edit the `tutorial/settings.py` file, and set the default database `"ENGINE"` to `"sqlite3"`, and `"NAME"` to `"tmp.db"`. @@ -46,32 +50,48 @@ 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 `rest_framework` app to `INSTALLED_APPS`. +We'll also need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. INSTALLED_APPS = ( ... 'rest_framework', - 'blog' + 'snippets' ) -We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our blog views. +We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet views. urlpatterns = patterns('', - url(r'^', include('blog.urls')), + url(r'^', include('snippets.urls')), ) 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 `Comment` model that is used to store comments against a blog post. Go ahead and edit the `blog` 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. from django.db import models - - class Comment(models.Model): - email = models.EmailField() - content = models.CharField(max_length=200) + 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())) + + + class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) + title = models.CharField(max_length=100, default='') + code = models.TextField() + linenos = models.BooleanField(default=False) + language = models.CharField(choices=LANGUAGE_CHOICES, + default='python', + max_length=100) + style = models.CharField(choices=STYLE_CHOICES, + default='friendly', + max_length=100) + + class Meta: + ordering = ('created',) Don't forget to sync the database for the first time. @@ -79,28 +99,40 @@ Don't forget to sync the database for the first time. ## Creating a Serializer class -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 `blog` directory named `serializers.py` and add the following. +The first thing we need to get started on our Web API is 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 similarly to Django's forms. Create a file in the `snippets` directory named `serializers.py` and add the following. - from blog import models + from django.forms import widgets 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(readonly=True) - + from snippets import models + + + class SnippetSerializer(serializers.Serializer): + pk = serializers.Field() # Note: `Field` is an untyped read-only field. + title = serializers.CharField(required=False, + max_length=100) + code = serializers.CharField(widget=widgets.Textarea, + max_length=100000) + linenos = serializers.BooleanField(required=False) + language = serializers.ChoiceField(choices=models.LANGUAGE_CHOICES, + default='python') + style = serializers.ChoiceField(choices=models.STYLE_CHOICES, + default='friendly') + def restore_object(self, attrs, instance=None): """ - Create or update a new comment instance. + Create or update a new snippet instance. """ if instance: - instance.email = attrs['email'] - instance.content = attrs['content'] - instance.created = attrs['created'] + # Update existing instance + instance.title = attrs['title'] + instance.code = attrs['code'] + instance.linenos = attrs['linenos'] + instance.language = attrs['language'] + instance.style = attrs['style'] return instance - return models.Comment(**attrs) + + # Create new instance + return models.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. @@ -112,31 +144,27 @@ Before we go any further we'll familiarise ourselves with using our new Serializ python manage.py shell -Okay, once we've got a few imports out of the way, we'd better create a few comments to work with. +Okay, once we've got a few imports out of the way, let's create a code snippet to work with. - from blog.models import Comment - from blog.serializers import CommentSerializer + from snippets.models import Snippet + from snippets.serializers import SnippetSerializer 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') - c3 = Comment(email='anna@example.com', content='LOLZ!') - c1.save() - c2.save() - c3.save() + snippet = Snippet(code='print "hello, world"\n') + snippet.save() -We've now got a few comment 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 = CommentSerializer(instance=c1) + serializer = SnippetSerializer(instance=snippet) serializer.data - # {'id': 1, 'email': u'leila@example.com', 'content': u'nothing to say', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774, tzinfo=)} + # {'pk': 1, '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 finalise the serialization process we render the data into `json`. content = JSONRenderer().render(serializer.data) content - # '{"id": 1, "email": "leila@example.com", "content": "nothing to say", "created": "2012-08-22T16:20:09.822"}' + # '{"pk": 1, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}' Deserialization is similar. First we parse a stream into python native datatypes... @@ -147,28 +175,45 @@ Deserialization is similar. First we parse a stream into python native datatype ...then we restore those native datatypes into to a fully populated object instance. - serializer = CommentSerializer(data) + serializer = SnippetSerializer(data) serializer.is_valid() # True serializer.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. -## Writing regular Django views using our Serializers +## 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. + +In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes. + +Let's look at refactoring our serializer using the `ModelSerializer` class. +Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer` class. + + class SnippetSerializer(serializers.ModelSerializer): + class Meta: + model = models.Snippet + fields = ('pk', '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. +For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views. + We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into `json`. -Edit the `blog/views.py` file, and add the following. +Edit the `snippet/views.py` file, and add the following. - from blog.models import Comment - from blog.serializers import CommentSerializer 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 - + from snippets.models import Snippet + from snippets.serializers import SnippetSerializer class JSONResponse(HttpResponse): """ @@ -181,67 +226,65 @@ Edit the `blog/views.py` file, and add the following. super(JSONResponse, self).__init__(content, **kwargs) -The root of our API is going to be a view that supports listing all the existing comments, or creating a new comment. +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 - def comment_root(request): + def snippet_list(request): """ - List all comments, or create a new comment. + List all code snippets, or create a new snippet. """ if request.method == 'GET': - comments = Comment.objects.all() - serializer = CommentSerializer(instance=comments) + snippets = Snippet.objects.all() + serializer = SnippetSerializer(instance=snippets) return JSONResponse(serializer.data) elif request.method == 'POST': data = JSONParser().parse(request) - serializer = CommentSerializer(data) + serializer = SnippetSerializer(data) if serializer.is_valid(): - comment = serializer.object - comment.save() + serializer.save() return JSONResponse(serializer.data, status=201) else: 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 corresponds to an individual comment, and can be used to retrieve, update or delete the comment. +We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet. @csrf_exempt - def comment_instance(request, pk): + def snippet_detail(request, pk): """ - Retrieve, update or delete a comment instance. + Retrieve, update or delete a code snippet. """ try: - comment = Comment.objects.get(pk=pk) - except Comment.DoesNotExist: + snippet = Snippet.objects.get(pk=pk) + except Snippet.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': - serializer = CommentSerializer(instance=comment) + serializer = SnippetSerializer(instance=snippet) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) - serializer = CommentSerializer(data, instance=comment) + serializer = SnippetSerializer(data, instance=snippet) if serializer.is_valid(): - comment = serializer.object - comment.save() + serializer.save() return JSONResponse(serializer.data) else: return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': - comment.delete() + snippet.delete() return HttpResponse(status=204) -Finally we need to wire these views up. Create the `blog/urls.py` file: +Finally we need to wire these views up. Create the `snippet/urls.py` file: from django.conf.urls import patterns, url - urlpatterns = patterns('blog.views', - url(r'^$', 'comment_root'), - url(r'^(?P[0-9]+)$', 'comment_instance') + urlpatterns = patterns('snippets.views', + url(r'^snippet/$', 'snippet_list'), + url(r'^snippet/(?P[0-9]+)/$', 'snippet_detail') ) It's worth noting that there's 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. @@ -260,5 +303,6 @@ 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]. +[quickstart]: quickstart.md [virtualenv]: http://www.virtualenv.org/en/latest/index.html [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 fc37322a..76803d24 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -38,27 +38,27 @@ Okay, let's go ahead and start using these new components to write a few views. We don't need our `JSONResponse` class anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly. - from blog.models import Comment - from blog.serializers import CommentSerializer from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response + from snippet.models import Snippet + from snippet.serializers import SnippetSerializer + @api_view(['GET', 'POST']) - def comment_root(request): + def snippet_list(request): """ - List all comments, or create a new comment. + List all snippets, or create a new snippet. """ if request.method == 'GET': - comments = Comment.objects.all() - serializer = CommentSerializer(instance=comments) + snippets = Snippet.objects.all() + serializer = SnippetSerializer(instance=snippets) return Response(serializer.data) elif request.method == 'POST': - serializer = CommentSerializer(request.DATA) + serializer = SnippetSerializer(request.DATA) if serializer.is_valid(): - comment = serializer.object - comment.save() + serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @@ -67,30 +67,29 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On 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. @api_view(['GET', 'PUT', 'DELETE']) - def comment_instance(request, pk): + def snippet_detail(request, pk): """ - Retrieve, update or delete a comment instance. + Retrieve, update or delete a snippet instance. """ try: - comment = Comment.objects.get(pk=pk) - except Comment.DoesNotExist: + snippet = Snippet.objects.get(pk=pk) + except Snippet.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': - serializer = CommentSerializer(instance=comment) + serializer = SnippetSerializer(instance=snippet) return Response(serializer.data) elif request.method == 'PUT': - serializer = CommentSerializer(request.DATA, instance=comment) + serializer = SnippetSerializer(request.DATA, instance=snippet) if serializer.is_valid(): - comment = serializer.object - comment.save() + serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': - comment.delete() + snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT) This should all feel very familiar - there's not a lot different to working with regular Django views. @@ -103,20 +102,20 @@ To take advantage of the fact that our responses are no longer hardwired to a si Start by adding a `format` keyword argument to both of the views, like so. - def comment_root(request, format=None): + def snippet_list(request, format=None): and - def comment_instance(request, pk, format=None): + def snippet_detail(request, pk, format=None): 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 rest_framework.urlpatterns import format_suffix_patterns - urlpatterns = patterns('blog.views', - url(r'^$', 'comment_root'), - url(r'^(?P[0-9]+)$', 'comment_instance') + urlpatterns = patterns('snippet.views', + url(r'^$', 'snippet_list'), + url(r'^(?P[0-9]+)$', 'snippet_detail') ) urlpatterns = format_suffix_patterns(urlpatterns) diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 0ee81ea3..3d58fe8e 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -6,61 +6,59 @@ 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. - from blog.models import Comment - from blog.serializers import CommentSerializer + from snippet.models import Snippet + from snippet.serializers import SnippetSerializer from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status - class CommentRoot(APIView): + class SnippetList(APIView): """ - List all comments, or create a new comment. + List all snippets, or create a new snippet. """ def get(self, request, format=None): - comments = Comment.objects.all() - serializer = CommentSerializer(instance=comments) + snippets = Snippet.objects.all() + serializer = SnippetSerializer(instance=snippets) return Response(serializer.data) def post(self, request, format=None): - serializer = CommentSerializer(request.DATA) + serializer = SnippetSerializer(request.DATA) if serializer.is_valid(): - comment = serializer.object - comment.save() + serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) 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. - class CommentInstance(APIView): + class SnippetDetail(APIView): """ - Retrieve, update or delete a comment instance. + Retrieve, update or delete a snippet instance. """ def get_object(self, pk): try: - return Comment.objects.get(pk=pk) - except Comment.DoesNotExist: + return Snippet.objects.get(pk=pk) + except Snippet.DoesNotExist: raise Http404 def get(self, request, pk, format=None): - comment = self.get_object(pk) - serializer = CommentSerializer(instance=comment) + snippet = self.get_object(pk) + serializer = SnippetSerializer(instance=snippet) return Response(serializer.data) def put(self, request, pk, format=None): - comment = self.get_object(pk) - serializer = CommentSerializer(request.DATA, instance=comment) + snippet = self.get_object(pk) + serializer = SnippetSerializer(request.DATA, instance=snippet) if serializer.is_valid(): - comment = serializer.object - comment.save() + serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): - comment = self.get_object(pk) - comment.delete() + snippet = self.get_object(pk) + snippet.delete() 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. @@ -69,11 +67,11 @@ We'll also need to refactor our URLconf slightly now we're using class based vie from django.conf.urls import patterns, url from rest_framework.urlpatterns import format_suffix_patterns - from blogpost import views + from snippetpost import views urlpatterns = patterns('', - url(r'^$', views.CommentRoot.as_view()), - url(r'^(?P[0-9]+)$', views.CommentInstance.as_view()) + url(r'^$', views.SnippetList.as_view()), + url(r'^(?P[0-9]+)$', views.SnippetDetail.as_view()) ) urlpatterns = format_suffix_patterns(urlpatterns) @@ -88,16 +86,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 our views by using the mixin classes. - from blog.models import Comment - from blog.serializers import CommentSerializer + from snippet.models import Snippet + from snippet.serializers import SnippetSerializer from rest_framework import mixins from rest_framework import generics - class CommentRoot(mixins.ListModelMixin, + class SnippetList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.MultipleObjectBaseView): - model = Comment - serializer_class = CommentSerializer + model = Snippet + serializer_class = SnippetSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) @@ -109,12 +107,12 @@ We'll take a moment to examine exactly what's happening here - We're building ou 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 CommentInstance(mixins.RetrieveModelMixin, - mixins.UpdateModelMixin, - mixins.DestroyModelMixin, - generics.SingleObjectBaseView): - model = Comment - serializer_class = CommentSerializer + class SnippetDetail(mixins.RetrieveModelMixin, + mixins.UpdateModelMixin, + mixins.DestroyModelMixin, + generics.SingleObjectBaseView): + model = Snippet + serializer_class = SnippetSerializer def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) @@ -131,23 +129,23 @@ Pretty similar. This time we're using the `SingleObjectBaseView` class to provi 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. - from blog.models import Comment - from blog.serializers import CommentSerializer + from snippet.models import Snippet + from snippet.serializers import SnippetSerializer from rest_framework import generics - class CommentRoot(generics.ListCreateAPIView): - model = Comment - serializer_class = CommentSerializer + class SnippetList(generics.ListCreateAPIView): + model = Snippet + serializer_class = SnippetSerializer - class CommentInstance(generics.RetrieveUpdateDestroyAPIView): - model = Comment - serializer_class = CommentSerializer + class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): + model = Snippet + serializer_class = SnippetSerializer Wow, that's pretty concise. We've got a huge amount for free, and our code looks like good, clean, idiomatic Django. -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. +Next we'll move onto [part 4 of the tutorial][tut-4], where we'll take a look at how we can deal with authentication and permissions for our API. [dry]: http://en.wikipedia.org/wiki/Don't_repeat_yourself -[tut-4]: 4-authentication-permissions-and-throttling.md +[tut-4]: 4-authentication-and-permissions.md diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md new file mode 100644 index 00000000..79436ad4 --- /dev/null +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -0,0 +1,183 @@ +# Tutorial 4: Authentication & Permissions + +Currently our API doesn't have any restrictions on who can + + +## Adding information to our model + +We're going to make a couple of changes to our `Snippet` model class. +First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code. + +Add the following two fields to the model. + + owner = models.ForeignKey('auth.User', related_name='snippets') + 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 higlighting library. + +We'll ned some extra imports: + + from pygments.lexers import get_lexer_by_name + from pygments.formatters 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 + representation of the code snippet. + """ + lexer = get_lexer_by_name(self.language) + linenos = self.linenos and 'table' or False + options = self.title and {'title': self.title} or {} + formatter = HtmlFormatter(style=self.style, linenos=linenos, + full=True, **options) + self.highlighted = highlight(self.code, lexer, formatter) + super(Snippet, self).save(*args, **kwargs) + +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. + + rm tmp.db + python ./manage.py syncdb + +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. + + python ./manage.py createsuperuser + +## 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: + + class UserSerializer(serializers.ModelSerializer): + snippets = serializers.ManyPrimaryKeyRelatedField() + + class Meta: + model = User + fields = ('pk', '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've needed to add an explicit field for it. + +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 + serializer_class = UserSerializer + + + class UserInstance(generics.RetrieveAPIView): + model = User + 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[0-9]+)/$', views.UserInstance.as_view()) + +## Associating Snippets with Users + +Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request. + +The way we deal with that is by overriding a `.pre_save()` method on our snippet views, that allows us to handle any information that is implicit in the incoming request or requested URL. + +On **both** the `SnippetList` and `SnippetInstance` view classes, add the following method: + + def pre_save(self, obj): + obj.owner = self.request.user + +## Updating our serializer + +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: + + owner = serializers.Field(source='owner.username') + +**Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class. + +This field is doing something quite interesting. The `source` argument controls which attribtue is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as is used with Django's template language. + +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. + +## 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. + +REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is `IsAuthenticatedOrReadOnly`, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access. + +Add the following property to **both** the `SnippetList` and `SnippetInstance` view classes. + + permission_classes = (permissions.IsAuthenticatedOrReadOnly,) + +**TODO: Now that the permissions are restricted, demonstrate using HTTP basic authentication with curl requests** + +## Adding login to the Browseable API + +If you open a browser and navigate to the browseable API at the moment, you'll find 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. + +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. + + urlpatterns += patterns('', + url(r'^api-auth/', include('rest_framework.urls', + 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. + +Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earier, you'll be able to create code snippets again. + +Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet pks that are associated with each user, in each user's 'snippets' field. + +## 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. + +To do that we're going to need to create a custom permission. + +In the snippets app, create a new file, `permissions.py` + + from rest_framework import permissions + + + class IsOwnerOrReadOnly(permissions.BasePermission): + """ + 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 + if request.method in permissions.SAFE_METHODS: + return True + + # Write permissions are only allowed to the owner of the snippet + 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 `SnippetInstance` class: + + permission_classes = (permissions.IsAuthenticatedOrReadOnly, + IsOwnerOrReadOnly,) + +Make sure to also import the `IsOwnerOrReadOnly` class. + + 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. + +## 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. + +[tut-5]: 5-relationships-and-hyperlinked-apis.md \ No newline at end of file diff --git a/docs/tutorial/4-authentication-permissions-and-throttling.md b/docs/tutorial/4-authentication-permissions-and-throttling.md deleted file mode 100644 index c8d7cbd3..00000000 --- a/docs/tutorial/4-authentication-permissions-and-throttling.md +++ /dev/null @@ -1,5 +0,0 @@ -# Tutorial 4: Authentication & Permissions - -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 8600d5ed..84d02a53 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -1,11 +1,157 @@ # Tutorial 5 - Relationships & Hyperlinked APIs -**TODO** +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. -* Create BlogPost model -* Demonstrate nested relationships -* Demonstrate and describe hyperlinked relationships +## Creating an endpoint for the root of our API - + from rest_framework import renderers + from rest_framework.decorators import api_view + from rest_framework.response import Response + from rest_framework.reverse import reverse + + + @api_view(('GET',)) + def api_root(request, format=None): + return Response({ + 'users': reverse('user-list', request=request), + 'snippets': reverse('snippet-list', request=request) + }) + +Notice that we're using REST framework's `reverse` function in order to return fully-qualified URLs. + +## Creating an endpoint for the highlighted snippets + +The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints. + +Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two style of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint. + +The other thing we need to consider when creating the code highlight view is that there's no existing concreate generic view that we can use. We're not returning an object instance, but instead a property of an object instance. + +Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. + + class SnippetHighlight(generics.SingleObjectAPIView): + model = Snippet + renderer_classes = (renderers.StaticHTMLRenderer,) + + def get(self, request, *args, **kwargs): + snippet = self.get_object() + return Response(snippet.highlighted) + +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: + + url(r'^$', 'api_root'), + +And then add a url pattern for the snippet highlights: + + url(r'^snippets/(?P[0-9]+)/highlight/$', views.SnippetHighlight.as_view()), + +## Hyperlinking our API + +Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship: + +* Using primary keys. +* Using hyperlinking between entities. +* Using a unique identifying slug field on the related entity. +* Using the default string representation of the related entity. +* Nesting the related entity inside the parent representation. +* Some other custom representation. + +REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys. + +In this case we'd like to use a hyperlinked style between entities. In order to do so, we'll modify our serializers to extend `HyperlinkedModelSerializer` instead of the existing `ModelSerializer`. + +The `HyperlinkedModelSerializer` has the following differences from `ModelSerializer`: + +* 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`. + +We can easily re-write our existing serializers to use hyperlinking. + + class SnippetSerializer(serializers.HyperlinkedModelSerializer): + owner = serializers.Field(source='owner.username') + highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight') + + class Meta: + model = models.Snippet + fields = ('url', 'highlight', 'owner', + 'title', 'code', 'linenos', 'language', 'style') + + + class UserSerializer(serializers.HyperlinkedModelSerializer): + snippets = serializers.ManyHyperlinkedRelatedField(view_name='snippet-detail') + + class Meta: + model = User + fields = ('url', '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. + +## Making sure our URL patterns are named + +If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name. + +* The root of our API refers to `'user-list'` and `'snippet-list'`. +* Our snippet serializer includes a field that refers to `'snippet-highlight'`. +* Our user serializer includes a field that refers to `'snippet-detail'`. +* Our snippet and user serializers include `'url'` fields that by default will refer to `'{model_name}-detail'`, which in this case will be `'snippet-detail'` and `'user-detail'`. + +After adding all those names into our URLconf, our final `'urls.py'` file should look something like this: + + # API endpoints + urlpatterns = format_suffix_patterns(patterns('snippets.views', + url(r'^$', 'api_root'), + url(r'^snippets/$', + views.SnippetList.as_view(), + name='snippet-list'), + url(r'^snippets/(?P[0-9]+)/$', + views.SnippetInstance.as_view(), + name='snippet-detail'), + url(r'^snippets/(?P[0-9]+)/highlight/$' + views.SnippetHighlight.as_view(), + name='snippet-highlight'), + url(r'^users/$', + views.UserList.as_view(), + name='user-list'), + url(r'^users/(?P[0-9]+)/$', + views.UserInstance.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')) + ) + +## Reviewing our work + +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. + +You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the hightlighted 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. + +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 subitting 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 some awesome things.** + +[repo]: https://github.com/tomchristie/rest-framework-tutorial +[sandbox]: http://sultry-coast-6726.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 -- cgit v1.2.3 From db635fa6327d8d3ac3b06886c5f459b5c5a5cd04 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 28 Oct 2012 19:37:27 +0000 Subject: Minor fixes --- docs/tutorial/1-serialization.md | 6 +++--- docs/tutorial/2-requests-and-responses.md | 8 ++++---- docs/tutorial/4-authentication-and-permissions.md | 2 ++ 3 files changed, 9 insertions(+), 7 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index fc052202..c1ab49d1 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -278,13 +278,13 @@ We'll also need a view which corresponds to an individual snippet, and can be us snippet.delete() return HttpResponse(status=204) -Finally we need to wire these views up. Create the `snippet/urls.py` file: +Finally we need to wire these views up. Create the `snippets/urls.py` file: from django.conf.urls import patterns, url urlpatterns = patterns('snippets.views', - url(r'^snippet/$', 'snippet_list'), - url(r'^snippet/(?P[0-9]+)/$', 'snippet_detail') + url(r'^snippets/$', 'snippet_list'), + url(r'^snippets/(?P[0-9]+)/$', 'snippet_detail') ) It's worth noting that there's 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. diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 76803d24..938739fa 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -114,8 +114,8 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = patterns('snippet.views', - url(r'^$', 'snippet_list'), - url(r'^(?P[0-9]+)$', 'snippet_detail') + url(r'^snippets/$', 'snippet_list'), + url(r'^snippets/(?P[0-9]+)$', 'snippet_detail') ) urlpatterns = format_suffix_patterns(urlpatterns) @@ -128,7 +128,7 @@ Go ahead and test the API from the command line, as we did in [tutorial part 1][ **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/][devserver]." +Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver]." **Note: Right now the Browseable API only works with the CBV's. Need to fix that.** @@ -144,7 +144,7 @@ See the [browsable api][browseable-api] topic for more information about the bro 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 -[devserver]: http://127.0.0.1:8000/ +[devserver]: http://127.0.0.1:8000/snippets/ [browseable-api]: ../topics/browsable-api.md [tut-1]: 1-serialization.md [tut-3]: 3-class-based-views.md diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 79436ad4..336d5891 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -100,6 +100,8 @@ 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. -- cgit v1.2.3 From f2d63467764fd3784e9eb207bdb5b5387e7cd516 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 28 Oct 2012 20:50:37 +0000 Subject: Add initial explanatory paragraph --- docs/tutorial/4-authentication-and-permissions.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 336d5891..a0d7c5a6 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -1,7 +1,11 @@ # Tutorial 4: Authentication & Permissions -Currently our API doesn't have any restrictions on who can +Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that: +* Code snippets are always associated with a creator. +* Only authenticated users may create snippets. +* Only the creator of a snippet may update or delete it. +* Unauthenticated requests should have full read-only access. ## Adding information to our model -- cgit v1.2.3 From 411c95ea0e1051aca78e4fb02152a983bea830cc Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 28 Oct 2012 20:54:12 +0000 Subject: Tweaks --- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 84d02a53..38e32157 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -140,7 +140,7 @@ We've walked through each step of the design process, and seen how if we need to You can review the final [tutorial code][repo] on GitHub, or try out a live example in [the sandbox][sandbox]. -## Onwards and upwards. +## 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: -- cgit v1.2.3 From 76db7d4c590957c7e81ce521a1ab5bfb6760afaf Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Mon, 29 Oct 2012 08:54:14 +0100 Subject: correct code indent --- docs/tutorial/1-serialization.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index c1ab49d1..f6dcca13 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -87,8 +87,8 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, - default='friendly', - max_length=100) + default='friendly', + max_length=100) class Meta: ordering = ('created',) -- cgit v1.2.3 From c6240f4514ad34c53122eed77a349b71f28d8847 Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Mon, 29 Oct 2012 08:58:29 +0100 Subject: removed empty row --- docs/tutorial/1-serialization.md | 1 - 1 file changed, 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index f6dcca13..7330fdef 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -219,7 +219,6 @@ Edit the `snippet/views.py` file, and add the following. """ An HttpResponse that renders it's content into JSON. """ - def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' -- cgit v1.2.3 From 29bc52096a40c3f483e763cf562815ded3e56faa Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 30 Oct 2012 11:55:02 +0000 Subject: Docs tweaks for tutorial. --- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 38e32157..777aa5e1 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -74,7 +74,7 @@ We can easily re-write our existing serializers to use hyperlinking. class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.Field(source='owner.username') - highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight') + highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') class Meta: model = models.Snippet @@ -91,6 +91,8 @@ We can easily re-write our existing serializers to use hyperlinking. 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. +Because we've included format suffixed URLs such as `'.json'`, we also need to indicate on the `highlight` field that any format suffixed hyperlinks it returns should use the `'.html'` suffix. + ## Making sure our URL patterns are named If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name. @@ -128,6 +130,20 @@ After adding all those names into our URLconf, our final `'urls.py'` file should namespace='rest_framework')) ) +## Adding pagination + +The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages. + +We can change the default list style to use pagination, by modifying our `settings.py` file slightly. Add the following setting: + + REST_FRAMEWORK = { + '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. + +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 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. -- cgit v1.2.3 From 41ab18b13ec6d96906463a3b05680226c7245b6d Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 30 Oct 2012 12:23:17 +0000 Subject: Docs update --- docs/tutorial/1-serialization.md | 8 ++++++++ docs/tutorial/5-relationships-and-hyperlinked-apis.md | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 7330fdef..19fc28a5 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -6,6 +6,12 @@ This tutorial will cover creating a simple pastebin code highlighting Web API. A 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]. + +--- + ## Setting up a new environment Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is keep nicely isolated from any other projects we're working on. @@ -303,5 +309,7 @@ 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]. [quickstart]: quickstart.md +[repo]: https://github.com/tomchristie/rest-framework-tutorial +[sandbox]: http://restframework.herokuapp.com/ [virtualenv]: http://www.virtualenv.org/en/latest/index.html [tut-2]: 2-requests-and-responses.md diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 777aa5e1..1f663745 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -167,7 +167,7 @@ We've reached the end of our tutorial. If you want to get more involved in the **Now go build some awesome things.** [repo]: https://github.com/tomchristie/rest-framework-tutorial -[sandbox]: http://sultry-coast-6726.herokuapp.com/ +[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 -- cgit v1.2.3 From 9aa37260098b5ec2750090fb035945780b35ad1d Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Tue, 30 Oct 2012 13:50:07 +0100 Subject: fix ModelSerializer useage cause of: from snippets.models import Snippet --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 7330fdef..0b84a779 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -194,7 +194,7 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer` class SnippetSerializer(serializers.ModelSerializer): class Meta: - model = models.Snippet + model = Snippet fields = ('pk', 'title', 'code', 'linenos', 'language', 'style') -- cgit v1.2.3 From bcfb46eedc8fd7184e73a1fa6cecb1a359d1ef1f Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Tue, 30 Oct 2012 14:02:12 +0100 Subject: removed empty row --- docs/tutorial/3-class-based-views.md | 1 - 1 file changed, 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 3d58fe8e..f27b5af0 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -36,7 +36,6 @@ So far, so good. It looks pretty similar to the previous case, but we've got be """ Retrieve, update or delete a snippet instance. """ - def get_object(self, pk): try: return Snippet.objects.get(pk=pk) -- cgit v1.2.3 From abf7f1161933567e622c51af9a53e4b860c11693 Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Tue, 30 Oct 2012 14:11:36 +0100 Subject: fixed typo --- docs/tutorial/4-authentication-and-permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index a0d7c5a6..2dc62219 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -19,7 +19,7 @@ Add the following two fields to the model. We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the `pygments` code higlighting library. -We'll ned some extra imports: +We'll need some extra imports: from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter -- cgit v1.2.3 From a967187b4102af88dec4d8a2b9ffd97b6c65db0b Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Tue, 30 Oct 2012 14:36:37 +0100 Subject: fixed typo --- docs/tutorial/4-authentication-and-permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 2dc62219..5a30082c 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -100,7 +100,7 @@ Add the following field to the serializer definition: **Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class. -This field is doing something quite interesting. The `source` argument controls which attribtue is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as is used with Django's template language. +This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as is used with Django's template language. 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. -- cgit v1.2.3 From aa081678d5fecf6a17b411545571348e047c6846 Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Tue, 30 Oct 2012 14:38:23 +0100 Subject: added missing word --- docs/tutorial/4-authentication-and-permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 5a30082c..ca6ab80c 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -100,7 +100,7 @@ Add the following field to the serializer definition: **Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class. -This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as is used with Django's template language. +This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language. 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. -- cgit v1.2.3 From 3216ac022419710485695a9a21f083f08e012a7f Mon Sep 17 00:00:00 2001 From: Stephan Groß Date: Tue, 30 Oct 2012 14:53:38 +0100 Subject: added missing word + removed double whitespace --- docs/tutorial/4-authentication-and-permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index ca6ab80c..b0ed8f2a 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -120,7 +120,7 @@ Add the following property to **both** the `SnippetList` and `SnippetInstance` v ## Adding login to the Browseable API -If you open a browser and navigate to the browseable API at the moment, you'll find 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. -- cgit v1.2.3 From 4cdd0b845e10c433358f210c84a2b3fe28543c68 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 30 Oct 2012 13:59:31 +0000 Subject: Final docs tweaks for 2.0 --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 19fc28a5..77a7641f 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -4,7 +4,7 @@ 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. --- -- cgit v1.2.3