diff options
Diffstat (limited to 'docs/tutorial')
| -rw-r--r-- | docs/tutorial/1-serialization.md | 219 | ||||
| -rw-r--r-- | docs/tutorial/2-requests-and-responses.md | 98 | ||||
| -rw-r--r-- | docs/tutorial/3-class-based-views.md | 24 | ||||
| -rw-r--r-- | docs/tutorial/4-authentication-and-permissions.md | 83 | ||||
| -rw-r--r-- | docs/tutorial/5-relationships-and-hyperlinked-apis.md | 47 | ||||
| -rw-r--r-- | docs/tutorial/6-viewsets-and-routers.md | 40 | ||||
| -rw-r--r-- | docs/tutorial/quickstart.md | 125 | 
7 files changed, 378 insertions, 258 deletions
| diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 2b214d6a..ceb23a02 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -16,10 +16,8 @@ The tutorial is fairly in-depth, so you should probably get a cookie and a cup o  Before we do anything else we'll create a new virtual environment, using [virtualenv].  This will make sure our package configuration is kept nicely isolated from any other projects we're working on. -    :::bash -    mkdir ~/env -    virtualenv ~/env/tutorial -    source ~/env/tutorial/bin/activate +    virtualenv env +    source env/bin/activate  Now that we're inside a virtualenv environment, we can install our package requirements. @@ -42,20 +40,7 @@ Once that's done we can create an app that we'll use to create a simple Web API.      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`. +We'll need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. Let's edit the `tutorial/settings.py` file:      INSTALLED_APPS = (          ... @@ -65,15 +50,15 @@ We'll also need to add our new `snippets` app and the `rest_framework` app to `I  We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs. -    urlpatterns = patterns('', +    urlpatterns = [          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.  Note: Good programming practices include comments.  Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself. +For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets.  Go ahead and edit the `snippets/models.py` file.  Note: Good programming practices include comments.  Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.      from django.db import models      from pygments.lexers import get_all_lexers @@ -82,30 +67,27 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni      LEXERS = [item for item in get_all_lexers() if item[1]]      LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])      STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) -     -     + +      class Snippet(models.Model):          created = models.DateTimeField(auto_now_add=True)          title = models.CharField(max_length=100, blank=True, 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) -        +        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. +We'll also need to create an initial migration for our snippet model, and sync the database for the first time. -    python manage.py syncdb +    python manage.py makemigrations snippets +    python manage.py migrate  ## 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 similar to Django's forms.  Create a file in the `snippets` directory named `serializers.py` and add the following. +The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as `json`.  We can do this by declaring serializers that work very similar to Django's forms.  Create a file in the `snippets` directory named `serializers.py` and add the following.      from django.forms import widgets      from rest_framework import serializers @@ -113,42 +95,38 @@ The first thing we need to get started on our Web API is provide a way of serial      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) +        pk = serializers.IntegerField(read_only=True) +        title = serializers.CharField(required=False, allow_blank=True, max_length=100) +        code = serializers.CharField(style={'base_template': 'textarea.html'})          linenos = serializers.BooleanField(required=False) -        language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, -                                           default='python') -        style = serializers.ChoiceField(choices=STYLE_CHOICES, -                                        default='friendly') -     -        def restore_object(self, attrs, instance=None): +        language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') +        style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') + +        def create(self, validated_data): +            """ +            Create and return a new `Snippet` instance, given the validated data. +            """ +            return Snippet.objects.create(**validated_data) + +        def update(self, instance, validated_data):              """ -            Create or update a new snippet instance, given a dictionary -            of deserialized field values. -             -            Note that if we don't define this method, then deserializing -            data will simply return a dictionary of items. +            Update and return an existing `Snippet` instance, given the validated data.              """ -            if instance: -                # Update existing instance -                instance.title = attrs.get('title', instance.title) -                instance.code = attrs.get('code', instance.code) -                instance.linenos = attrs.get('linenos', instance.linenos) -                instance.language = attrs.get('language', instance.language) -                instance.style = attrs.get('style', instance.style) -                return instance +            instance.title = validated_data.get('title', instance.title) +            instance.code = validated_data.get('code', instance.code) +            instance.linenos = validated_data.get('linenos', instance.linenos) +            instance.language = validated_data.get('language', instance.language) +            instance.style = validated_data.get('style', instance.style) +            instance.save() +            return instance -            # Create new instance -            return Snippet(**attrs) +The first part of the serializer class defines the fields that get serialized/deserialized.  The `create()` and `update()` methods define how fully fledged instances are created or modified when calling `serializer.save()` -The first part of serializer class defines the fields that get serialized/deserialized.  The `restore_object` method defines how fully fledged instances get created when deserializing data. +A serializer class is very similar to a Django `Form` class, and includes similar validation flags on the various fields, such as `required`, `max_length` and `default`. -Notice that we can also use various attributes that would typically be used on form fields, such as `widget=widgets.Textarea`.  These can be used to control how the serializer should render when displayed as an HTML form.  This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial. +The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The `{'base_template': 'textarea.html'}` flag above is equivelent to using `widget=widgets.Textarea` on a Django `Form` class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial. -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.   +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 @@ -181,11 +159,11 @@ At this point we've translated the model instance into Python native datatypes.      content      # '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}' -Deserialization is similar.  First we parse a stream into Python native datatypes...  +Deserialization is similar.  First we parse a stream into Python native datatypes... -    import StringIO +    from django.utils.six import BytesIO -    stream = StringIO.StringIO(content) +    stream = BytesIO(content)      data = JSONParser().parse(stream)  ...then we restore those native datatypes into to a fully populated object instance. @@ -193,9 +171,11 @@ Deserialization is similar.  First we parse a stream into Python native datatype      serializer = SnippetSerializer(data=data)      serializer.is_valid()      # True -    serializer.object +    serializer.validated_data +    # OrderedDict([('title', ''), ('code', 'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]) +    serializer.save()      # <Snippet: Snippet object> -     +  Notice how similar the API is to working with forms.  The similarity should become even more apparent when we start writing views that use our serializer.  We can also serialize querysets instead of model instances.  To do so we simply add a `many=True` flag to the serializer arguments. @@ -211,13 +191,31 @@ Our `SnippetSerializer` class is replicating a lot of information that's also co  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. +Open the file `snippets/serializers.py` again, and replace the `SnippetSerializer` class with the following.      class SnippetSerializer(serializers.ModelSerializer):          class Meta:              model = Snippet              fields = ('id', 'title', 'code', 'linenos', 'language', 'style') +One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with `python manage.py shell`, then try the following: + +    >>> from snippets.serializers import SnippetSerializer +    >>> serializer = SnippetSerializer() +    >>> print(repr(serializer)) +    SnippetSerializer(): +        id = IntegerField(label='ID', read_only=True) +        title = CharField(allow_blank=True, max_length=100, required=False) +        code = CharField(style={'base_template': 'textarea.html'}) +        linenos = BooleanField(required=False) +        language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')... +        style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')... + +It's important to remember that `ModelSerializer` classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes: + +* An automatically determined set of fields. +* Simple default implementations for the `create()` and `update()` methods. +  ## Writing regular Django views using our Serializer  Let's see how we can write some API views using our new Serializer class. @@ -225,7 +223,7 @@ For the moment we won't use any of REST framework's other features, we'll just w  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. +Edit the `snippets/views.py` file, and add the following.      from django.http import HttpResponse      from django.views.decorators.csrf import csrf_exempt @@ -236,7 +234,7 @@ Edit the `snippet/views.py` file, and add the following.      class JSONResponse(HttpResponse):          """ -        An HttpResponse that renders it's content into JSON. +        An HttpResponse that renders its content into JSON.          """          def __init__(self, data, **kwargs):              content = JSONRenderer().render(data) @@ -261,10 +259,9 @@ The root of our API is going to be a view that supports listing all the existing              if serializer.is_valid():                  serializer.save()                  return JSONResponse(serializer.data, status=201) -            else: -                return JSONResponse(serializer.errors, status=400) +            return JSONResponse(serializer.errors, status=400) -Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as `csrf_exempt`.  This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.  +Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as `csrf_exempt`.  This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.  We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet. @@ -277,19 +274,18 @@ We'll also need a view which corresponds to an individual snippet, and can be us              snippet = Snippet.objects.get(pk=pk)          except Snippet.DoesNotExist:              return HttpResponse(status=404) -  +          if request.method == 'GET':              serializer = SnippetSerializer(snippet)              return JSONResponse(serializer.data) -     +          elif request.method == 'PUT':              data = JSONParser().parse(request)              serializer = SnippetSerializer(snippet, data=data)              if serializer.is_valid():                  serializer.save()                  return JSONResponse(serializer.data) -            else: -                return JSONResponse(serializer.errors, status=400) +            return JSONResponse(serializer.errors, status=400)          elif request.method == 'DELETE':              snippet.delete() @@ -297,12 +293,13 @@ We'll also need a view which corresponds to an individual snippet, and can be us  Finally we need to wire these views up.  Create the `snippets/urls.py` file: -    from django.conf.urls import patterns, url +    from django.conf.urls import url +    from snippets import views -    urlpatterns = patterns('snippets.views', -        url(r'^snippets/$', 'snippet_list'), -        url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail'), -    ) +    urlpatterns = [ +        url(r'^snippets/$', views.snippet_list), +        url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail), +    ]  It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment.  If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response.  Still, this'll do for now. @@ -327,17 +324,51 @@ Quit out of the shell...  In another terminal window, we can test the server. -We can get a list of all of the snippets. - -	curl http://127.0.0.1:8000/snippets/ - -	[{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}] - -Or we can get a particular snippet by referencing its id. - -	curl http://127.0.0.1:8000/snippets/2/ - -	{"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"} +We can test our API using using [curl][curl] or [httpie][httpie]. Httpie is a user friendly http client that's written in Python. Let's install that. + +You can install httpie using pip: + +    pip install httpie + +Finally, we can get a list of all of the snippets: + +    http http://127.0.0.1:8000/snippets/ + +    HTTP/1.1 200 OK +    ... +    [ +      { +        "id": 1, +        "title": "", +        "code": "foo = \"bar\"\n", +        "linenos": false, +        "language": "python", +        "style": "friendly" +      }, +      { +        "id": 2, +        "title": "", +        "code": "print \"hello, world\"\n", +        "linenos": false, +        "language": "python", +        "style": "friendly" +      } +    ] + +Or we can get a particular snippet by referencing its id: + +    http http://127.0.0.1:8000/snippets/2/ + +    HTTP/1.1 200 OK +    ... +    { +      "id": 2, +      "title": "", +      "code": "print \"hello, world\"\n", +      "linenos": false, +      "language": "python", +      "style": "friendly" +    }  Similarly, you can have the same json displayed by visiting these URLs in a web browser. @@ -354,3 +385,5 @@ We'll see how we can start to improve things in [part 2 of the tutorial][tut-2].  [sandbox]: http://restframework.herokuapp.com/  [virtualenv]: http://www.virtualenv.org/en/latest/index.html  [tut-2]: 2-requests-and-responses.md +[httpie]: https://github.com/jakubroztocil/httpie#installation +[curl]: http://curl.haxx.se diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 30966a10..e2c173d6 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -5,10 +5,10 @@ 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. +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 for 'POST', 'PUT' and 'PATCH' methods. +    request.data  # Handles arbitrary data.  Works for 'POST', 'PUT' and 'PATCH' methods.  ## Response objects @@ -29,13 +29,13 @@ REST framework provides two wrappers you can use to write API 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. +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.  +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. +We don't need our `JSONResponse` class in `views.py` 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 @@ -55,22 +55,21 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that.  On              return Response(serializer.data)          elif request.method == 'POST': -            serializer = SnippetSerializer(data=request.DATA) +            serializer = SnippetSerializer(data=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) +            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)  Our instance view is an improvement over the previous example.  It's a little more concise, and the code now feels very similar to if we were working with the Forms API.  We're also using named status codes, which makes the response meanings more obvious. -Here is the view for an individual snippet. +Here is the view for an individual snippet, in the `views.py` module.      @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: @@ -81,12 +80,11 @@ Here is the view for an individual snippet.              return Response(serializer.data)          elif request.method == 'PUT': -            serializer = SnippetSerializer(snippet, data=request.DATA) +            serializer = SnippetSerializer(snippet, data=request.data)              if serializer.is_valid():                  serializer.save()                  return Response(serializer.data) -            else: -                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) +            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)          elif request.method == 'DELETE':              snippet.delete() @@ -94,11 +92,11 @@ Here is the view for an individual snippet.  This should all feel very familiar - it is not a lot different from 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. +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 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]. +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. @@ -112,12 +110,13 @@ 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 +    from snippets import views + +    urlpatterns = [ +        url(r'^snippets/$', views.snippet_list), +        url(r'^snippets/(?P<pk>[0-9]+)$', views.snippet_detail), +    ] -    urlpatterns = patterns('snippets.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. @@ -128,31 +127,64 @@ Go ahead and test the API from the command line, as we did in [tutorial part 1][  We can get a list of all of the snippets, as before. -	curl http://127.0.0.1:8000/snippets/ - -	[{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}] +    http http://127.0.0.1:8000/snippets/ + +    HTTP/1.1 200 OK +    ... +    [ +      { +        "id": 1, +        "title": "", +        "code": "foo = \"bar\"\n", +        "linenos": false, +        "language": "python", +        "style": "friendly" +      }, +      { +        "id": 2, +        "title": "", +        "code": "print \"hello, world\"\n", +        "linenos": false, +        "language": "python", +        "style": "friendly" +      } +    ]  We can control the format of the response that we get back, either by using the `Accept` header: -    curl http://127.0.0.1:8000/snippets/ -H 'Accept: application/json'  # Request JSON -    curl http://127.0.0.1:8000/snippets/ -H 'Accept: text/html'         # Request HTML +    http http://127.0.0.1:8000/snippets/ Accept:application/json  # Request JSON +    http http://127.0.0.1:8000/snippets/ Accept:text/html         # Request HTML  Or by appending a format suffix: -    curl http://127.0.0.1:8000/snippets/.json  # JSON suffix -    curl http://127.0.0.1:8000/snippets/.api   # Browsable API suffix +    http http://127.0.0.1:8000/snippets/.json  # JSON suffix +    http http://127.0.0.1:8000/snippets/.api   # Browsable API suffix  Similarly, we can control the format of the request that we send, using the `Content-Type` header.      # POST using form data -    curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123" +    http --form POST http://127.0.0.1:8000/snippets/ code="print 123" -    {"id": 3, "title": "", "code": "123", "linenos": false, "language": "python", "style": "friendly"} -     -    # POST using JSON -    curl -X POST http://127.0.0.1:8000/snippets/ -d '{"code": "print 456"}' -H "Content-Type: application/json" +    { +      "id": 3, +      "title": "", +      "code": "print 123", +      "linenos": false, +      "language": "python", +      "style": "friendly" +    } -    {"id": 4, "title": "", "code": "print 456", "linenos": true, "language": "python", "style": "friendly"} +    # POST using JSON +    http --json POST http://127.0.0.1:8000/snippets/ code="print 456" + +    { +        "id": 4, +        "title": "", +        "code": "print 456", +        "linenos": false, +        "language": "python", +        "style": "friendly" +    }  Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver]. diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index c1b3d8f2..abf82e49 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -4,7 +4,7 @@ We can also write our API views using class based views, rather than function ba  ## 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. +We'll start by rewriting the root view as a class based view.  All this involves is a little bit of refactoring of `views.py`.      from snippets.models import Snippet      from snippets.serializers import SnippetSerializer @@ -24,13 +24,13 @@ We'll start by rewriting the root view as a class based view.  All this involves              return Response(serializer.data)          def post(self, request, format=None): -            serializer = SnippetSerializer(data=request.DATA) +            serializer = SnippetSerializer(data=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.  +So far, so good.  It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods.  We'll also need to update the instance view in `views.py`.      class SnippetDetail(APIView):          """ @@ -49,7 +49,7 @@ So far, so good.  It looks pretty similar to the previous case, but we've got be          def put(self, request, pk, format=None):              snippet = self.get_object(pk) -            serializer = SnippetSerializer(snippet, data=request.DATA) +            serializer = SnippetSerializer(snippet, data=request.data)              if serializer.is_valid():                  serializer.save()                  return Response(serializer.data) @@ -62,17 +62,17 @@ So far, so good.  It looks pretty similar to the previous case, but we've got be  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. +We'll also need to refactor our `urls.py` slightly now we're using class based views. -    from django.conf.urls import patterns, url +    from django.conf.urls import url      from rest_framework.urlpatterns import format_suffix_patterns      from snippets import views -    urlpatterns = patterns('', +    urlpatterns = [          url(r'^snippets/$', views.SnippetList.as_view()),          url(r'^snippets/(?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. @@ -81,9 +81,9 @@ 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 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. +The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar 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. +Let's take a look at how we can compose the views by using the mixin classes.  Here's our `views.py` module again.      from snippets.models import Snippet      from snippets.serializers import SnippetSerializer @@ -126,7 +126,7 @@ Pretty similar.  Again we're using the `GenericAPIView` class to provide the cor  ## 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. +Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further.  REST framework provides a set of already mixed-in generic views that we can use to trim down our `views.py` module even more.      from snippets.models import Snippet      from snippets.serializers import SnippetSerializer diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 393d879a..887d1e56 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -12,7 +12,7 @@ Currently our API doesn't have any restrictions on who can edit or delete code s  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. +Add the following two fields to the `Snippet` model in `models.py`.      owner = models.ForeignKey('auth.User', related_name='snippets')      highlighted = models.TextField() @@ -43,21 +43,23 @@ And now we can add a `.save()` method to our model class:  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 +    rm -f tmp.db db.sqlite3 +    rm -r snippets/migrations +    python manage.py makemigrations snippets +    python manage.py migrate  You might also want to create a few different users, to use for testing the API.  The quickest way to do this will be with the `createsuperuser` command. -    python ./manage.py createsuperuser +    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: +Now that we've got some users to work with, we'd better add representations of those users to our API.  Creating a new serializer is easy. In `serializers.py` add:      from django.contrib.auth.models import User      class UserSerializer(serializers.ModelSerializer): -        snippets = serializers.PrimaryKeyRelatedField(many=True) +        snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())          class Meta:              model = User @@ -65,18 +67,25 @@ Now that we've got some users to work with, we'd better add representations of t  Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we needed to add an explicit field for it. -We'll also add a couple of views.  We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class based views. +We'll also add a couple of views to `views.py`.  We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class based views. + +    from django.contrib.auth.models import User +      class UserList(generics.ListAPIView):          queryset = User.objects.all()          serializer_class = UserSerializer -     -     + +      class UserDetail(generics.RetrieveAPIView):          queryset = User.objects.all()          serializer_class = UserSerializer -Finally we need to add those views into the API, by referencing them from the URL conf. +Make sure to also import the `UserSerializer` class + +	from snippets.serializers import UserSerializer + +Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `urls.py`.      url(r'^users/$', views.UserList.as_view()),      url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()), @@ -85,24 +94,26 @@ Finally we need to add those views into the API, by referencing them from the UR  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. +The way we deal with that is by overriding a `.perform_create()` method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL. + +On the `SnippetList` view class, add the following method: -On **both** the `SnippetList` and `SnippetDetail` view classes, add the following method: +    def perform_create(self, serializer): +        serializer.save(owner=self.request.user) -    def pre_save(self, obj): -        obj.owner = self.request.user +The `create()` method of our serializer will now be passed an additional `'owner'` field, along with the validated data from the request.  ## 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: +Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that.  Add the following field to the serializer definition in `serializers.py`: -    owner = serializers.Field(source='owner.username') +    owner = serializers.ReadOnlyField(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. +The field we've added is the untyped `ReadOnlyField` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc...  The untyped `ReadOnlyField` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also used `CharField(read_only=True)` here.  ## Adding required permissions to views @@ -122,7 +133,7 @@ Then, add the following property to **both** the `SnippetList` and `SnippetDetai  If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets.  In order to do so we'd need to be able to login as a user. -We can add a login view for use with the browsable API, by editing our URLconf once more. +We can add a login view for use with the browsable API, by editing the URLconf in our project-level `urls.py` file.  Add the following import at the top of the file: @@ -130,10 +141,10 @@ Add the following import at the top of the file:  And, at the end of the file, add a pattern to include the login and logout views for the browsable API. -    urlpatterns += patterns('', +    urlpatterns += [          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. @@ -150,8 +161,8 @@ 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. @@ -160,13 +171,13 @@ In the snippets app, create a new file, `permissions.py`          def has_object_permission(self, request, view, obj):              # Read permissions are allowed to any request,              # so we'll always allow GET, HEAD or OPTIONS requests. -            if request.method in permissions.SAFE_METHODS:             +            if request.method in permissions.SAFE_METHODS:                  return True -     -            # Write permissions are only allowed to the owner of the snippet + +            # Write permissions are only allowed to the owner of the snippet.              return obj.owner == request.user -Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` class: +Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` view class:      permission_classes = (permissions.IsAuthenticatedOrReadOnly,                            IsOwnerOrReadOnly,) @@ -187,15 +198,25 @@ If we're interacting with the API programmatically we need to explicitly provide  If we try to create a snippet without authenticating, we'll get an error: -    curl -i -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123" +    http POST http://127.0.0.1:8000/snippets/ code="print 123" -    {"detail": "Authentication credentials were not provided."} +    { +        "detail": "Authentication credentials were not provided." +    }  We can make a successful request by including the username and password of one of the users we created earlier. -    curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 789" -u tom:password -     -    {"id": 5, "owner": "tom", "title": "foo", "code": "print 789", "linenos": false, "language": "python", "style": "friendly"} +    http -a tom:password POST http://127.0.0.1:8000/snippets/ code="print 789" + +    { +        "id": 5, +        "owner": "tom", +        "title": "foo", +        "code": "print 789", +        "linenos": false, +        "language": "python", +        "style": "friendly" +    }  ## Summary diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 2cf44bf9..91cdd6f1 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -1,12 +1,11 @@  # 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.  +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. +Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API.  To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. In your `snippets/views.py` add: -    from rest_framework import renderers      from rest_framework.decorators import api_view      from rest_framework.response import Response      from rest_framework.reverse import reverse @@ -29,7 +28,7 @@ Unlike all our other API endpoints, we don't want to use JSON, but instead just  The other thing we need to consider when creating the code highlight view is that there's no existing concrete 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.  In your snippets.views add: +Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method.  In your `snippets/views.py` add:      from rest_framework import renderers      from rest_framework.response import Response @@ -37,15 +36,15 @@ Instead of using a concrete generic view, we'll use the base class for represent      class SnippetHighlight(generics.GenericAPIView):          queryset = Snippet.objects.all()          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: +We'll add a url pattern for our new API root in `snippets/urls.py`: -    url(r'^$', 'api_root'), +    url(r'^$', views.api_root),  And then add a url pattern for the snippet highlights: @@ -73,21 +72,21 @@ The `HyperlinkedModelSerializer` has the following differences from `ModelSerial  * Relationships use `HyperlinkedRelatedField`,    instead of `PrimaryKeyRelatedField`. -We can easily re-write our existing serializers to use hyperlinking. +We can easily re-write our existing serializers to use hyperlinking. In your `snippets/serializers.py` add:      class SnippetSerializer(serializers.HyperlinkedModelSerializer): -        owner = serializers.Field(source='owner.username') +        owner = serializers.ReadOnlyField(source='owner.username')          highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') -     +          class Meta:              model = Snippet              fields = ('url', 'highlight', 'owner',                        'title', 'code', 'linenos', 'language', 'style') -     -     + +      class UserSerializer(serializers.HyperlinkedModelSerializer): -        snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail') -     +        snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True) +          class Meta:              model = User              fields = ('url', 'username', 'snippets') @@ -105,11 +104,13 @@ If we're going to have a hyperlinked API, we need to make sure we name our URL p  * 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: +After adding all those names into our URLconf, our final `snippets/urls.py` file should look something like this: + +    from django.conf.urls import url, include      # API endpoints -    urlpatterns = format_suffix_patterns(patterns('snippets.views', -        url(r'^$', 'api_root'), +    urlpatterns = format_suffix_patterns([ +        url(r'^$', views.api_root),          url(r'^snippets/$',              views.SnippetList.as_view(),              name='snippet-list'), @@ -125,22 +126,22 @@ After adding all those names into our URLconf, our final `'urls.py'` file should          url(r'^users/(?P<pk>[0-9]+)/$',              views.UserDetail.as_view(),              name='user-detail') -    )) -     +    ]) +      # Login and logout views for the browsable API -    urlpatterns += patterns('',     +    urlpatterns += [          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: +We can change the default list style to use pagination, by modifying our `tutorial/settings.py` file slightly.  Add the following setting:      REST_FRAMEWORK = { -        'PAGINATE_BY': 10 +        'PAGE_SIZE': 10      }  Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well separated from your other project settings. diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index f16add39..63dff73f 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -10,7 +10,7 @@ A `ViewSet` class is only bound to a set of method handlers at the last moment,  Let's take our current set of views, and refactor them into view sets. -First of all let's refactor our `UserList` and `UserDetail` views into a single `UserViewSet`.  We can remove the two views, and replace then with a single class: +First of all let's refactor our `UserList` and `UserDetail` views into a single `UserViewSet`.  We can remove the two views, and replace them with a single class:      from rest_framework import viewsets @@ -21,11 +21,11 @@ First of all let's refactor our `UserList` and `UserDetail` views into a single          queryset = User.objects.all()          serializer_class = UserSerializer -Here we've used `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations.  We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes. +Here we've used the `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations.  We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.  Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes.  We can remove the three views, and again replace them with a single class. -    from rest_framework.decorators import link +    from rest_framework.decorators import detail_route      class SnippetViewSet(viewsets.ModelViewSet):          """ @@ -39,19 +39,21 @@ Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl          permission_classes = (permissions.IsAuthenticatedOrReadOnly,                                IsOwnerOrReadOnly,) -        @link(renderer_classes=[renderers.StaticHTMLRenderer]) +        @detail_route(renderer_classes=[renderers.StaticHTMLRenderer])          def highlight(self, request, *args, **kwargs):              snippet = self.get_object()              return Response(snippet.highlighted) -        def pre_save(self, obj): -            obj.owner = self.request.user +        def perform_create(self, serializer): +                serializer.save(owner=self.request.user)  This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations. -Notice that we've also used the `@link` decorator to create a custom action, named `highlight`.  This decorator can be used to add any custom endpoints that don't fit into the standard `create`/`update`/`delete` style. +Notice that we've also used the `@detail_route` decorator to create a custom action, named `highlight`.  This decorator can be used to add any custom endpoints that don't fit into the standard `create`/`update`/`delete` style. -Custom actions which use the `@link` decorator will respond to `GET` requests.  We could have instead used the `@action` decorator if we wanted an action that responded to `POST` requests. +Custom actions which use the `@detail_route` decorator will respond to `GET` requests.  We can use the `methods` argument if we wanted an action that responded to `POST` requests. + +The URLs for custom actions by default depend on the method name itself. If you want to change the way url should be constructed, you can include url_path as a decorator keyword argument.  ## Binding ViewSets to URLs explicitly @@ -60,7 +62,8 @@ To see what's going on under the hood let's first explicitly create a set of vie  In the `urls.py` file we bind our `ViewSet` classes into a set of concrete views. -    from snippets.views import SnippetViewSet, UserViewSet +    from snippets.views import SnippetViewSet, UserViewSet, api_root +    from rest_framework import renderers      snippet_list = SnippetViewSet.as_view({          'get': 'list', @@ -84,16 +87,16 @@ In the `urls.py` file we bind our `ViewSet` classes into a set of concrete views  Notice how we're creating multiple views from each `ViewSet` class, by binding the http methods to the required action for each view. -Now that we've bound our resources into concrete views, that we can register the views with the URL conf as usual. +Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual. -    urlpatterns = format_suffix_patterns(patterns('snippets.views', -        url(r'^$', 'api_root'), +    urlpatterns = format_suffix_patterns([ +        url(r'^$', api_root),          url(r'^snippets/$', snippet_list, name='snippet-list'),          url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail, name='snippet-detail'),          url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),          url(r'^users/$', user_list, name='user-list'),          url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail') -    )) +    ])  ## Using Routers @@ -101,6 +104,7 @@ Because we're using `ViewSet` classes rather than `View` classes, we actually do  Here's our re-wired `urls.py` file. +    from django.conf.urls import url, include      from snippets import views      from rest_framework.routers import DefaultRouter @@ -110,11 +114,11 @@ Here's our re-wired `urls.py` file.      router.register(r'users', views.UserViewSet)      # The API URLs are now determined automatically by the router. -    # Additionally, we include the login URLs for the browseable API. -    urlpatterns = patterns('', +    # Additionally, we include the login URLs for the browsable API. +    urlpatterns = [          url(r'^', include(router.urls)),          url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) -    ) +    ]  Registering the viewsets with the router is similar to providing a urlpattern.  We include two arguments - the URL prefix for the views, and the viewset itself. @@ -128,7 +132,7 @@ That doesn't mean it's always the right approach to take.  There's a similar set  ## Reviewing our work -With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browseable, and comes complete with authentication, per-object permissions, and multiple renderer formats. +With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browsable, 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. @@ -136,7 +140,7 @@ You can review the final [tutorial code][repo] on GitHub, or try out a live exam  ## 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: +We've reached the end of our tutorial.  If you want to get more involved in the REST framework project, here are a few places you can start:  * Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests.  * Join the [REST framework discussion group][group], and help build the community. diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index f15e75c0..fe0ecbc7 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -6,54 +6,48 @@ We're going to create a simple API to allow admin users to view and edit the use  Create a new Django project named `tutorial`, then start a new app called `quickstart`. -    # Set up a new project -    django-admin.py startproject tutorial +    # Create the project directory +    mkdir tutorial      cd tutorial      # Create a virtualenv to isolate our package dependencies locally      virtualenv env -    source env/bin/activate +    source env/bin/activate  # On Windows use `env\Scripts\activate`      # Install Django and Django REST framework into the virtualenv      pip install django      pip install djangorestframework -    # Create a new app -    python manage.py startapp quickstart +    # Set up a new project with a single application +    django-admin.py startproject tutorial .  # Note the trailing '.' character +    cd tutorial +    django-admin.py startapp quickstart +    cd .. -Next you'll need to get a database set up and synced.  If you just want to use SQLite for now, then you'll want to edit your `tutorial/settings.py` module to include something like this: +Now sync your database for the first time: -    DATABASES = { -        'default': { -            'ENGINE': 'django.db.backends.sqlite3', -            'NAME': 'database.sql', -            'USER': '', -            'PASSWORD': '', -            'HOST': '', -            'PORT': '' -        } -    } +    python manage.py migrate -The run `syncdb` like so: +We'll also create an initial user named `admin` with a password of `password`. We'll authenticate as that user later in our example. -    python manage.py syncdb +    python manage.py createsuperuser -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... +Once you've set up a database and initial user created 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. +First up we're going to define some serializers. Let's create a new module named `tutorial/quickstart/serializers.py` that we'll use for our data representations.      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 @@ -63,21 +57,21 @@ Notice that we're using hyperlinked relations in this case, with `HyperlinkedMod  ## Views -Right, we'd better write some views then.  Open `quickstart/views.py` and get typing. +Right, we'd better write some views then.  Open `tutorial/quickstart/views.py` and get typing.      from django.contrib.auth.models import User, Group      from rest_framework import viewsets -    from quickstart.serializers import UserSerializer, GroupSerializer -     -     +    from tutorial.quickstart.serializers import UserSerializer, GroupSerializer + +      class UserViewSet(viewsets.ModelViewSet):          """          API endpoint that allows users to be viewed or edited.          """          queryset = User.objects.all()          serializer_class = UserSerializer -     -     + +      class GroupViewSet(viewsets.ModelViewSet):          """          API endpoint that allows groups to be viewed or edited. @@ -85,28 +79,32 @@ Right, we'd better write some views then.  Open `quickstart/views.py` and get ty          queryset = Group.objects.all()          serializer_class = GroupSerializer -Rather that write multiple views we're grouping together all the common behavior into classes called `ViewSets`. +Rather than write multiple views we're grouping together all the common behavior into classes called `ViewSets`.  We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise. +Notice that our viewset classes here are a little different from those in the [frontpage example][readme-example-api], as they include `queryset` and `serializer_class` attributes, instead of a `model` attribute. + +For trivial cases you can simply set a `model` attribute on the `ViewSet` class and the serializer and queryset will be automatically generated for you.  Setting the `queryset` and/or `serializer_class` attributes gives you more explicit control of the API behaviour, and is the recommended style for most applications. +  ## URLs  Okay, now let's wire up the API URLs.  On to `tutorial/urls.py`... -    from django.conf.urls import patterns, url, include +    from django.conf.urls import url, include      from rest_framework import routers -    from quickstart import views +    from tutorial.quickstart import views      router = routers.DefaultRouter()      router.register(r'users', views.UserViewSet)      router.register(r'groups', views.GroupViewSet)      # Wire up our API using automatic URL routing. -    # Additionally, we include login URLs for the browseable API. -    urlpatterns = patterns('', +    # Additionally, we include login URLs for the browsable API. +    urlpatterns = [          url(r'^', include(router.urls)),          url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) -    ) +    ]  Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class. @@ -125,7 +123,7 @@ We'd also like to set a few global settings.  We'd like to turn on pagination, a      REST_FRAMEWORK = {          'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',), -        'PAGINATE_BY': 10 +        'PAGE_SIZE': 10      }  Okay, we're done. @@ -140,35 +138,66 @@ We're now ready to test the API we've built.  Let's fire up the server from the  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/  +    bash: curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/      { -        "count": 2,  -        "next": null,  -        "previous": null,  +        "count": 2, +        "next": null, +        "previous": null,          "results": [              { -                "email": "admin@example.com",  -                "groups": [],  -                "url": "http://127.0.0.1:8000/users/1/",  +                "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/",  +                "email": "tom@example.com", +                "groups": [                ], +                "url": "http://127.0.0.1:8000/users/2/",                  "username": "tom"              }          ]      } +Or using the [httpie][httpie], command line tool... + +    bash: http -a username:password http://127.0.0.1:8000/users/ + +    HTTP/1.1 200 OK +    ... +    { +        "count": 2, +        "next": null, +        "previous": null, +        "results": [ +            { +                "email": "admin@example.com", +                "groups": [], +                "url": "http://localhost:8000/users/1/", +                "username": "paul" +            }, +            { +                "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] +If you're working through the browser, make sure to login using the control in the top right corner. +  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]. +[readme-example-api]: ../#example  [image]: ../img/quickstart.png  [tutorial]: 1-serialization.md  [guide]: ../#api-guide +[httpie]: https://github.com/jakubroztocil/httpie#installation | 
