mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-23 10:03:57 +03:00
commit
1cf6a0469b
|
@ -14,7 +14,7 @@ The tutorial is fairly in-depth, so you should probably get a cookie and a cup o
|
|||
|
||||
## 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.
|
||||
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
|
||||
|
@ -39,7 +39,6 @@ To get started, let's create a new project to work with.
|
|||
cd tutorial
|
||||
|
||||
Once that's done we can create an app that we'll use to create a simple Web API.
|
||||
We're going to create a project that
|
||||
|
||||
python manage.py startapp snippets
|
||||
|
||||
|
@ -64,7 +63,7 @@ We'll also need to add our new `snippets` app and the `rest_framework` app to `I
|
|||
'snippets'
|
||||
)
|
||||
|
||||
We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet views.
|
||||
We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs.
|
||||
|
||||
urlpatterns = patterns('',
|
||||
url(r'^', include('snippets.urls')),
|
||||
|
@ -105,7 +104,7 @@ Don't forget to sync the database for the first time.
|
|||
|
||||
## 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.
|
||||
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.
|
||||
|
||||
from django.forms import widgets
|
||||
from rest_framework import serializers
|
||||
|
@ -146,7 +145,7 @@ We can actually also save ourselves some time by using the `ModelSerializer` cla
|
|||
|
||||
## 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.
|
||||
Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.
|
||||
|
||||
python manage.py shell
|
||||
|
||||
|
@ -166,7 +165,7 @@ We've now got a few snippet instances to play with. Let's take a look at serial
|
|||
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`.
|
||||
At this point we've translated the model instance into python native datatypes. To finalize the serialization process we render the data into `json`.
|
||||
|
||||
content = JSONRenderer().render(serializer.data)
|
||||
content
|
||||
|
@ -292,7 +291,7 @@ Finally we need to wire these views up. Create the `snippets/urls.py` file:
|
|||
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.
|
||||
It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.
|
||||
|
||||
## Testing our first attempt at a Web API
|
||||
|
||||
|
@ -304,7 +303,7 @@ It's worth noting that there's a couple of edge cases we're not dealing with pro
|
|||
|
||||
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.
|
||||
Our API views don't do anything particularly special at the moment, beyond serving `json` responses, and there are 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].
|
||||
|
||||
|
|
|
@ -66,6 +66,8 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On
|
|||
|
||||
Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.
|
||||
|
||||
Here is the view for an individual snippet.
|
||||
|
||||
@api_view(['GET', 'PUT', 'DELETE'])
|
||||
def snippet_detail(request, pk):
|
||||
"""
|
||||
|
@ -92,7 +94,7 @@ Our instance view is an improvement over the previous example. It's a little mo
|
|||
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.
|
||||
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.
|
||||
|
||||
|
@ -128,7 +130,7 @@ Go ahead and test the API from the command line, as we did in [tutorial part 1][
|
|||
|
||||
**TODO: Describe using accept headers, content-type headers, and format suffixed URLs**
|
||||
|
||||
Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver]."
|
||||
Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver].
|
||||
|
||||
### Browsability
|
||||
|
||||
|
|
|
@ -102,7 +102,7 @@ Let's take a look at how we can compose our views by using the mixin classes.
|
|||
def post(self, request, *args, **kwargs):
|
||||
return self.create(request, *args, **kwargs)
|
||||
|
||||
We'll take a moment to examine exactly what's happening here - We're building our view using `MultipleObjectAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`.
|
||||
We'll take a moment to examine exactly what's happening here. We're building our view using `MultipleObjectAPIView`, 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.
|
||||
|
||||
|
@ -142,7 +142,7 @@ Using the mixin classes we've rewritten the views to use slightly less code than
|
|||
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.
|
||||
Wow, that's pretty concise. We've gotten 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.
|
||||
|
||||
|
|
|
@ -61,7 +61,7 @@ Now that we've got some users to work with, we'd better add representations of t
|
|||
model = User
|
||||
fields = ('id', '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.
|
||||
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.
|
||||
|
||||
|
@ -92,9 +92,7 @@ On **both** the `SnippetList` and `SnippetDetail` view classes, add the followin
|
|||
|
||||
## 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:
|
||||
|
||||
owner = serializers.Field(source='owner.username')
|
||||
|
||||
|
@ -108,7 +106,7 @@ The field we've added is the untyped `Field` class, in contrast to the other typ
|
|||
|
||||
## 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.
|
||||
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.
|
||||
|
||||
|
|
|
@ -25,7 +25,7 @@ Notice that we're using REST framework's `reverse` function in order to return f
|
|||
|
||||
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.
|
||||
Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two styles 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 concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.
|
||||
|
||||
|
@ -151,7 +151,7 @@ We could also customize the pagination style if we needed too, but in this case
|
|||
|
||||
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.
|
||||
You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.
|
||||
|
||||
We've now got a complete pastebin Web API, which is fully web browseable, and comes complete with authentication, per-object permissions, and multiple renderer formats.
|
||||
|
||||
|
|
|
@ -137,7 +137,7 @@ We'd also like to set a few global settings. We'd like to turn on pagination, a
|
|||
'PAGINATE_BY': 10
|
||||
}
|
||||
|
||||
Okay, that's us done.
|
||||
Okay, we're done.
|
||||
|
||||
---
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user