diff options
Diffstat (limited to 'docs/tutorial')
| -rw-r--r-- | docs/tutorial/1-serialization.md | 315 | ||||
| -rw-r--r-- | docs/tutorial/2-requests-and-responses.md | 150 | ||||
| -rw-r--r-- | docs/tutorial/3-class-based-views.md | 150 | ||||
| -rw-r--r-- | docs/tutorial/4-authentication-and-permissions.md | 189 | ||||
| -rw-r--r-- | docs/tutorial/5-relationships-and-hyperlinked-apis.md | 173 | ||||
| -rw-r--r-- | docs/tutorial/quickstart.md | 172 |
6 files changed, 1149 insertions, 0 deletions
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md new file mode 100644 index 00000000..5cf16a67 --- /dev/null +++ b/docs/tutorial/1-serialization.md @@ -0,0 +1,315 @@ +# Tutorial 1: Serialization + +## Introduction + +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. --> + +--- + +**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. + + :::bash + mkdir ~/env + virtualenv ~/env/tutorial + source ~/env/tutorial/bin/activate + +Now that we're inside a virtualenv environment, we can install our package requirements. + + 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]. + +## Getting started + +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 + +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 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"`. + + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': 'tmp.db', + 'USER': '', + 'PASSWORD': '', + 'HOST': '', + 'PORT': '', + } + } + +We'll also need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. + + INSTALLED_APPS = ( + ... + 'rest_framework', + 'snippets' + ) + +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('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 `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 + 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. + + python manage.py syncdb + +## Creating a Serializer class + +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 django.forms import widgets + from rest_framework import serializers + 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 snippet instance. + """ + if instance: + # Update existing instance + instance.title = attrs['title'] + instance.code = attrs['code'] + instance.linenos = attrs['linenos'] + instance.language = attrs['language'] + instance.style = attrs['style'] + return instance + + # 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. + +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, let's create a code snippet to work with. + + from snippets.models import Snippet + from snippets.serializers import SnippetSerializer + from rest_framework.renderers import JSONRenderer + from rest_framework.parsers import JSONParser + + snippet = Snippet(code='print "hello, world"\n') + snippet.save() + +We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances. + + serializer = SnippetSerializer(instance=snippet) + serializer.data + # {'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 + # '{"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... + + import StringIO + + stream = StringIO.StringIO(content) + data = JSONParser().parse(stream) + +...then we restore those native datatypes into to a fully populated object instance. + + serializer = SnippetSerializer(data) + serializer.is_valid() + # True + serializer.object + # <Snippet: Snippet object> + +Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer. + +## 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 = 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 `snippet/views.py` file, and add the following. + + 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): + """ + 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 snippets, or creating a new snippet. + + @csrf_exempt + def snippet_list(request): + """ + List all code snippets, or create a new snippet. + """ + if request.method == 'GET': + snippets = Snippet.objects.all() + serializer = SnippetSerializer(instance=snippets) + return JSONResponse(serializer.data) + + elif request.method == 'POST': + data = JSONParser().parse(request) + serializer = SnippetSerializer(data) + if serializer.is_valid(): + 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 snippet, and can be used to retrieve, update or delete the snippet. + + @csrf_exempt + def snippet_detail(request, pk): + """ + Retrieve, update or delete a code snippet. + """ + try: + snippet = Snippet.objects.get(pk=pk) + except Snippet.DoesNotExist: + return HttpResponse(status=404) + + if request.method == 'GET': + serializer = SnippetSerializer(instance=snippet) + return JSONResponse(serializer.data) + + elif request.method == 'PUT': + data = JSONParser().parse(request) + serializer = SnippetSerializer(data, instance=snippet) + if serializer.is_valid(): + serializer.save() + return JSONResponse(serializer.data) + else: + return JSONResponse(serializer.errors, status=400) + + elif request.method == 'DELETE': + snippet.delete() + return HttpResponse(status=204) + +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'^snippets/$', 'snippet_list'), + url(r'^snippets/(?P<pk>[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. + +## 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][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/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md new file mode 100644 index 00000000..938739fa --- /dev/null +++ b/docs/tutorial/2-requests-and-responses.md @@ -0,0 +1,150 @@ +# 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. + +## Request objects + +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. + +## 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 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. + + +## Pulling it all together + +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 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 snippet_list(request): + """ + List all snippets, or create a new snippet. + """ + if request.method == 'GET': + snippets = Snippet.objects.all() + serializer = SnippetSerializer(instance=snippets) + return Response(serializer.data) + + elif request.method == 'POST': + serializer = SnippetSerializer(request.DATA) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) + else: + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + +Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious. + + @api_view(['GET', 'PUT', 'DELETE']) + def snippet_detail(request, pk): + """ + Retrieve, update or delete a snippet instance. + """ + try: + snippet = Snippet.objects.get(pk=pk) + except Snippet.DoesNotExist: + return Response(status=status.HTTP_404_NOT_FOUND) + + if request.method == 'GET': + serializer = SnippetSerializer(instance=snippet) + return Response(serializer.data) + + elif request.method == 'PUT': + serializer = SnippetSerializer(request.DATA, instance=snippet) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data) + else: + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + elif request.method == '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. + +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 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. + + def snippet_list(request, format=None): + +and + + 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('snippet.views', + url(r'^snippets/$', 'snippet_list'), + url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail') + ) + + urlpatterns = format_suffix_patterns(urlpatterns) + +We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format. + +## How's it looking? + +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/snippets/][devserver]." + +**Note: Right now the Browseable API only works with the CBV's. Need to fix that.** + +### Browsability + +Because the API chooses a return format based on what the client asks for, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a browser. This allows for the API to be easily browsable and usable by humans. + +See the [browsable api][browseable-api] topic for more information about the browsable API feature and how to customize it. + + +## What's next? + +In [tutorial part 3][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/snippets/ +[browseable-api]: ../topics/browsable-api.md +[tut-1]: 1-serialization.md +[tut-3]: 3-class-based-views.md diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md new file mode 100644 index 00000000..f27b5af0 --- /dev/null +++ b/docs/tutorial/3-class-based-views.md @@ -0,0 +1,150 @@ +# 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][dry]. + +## 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 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 SnippetList(APIView): + """ + List all snippets, or create a new snippet. + """ + def get(self, request, format=None): + snippets = Snippet.objects.all() + serializer = SnippetSerializer(instance=snippets) + return Response(serializer.data) + + def post(self, request, format=None): + serializer = SnippetSerializer(request.DATA) + if serializer.is_valid(): + 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 SnippetDetail(APIView): + """ + Retrieve, update or delete a snippet instance. + """ + def get_object(self, pk): + try: + return Snippet.objects.get(pk=pk) + except Snippet.DoesNotExist: + raise Http404 + + def get(self, request, pk, format=None): + snippet = self.get_object(pk) + serializer = SnippetSerializer(instance=snippet) + return Response(serializer.data) + + def put(self, request, pk, format=None): + snippet = self.get_object(pk) + serializer = SnippetSerializer(request.DATA, instance=snippet) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + def delete(self, request, pk, format=None): + 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. + +We'll also need to refactor our URLconf slightly now we're using class based views. + + from django.conf.urls import patterns, url + from rest_framework.urlpatterns import format_suffix_patterns + from snippetpost import views + + urlpatterns = patterns('', + url(r'^$', views.SnippetList.as_view()), + url(r'^(?P<pk>[0-9]+)$', views.SnippetDetail.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 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. + +Let's take a look at how we can compose our views by using the mixin classes. + + from snippet.models import Snippet + from snippet.serializers import SnippetSerializer + from rest_framework import mixins + from rest_framework import generics + + class SnippetList(mixins.ListModelMixin, + mixins.CreateModelMixin, + generics.MultipleObjectBaseView): + model = Snippet + serializer_class = SnippetSerializer + + def get(self, request, *args, **kwargs): + return self.list(request, *args, **kwargs) + + def post(self, request, *args, **kwargs): + return self.create(request, *args, **kwargs) + +We'll take a moment to examine exactly what's happening here - We're building our view using `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 explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far. + + class SnippetDetail(mixins.RetrieveModelMixin, + mixins.UpdateModelMixin, + mixins.DestroyModelMixin, + generics.SingleObjectBaseView): + model = Snippet + serializer_class = SnippetSerializer + + 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) + +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 + +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 snippet.models import Snippet + from snippet.serializers import SnippetSerializer + from rest_framework import generics + + + class SnippetList(generics.ListCreateAPIView): + model = Snippet + serializer_class = SnippetSerializer + + + 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 deal with authentication and permissions for our API. + +[dry]: http://en.wikipedia.org/wiki/Don't_repeat_yourself +[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..b0ed8f2a --- /dev/null +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -0,0 +1,189 @@ +# Tutorial 4: Authentication & Permissions + +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 + +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 need 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<pk>[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 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. + +**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. + +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 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. + +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/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md new file mode 100644 index 00000000..1f663745 --- /dev/null +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -0,0 +1,173 @@ +# Tutorial 5 - Relationships & Hyperlinked APIs + +At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships. + +## Creating an endpoint for the root of our API + +Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. + + 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<pk>[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', format='html') + + 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. + +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. + +* 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<pk>[0-9]+)/$', + views.SnippetInstance.as_view(), + name='snippet-detail'), + url(r'^snippets/(?P<pk>[0-9]+)/highlight/$' + views.SnippetHighlight.as_view(), + name='snippet-highlight'), + url(r'^users/$', + views.UserList.as_view(), + name='user-list'), + url(r'^users/(?P<pk>[0-9]+)/$', + views.UserInstance.as_view(), + name='user-detail') + )) + + # Login and logout views for the browsable API + urlpatterns += patterns('', + url(r'^api-auth/', include('rest_framework.urls', + 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. + +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://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 diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md new file mode 100644 index 00000000..6bde725b --- /dev/null +++ b/docs/tutorial/quickstart.md @@ -0,0 +1,172 @@ +# 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 write some views then. Open `quickstart/views.py` and get typing. + + from django.contrib.auth.models import User, Group + from rest_framework import generics + from rest_framework.decorators import api_view + from rest_framework.reverse import reverse + from rest_framework.response import Response + from 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<pk>\d+)/$', UserDetail.as_view(), name='user-detail'), + url(r'^groups/$', GroupList.as_view(), name='group-list'), + url(r'^groups/(?P<pk>\d+)/$', GroupDetail.as_view(), name='group-detail'), + ) + + + # Format suffixes + urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'api']) + + + # 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 = { + 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',), + 'PAGINATE_BY': 10 + } + +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]: ../img/quickstart.png +[tutorial]: 1-serialization.md +[guide]: ../#api-guide |
