diff --git a/api-guide/authentication.html b/api-guide/authentication.html index 1dcb47d74..ef0f8ab14 100644 --- a/api-guide/authentication.html +++ b/api-guide/authentication.html @@ -2,6 +2,7 @@
Or, if you're using the @api_view
decorator with function based views.
@api_view('GET'),
-@authentication_classes(SessionAuthentication, UserBasicAuthentication)
-@permissions_classes(IsAuthenticated)
+@api_view(('GET',)),
+@authentication_classes((SessionAuthentication, UserBasicAuthentication))
+@permissions_classes((IsAuthenticated,))
def example_view(request, format=None):
content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance.
@@ -200,9 +203,19 @@ print token.key
To implement a custom authentication policy, subclass BaseAuthentication
and override the .authenticate(self, request)
method. The method should return a two-tuple of (user, auth)
if authentication succeeds, or None
otherwise.
By default this exception results in a response with the HTTP status code "429 Too Many Requests".
Provides a .destroy(request, *args, **kwargs)
method, that implements deletion of an existing model instance.
The method should return True
if the request should be granted access, and False
otherwise.
It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an Accept: */*
header, or not including an Accept
header at all, then REST framework will select the first renderer in the list to use for the response.
For example if your API serves JSON responses and the HTML browseable API, you might want to make JSONRenderer
your default renderer, in order to send JSON
responses to clients that do not specify an Accept
header.
If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making TemplateHTMLRenderer
your default renderer, in order to play nicely with older browsers that send broken accept headers.
.media_type: application/json
Response
does not ne
.format: '.html'
To implement a custom renderer, you should override BaseRenderer
, set the .media_type
and .format
properties, and implement the .render(self, data, media_type)
method.
You can do some pretty flexible things using REST framework's renderers. Some examples...
Response
does not ne
media_type = 'image/*'
, and use the Accept
header to vary the encoding of the response. In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access request.accepted_renderer
to determine the negotiated renderer that will be used for the response.
For example:
@api_view(('GET',))
@@ -232,9 +239,19 @@ def list_users(request):
For good examples of custom media types, see GitHub's use of a custom application/vnd.github+json media type, and Mike Amundsen's IANA approved application/vnd.collection+json JSON-based hypermedia.
If you're using the rest_framework.views.View
class... [TODO]
The unrendered content of a Request
object can be accessed using the .data
attribute.
The unrendered content of a Request
object.
The numeric status code of the HTTP response.
The rendered content of the response. .render()
must have been called before .content
can be accessed.
The rendered content of the response. The .render()
method must have been called before .content
can be accessed.
The template_name
, if supplied. Only required if HTMLTemplateRenderer
or some other custom template renderer is the accepted renderer for the reponse.
Set automatically by the APIView
or @api_view
immediately before the response is returned from the view.
Has the same behavior as django.core.urlresolvers.reverse_lazy
, except that it returns a fully qualified URL, using the request to determine the host and port.
ModelSerializer
class lets you automatically create a Serialize
Default: 'format'
Optionally you may also override the .wait()
method. If implemented, .wait()
should return a recomended number of seconds to wait before attempting the next request, or None
. The .wait()
method will only be called if .check_throttle()
has previously returned False
.
The following methods are called directly by the view's .dispatch()
method.
These perform any actions that need to occur before or after calling the handler methods such as .get()
, .post()
, put()
and .delete()
.
Performs any actions that need to occur before the handler method gets called. This method is used to enforce permissions and throttling, and perform content negotiation.
You won't typically need to override this method.
@@ -173,10 +176,10 @@ This method is used to enforce permissions and throttling, and perform content nAny exception thrown by the handler method will be passed to this method, which either returns a Response
instance, or re-raises the exception.
The default implementation handles any subclass of rest_framework.exceptions.APIException
, as well as Django's Http404
and PermissionDenied
exceptions, and returns an appropriate error response.
If you need to customize the error responses your API returns you should subclass this method.
-Ensures that the request object that is passed to the handler method is an instance of Request
, rather than the usual Django HttpRequest
.
You won't typically need to override this method.
-Ensures that any Response
object returned from the handler method will be rendered into the correct content type, as determined by the content negotation.
You won't typically need to override this method.
[TODO]
For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have api.html
extend base.html
. Then the page content and capabilities are entirely up to you.
Describe compat module
Nope. It was at one point intended to support PUT
and DELETE
forms, but was later dropped from the spec. There remains ongoing discussion about adding support for PUT
and DELETE
, as well as how to support content types other than form-encoded data.
What REST framework doesn't do is give you is machine readable hypermedia formats such as Collection+JSON by default, or the ability to auto-magically create HATEOAS style APIs. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.
Okay, we're ready to get coding. To get started, let's create a new project to work with.
-django-admin.py startproject tutorial
+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.
@@ -173,7 +177,7 @@ class Comment(models.Model):
python manage.py syncdb
Creating a Serializer class
-We're going to create a simple Web API that we can use to edit these comment objects with. The first thing we need is a way of serializing and deserializing the objects into representations such as json
. We do this by declaring serializers that work very similarly to Django's forms. Create a file in the project named serializers.py
and add the following.
+We're going to create a simple Web API that we can use to edit these comment objects with. The first thing we need is a way of serializing and deserializing the objects into representations such as json
. We do this by declaring serializers that work very similarly to Django's forms. Create a file in the blog
directory named serializers.py
and add the following.
from blog import models
from rest_framework import serializers
@@ -325,9 +329,19 @@ urlpatterns = patterns('blog.views',
We'll see how we can start to improve things in part 2 of the tutorial.
In tutorial part 3, we'll start using class based views, and see how generic views reduce the amount of code we need to write.
Next we'll move onto part 4 of the tutorial, where we'll take a look at how we can customize the behavior of our views to support a range of authentication, permissions, throttling and other aspects.
Nothing to see here. Onwards to part 5.
Onwards to part 6.
Now go build some awesome things.