diff --git a/.travis.yml b/.travis.yml index dfb084961..0e177a95a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,10 +10,8 @@ env: - DJANGO=django==1.3.3 --use-mirrors install: - - pip install $DJANGO - - pip install -e . --use-mirrors - - pip install -r requirements.txt --use-mirrors - - pip install coverage==3.5.1 --use-mirrors + - pip install $DJANGO + - export PYTHONPATH=. script: - - python setup.py test + - python rest_framework/runtests/runtests.py diff --git a/README.md b/README.md index d8ffce944..4b2245cca 100644 --- a/README.md +++ b/README.md @@ -6,11 +6,23 @@ [![build-status-image]][travis] +--- + +**Full documentation for REST framework is available on [http://django-rest-framework.org][docs].** + +Note that this is the 2.0 version of REST framework. If you are looking for earlier versions please see the [0.4.x branch][0.4] on GitHub. + +--- + # Overview -This branch is the redesign of Django REST framework. It is a work in progress. +Django REST framework is a lightweight library that makes it easy to build Web APIs. It is designed as a modular and easy to customize architecture, based on Django's class based views. -For more information, check out [the documentation][docs], in particular, the tutorial is recommended as the best place to get an overview of the redesign. +Web APIs built using REST framework are fully self-describing and web browseable - a huge useability win for your developers. It also supports a wide range of media types, authentication and permission policies out of the box. + +If you are considering using REST framework for your API, we recommend reading the [REST framework 2 announcment][rest-framework-2-announcement] which gives a good overview of the framework and it's capabilities. + +There is also a sandbox API you can use for testing purposes, [available here][sandbox]. # Requirements @@ -24,21 +36,15 @@ For more information, check out [the documentation][docs], in particular, the tu # Installation -**Leaving these instructions in for the moment, they'll be valid once this becomes the master version** - Install using `pip`... - pip install rest_framework + pip install djangorestframework ...or clone the project from github. git clone git@github.com:tomchristie/django-rest-framework.git pip install -r requirements.txt -# Quickstart - -**TODO** - # Development To build the docs. @@ -82,9 +88,13 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=restframework2 -[travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=restframework2 +[travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master [twitter]: https://twitter.com/_tomchristie -[docs]: http://tomchristie.github.com/django-rest-framework/ +[0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X +[sandbox]: http://restframework.herokuapp.com/ +[rest-framework-2-announcement]: topics/rest-framework-2-announcement.md + +[docs]: http://django-rest-framework.org/ [urlobject]: https://github.com/zacharyvoase/urlobject [markdown]: http://pypi.python.org/pypi/Markdown/ [pyyaml]: http://pypi.python.org/pypi/PyYAML diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index ae21c66eb..3137b9d4c 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -26,11 +26,11 @@ The value of `request.user` and `request.auth` for unauthenticated requests can ## Setting the authentication policy -The default authentication policy may be set globally, using the `DEFAULT_AUTHENTICATION` setting. For example. +The default authentication policy may be set globally, using the `DEFAULT_AUTHENTICATION_CLASSES` setting. For example. REST_FRAMEWORK = { - 'DEFAULT_AUTHENTICATION': ( - 'rest_framework.authentication.UserBasicAuthentication', + 'DEFAULT_AUTHENTICATION_CLASSES': ( + 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } @@ -38,7 +38,7 @@ The default authentication policy may be set globally, using the `DEFAULT_AUTHEN You can also set the authentication policy on a per-view basis, using the `APIView` class based views. class ExampleView(APIView): - authentication_classes = (SessionAuthentication, UserBasicAuthentication) + authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) def get(self, request, format=None): @@ -50,8 +50,8 @@ You can also set the authentication policy on a per-view basis, using the `APIVi Or, if you're using the `@api_view` decorator with function based views. - @api_view(('GET',)), - @authentication_classes((SessionAuthentication, UserBasicAuthentication)) + @api_view(['GET']) + @authentication_classes((SessionAuthentication, BasicAuthentication)) @permissions_classes((IsAuthenticated,)) def example_view(request, format=None): content = { @@ -60,6 +60,8 @@ Or, if you're using the `@api_view` decorator with function based views. } return Response(content) +# API Reference + ## BasicAuthentication This policy uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing. @@ -84,7 +86,7 @@ You'll also need to create tokens for your users. token = Token.objects.create(user=...) print token.key -For clients to authenticate, the token key should be included in the `Authorization` HTTP header. The key should be prefixed by the string literal "Token", with whitespace seperating the two strings. For example: +For clients to authenticate, the token key should be included in the `Authorization` HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b @@ -113,7 +115,7 @@ If successfully authenticated, `SessionAuthentication` provides the following cr * `request.user` will be a `django.contrib.auth.models.User` instance. * `request.auth` will be `None`. -## Custom authentication policies +# Custom authentication 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. diff --git a/docs/api-guide/content-negotiation.md b/docs/api-guide/content-negotiation.md index ad98de3b9..10288c94d 100644 --- a/docs/api-guide/content-negotiation.md +++ b/docs/api-guide/content-negotiation.md @@ -7,3 +7,60 @@ > — [RFC 2616][cite], Fielding et al. [cite]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html + +Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client or server preferences. + +## Determining the accepted renderer + +REST framework uses a simple style of content negotiation to determine which media type should be returned to a client, based on the available renderers, the priorities of each of those renderers, and the client's `Accept:` header. The style used is partly client-driven, and partly server-driven. + +1. More specific media types are given preference to less specific media types. +2. If multiple media types have the same specificity, then preference is given to based on the ordering of the renderers configured for the given view. + +For example, given the following `Accept` header: + + application/json; indent=4, application/json, application/yaml, text/html, */* + +The priorities for each of the given media types would be: + +* `application/json; indent=4` +* `application/json`, `application/yaml` and `text/html` +* `*/*` + +If the requested view was only configured with renderers for `YAML` and `HTML`, then REST framework would select whichever renderer was listed first in the `renderer_classes` list or `DEFAULT_RENDERER_CLASSES` setting. + +For more information on the `HTTP Accept` header, see [RFC 2616][accept-header] + +--- + +**Note**: "q" values are not taken into account by REST framework when determining preference. The use of "q" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation. + +This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences. + +--- + +# Custom content negotiation + +It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override `BaseContentNegotiation`. + +REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the `.select_parser(request, parsers)` and `.select_renderer(request, renderers, format_suffix)` methods. + +## Example + +The following is a custom content negotiation class which ignores the client +request when selecting the appropriate parser or renderer. + + class IgnoreClientContentNegotiation(BaseContentNegotiation): + def select_parser(self, request, parsers): + """ + Select the first parser in the `.parser_classes` list. + """ + return parsers[0] + + def select_renderer(self, request, renderers, format_suffix): + """ + Select the first renderer in the `.renderer_classes` list. + """ + return renderers[0] + +[accept-header]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index c22d6d8bb..ba57fde87 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -25,7 +25,7 @@ For example, the following request: DELETE http://api.example.com/foo/bar HTTP/1.1 Accept: application/json -Might recieve an error response indicating that the `DELETE` method is not allowed on that resource: +Might receive an error response indicating that the `DELETE` method is not allowed on that resource: HTTP/1.1 405 Method Not Allowed Content-Type: application/json; charset=utf-8 @@ -33,11 +33,15 @@ Might recieve an error response indicating that the `DELETE` method is not allow {"detail": "Method 'DELETE' not allowed."} +--- + +# API Reference + ## APIException **Signature:** `APIException(detail=None)` -The base class for all exceptions raised inside REST framework. +The **base class** for all exceptions raised inside REST framework. To provide a custom exception, subclass `APIException` and set the `.status_code` and `.detail` properties on the class. @@ -81,4 +85,4 @@ Raised when an incoming request fails the throttling checks. By default this exception results in a response with the HTTP status code "429 Too Many Requests". -[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html \ No newline at end of file +[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index df54ea021..8c3df0678 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -12,6 +12,51 @@ Serializer fields handle converting between primative values and internal dataty **Note:** The serializer fields are declared in fields.py, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.`. +--- + +## Core arguments + +Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted: + +### `source` + +The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `Field(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `Field(source='user.email')`. + +The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations. (See the implementation of the `PaginationSerializer` class for an example.) + +Defaults to the name of the field. + +### `read_only` + +Set this to `True` to ensure that the field is used when serializing a representation, but is not used when updating an instance dureing deserialization. + +Defaults to `False` + +### `required` + +Normally an error will be raised if a field is not supplied during deserialization. +Set to false if this field is not required to be present during deserialization. + +Defaults to `True`. + +### `default` + +If set, this gives the default value that will be used for the field if none is supplied. If not set the default behaviour is to not populate the attribute at all. + +### `validators` + +A list of Django validators that should be used to validate deserialized values. + +### `error_messages` + +A dictionary of error codes to error messages. + +### `widget` + +Used only if rendering the field to HTML. +This argument sets the widget that should be used to render the field. + + --- # Generic Fields @@ -42,7 +87,7 @@ A serializer definition that looked like this: class Meta: fields = ('url', 'owner', 'name', 'expired') -Would produced output similar to: +Would produce output similar to: { 'url': 'http://example.com/api/accounts/3/', @@ -51,7 +96,7 @@ Would produced output similar to: 'expired': True } -Be default, the `Field` class will perform a basic translation of the source value into primative datatypes, falling back to unicode representations of complex datatypes when neccesary. +By default, the `Field` class will perform a basic translation of the source value into primative datatypes, falling back to unicode representations of complex datatypes when necessary. You can customize this behaviour by overriding the `.to_native(self, value)` method. @@ -73,18 +118,53 @@ These fields represent basic datatypes, and support both reading and writing val ## BooleanField +A Boolean representation. + +Corresponds to `django.db.models.fields.BooleanField`. + ## CharField +A text representation, optionally validates the text to be shorter than `max_length` and longer than `min_length`. + +Corresponds to `django.db.models.fields.CharField` +or `django.db.models.fields.TextField`. + +**Signature:** `CharField(max_length=None, min_length=None)` + +## ChoiceField + +A field that can accept a value out of a limited set of choices. + ## EmailField +A text representation, validates the text to be a valid e-mail address. + +Corresponds to `django.db.models.fields.EmailField` + ## DateField +A date representation. + +Corresponds to `django.db.models.fields.DateField` + ## DateTimeField +A date and time representation. + +Corresponds to `django.db.models.fields.DateTimeField` + ## IntegerField +An integer representation. + +Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField` + ## FloatField +A floating point representation. + +Corresponds to `django.db.models.fields.FloatField`. + --- # Relational Fields @@ -148,7 +228,7 @@ And a model serializer defined like this: model = Bookmark exclude = ('id',) -The an example output format for a Bookmark instance would be: +Then an example output format for a Bookmark instance would be: { 'tags': [u'django', u'python'], @@ -157,24 +237,42 @@ The an example output format for a Bookmark instance would be: ## PrimaryKeyRelatedField -As with `RelatedField` field can be applied to any "to-one" relationship, such as a `ForeignKey` field. +This field can be applied to any "to-one" relationship, such as a `ForeignKey` field. `PrimaryKeyRelatedField` will represent the target of the field using it's primary key. -Be default, `PrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `readonly` flag. +Be default, `PrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `read_only` flag. ## ManyPrimaryKeyRelatedField -As with `RelatedField` field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship. +This field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship. -`PrimaryKeyRelatedField` will represent the target of the field using their primary key. +`PrimaryKeyRelatedField` will represent the targets of the field using their primary key. -Be default, `ManyPrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `readonly` flag. +Be default, `ManyPrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `read_only` flag. ## HyperlinkedRelatedField +This field can be applied to any "to-one" relationship, such as a `ForeignKey` field. + +`HyperlinkedRelatedField` will represent the target of the field using a hyperlink. You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the target of the hyperlink. + +Be default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag. + ## ManyHyperlinkedRelatedField +This field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship. + +`ManyHyperlinkedRelatedField` will represent the targets of the field using hyperlinks. You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the target of the hyperlink. + +Be default, `ManyHyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag. + ## HyperLinkedIdentityField +This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. + +You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the model. + +This field is always read-only. + [cite]: http://www.python.org/dev/peps/pep-0020/ diff --git a/docs/api-guide/format-suffixes.md b/docs/api-guide/format-suffixes.md index 7d72d9f87..6d5feba42 100644 --- a/docs/api-guide/format-suffixes.md +++ b/docs/api-guide/format-suffixes.md @@ -7,5 +7,55 @@ used all the time. > > — Roy Fielding, [REST discuss mailing list][cite] -[cite]: http://tech.groups.yahoo.com/group/rest-discuss/message/5857 +A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation. +Adding format-suffix patterns to each individual entry in the URLconf for your API is error-prone and non-DRY, so REST framework provides a shortcut to adding these patterns to your URLConf. + +## format_suffix_patterns + +**Signature**: format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None) + +Returns a URL pattern list which includes format suffix patterns appended to each of the URL patterns provided. + +Arguments: + +* **urlpatterns**: Required. A URL pattern list. +* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default. +* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. + +Example: + + from rest_framework.urlpatterns import format_suffix_patterns + + urlpatterns = patterns('blog.views', + url(r'^/$', 'api_root'), + url(r'^comment/$', 'comment_root'), + url(r'^comment/(?P[0-9]+)/$', 'comment_instance') + ) + + urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) + +When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example. + + @api_view(('GET',)) + def api_root(request, format=None): + # do stuff... + +The name of the kwarg used may be modified by using the `FORMAT_SUFFIX_KWARG` setting. + +Also note that `format_suffix_patterns` does not support descending into `include` URL patterns. + +--- + +## Accept headers vs. format suffixes + +There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that `HTTP Accept` headers should always be used instead. + +It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators: + +“That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, [REST discuss mailing list][cite2] + +The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern. + +[cite]: http://tech.groups.yahoo.com/group/rest-discuss/message/5857 +[cite2]: http://tech.groups.yahoo.com/group/rest-discuss/message/14844 \ No newline at end of file diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 8bf7a7e2b..360ef1a2e 100644 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -30,7 +30,7 @@ For more complex cases you might also want to override various methods on the vi serializer_class = UserSerializer permission_classes = (IsAdminUser,) - def get_paginate_by(self): + def get_paginate_by(self, queryset): """ Use smaller pagination for HTML representations. """ @@ -49,21 +49,21 @@ For very simple cases you might want to pass through any class attributes using The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior. +## CreateAPIView + +Used for **create-only** endpoints. + +Provides `post` method handlers. + +Extends: [GenericAPIView], [CreateModelMixin] + ## ListAPIView Used for **read-only** endpoints to represent a **collection of model instances**. Provides a `get` method handler. -Extends: [MultipleObjectBaseAPIView], [ListModelMixin] - -## ListCreateAPIView - -Used for **read-write** endpoints to represent a **collection of model instances**. - -Provides `get` and `post` method handlers. - -Extends: [MultipleObjectBaseAPIView], [ListModelMixin], [CreateModelMixin] +Extends: [MultipleObjectAPIView], [ListModelMixin] ## RetrieveAPIView @@ -71,7 +71,31 @@ Used for **read-only** endpoints to represent a **single model instance**. Provides a `get` method handler. -Extends: [SingleObjectBaseAPIView], [RetrieveModelMixin] +Extends: [SingleObjectAPIView], [RetrieveModelMixin] + +## DestroyAPIView + +Used for **delete-only** endpoints for a **single model instance**. + +Provides a `delete` method handler. + +Extends: [SingleObjectAPIView], [DestroyModelMixin] + +## UpdateAPIView + +Used for **update-only** endpoints for a **single model instance**. + +Provides a `put` method handler. + +Extends: [SingleObjectAPIView], [UpdateModelMixin] + +## ListCreateAPIView + +Used for **read-write** endpoints to represent a **collection of model instances**. + +Provides `get` and `post` method handlers. + +Extends: [MultipleObjectAPIView], [ListModelMixin], [CreateModelMixin] ## RetrieveDestroyAPIView @@ -79,15 +103,15 @@ Used for **read or delete** endpoints to represent a **single model instance**. Provides `get` and `delete` method handlers. -Extends: [SingleObjectBaseAPIView], [RetrieveModelMixin], [DestroyModelMixin] +Extends: [SingleObjectAPIView], [RetrieveModelMixin], [DestroyModelMixin] ## RetrieveUpdateDestroyAPIView -Used for **read-write** endpoints to represent a **single model instance**. +Used for **read-write-delete** endpoints to represent a **single model instance**. Provides `get`, `put` and `delete` method handlers. -Extends: [SingleObjectBaseAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin] +Extends: [SingleObjectAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin] --- @@ -95,17 +119,17 @@ Extends: [SingleObjectBaseAPIView], [RetrieveModelMixin], [UpdateModelMixin], [D Each of the generic views provided is built by combining one of the base views below, with one or more mixin classes. -## BaseAPIView +## GenericAPIView Extends REST framework's `APIView` class, adding support for serialization of model instances and model querysets. -## MultipleObjectBaseAPIView +## MultipleObjectAPIView Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [MultipleObjectMixin]. **See also:** ccbv.co.uk documentation for [MultipleObjectMixin][multiple-object-mixin-classy]. -## SingleObjectBaseAPIView +## SingleObjectAPIView Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [SingleObjectMixin]. @@ -121,31 +145,31 @@ The mixin classes provide the actions that are used to provide the basic view be Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset. -Should be mixed in with [MultipleObjectBaseAPIView]. +Should be mixed in with [MultipleObjectAPIView]. ## CreateModelMixin Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance. -Should be mixed in with any [BaseAPIView]. +Should be mixed in with any [GenericAPIView]. ## RetrieveModelMixin Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response. -Should be mixed in with [SingleObjectBaseAPIView]. +Should be mixed in with [SingleObjectAPIView]. ## UpdateModelMixin Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance. -Should be mixed in with [SingleObjectBaseAPIView]. +Should be mixed in with [SingleObjectAPIView]. ## DestroyModelMixin Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance. -Should be mixed in with [SingleObjectBaseAPIView]. +Should be mixed in with [SingleObjectAPIView]. [cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views [MultipleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-multiple-object/ @@ -153,9 +177,9 @@ Should be mixed in with [SingleObjectBaseAPIView]. [multiple-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.list/MultipleObjectMixin/ [single-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.detail/SingleObjectMixin/ -[BaseAPIView]: #baseapiview -[SingleObjectBaseAPIView]: #singleobjectbaseapiview -[MultipleObjectBaseAPIView]: #multipleobjectbaseapiview +[GenericAPIView]: #genericapiview +[SingleObjectAPIView]: #singleobjectapiview +[MultipleObjectAPIView]: #multipleobjectapiview [ListModelMixin]: #listmodelmixin [CreateModelMixin]: #createmodelmixin [RetrieveModelMixin]: #retrievemodelmixin diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 50be59bf9..597baba4d 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -100,12 +100,16 @@ You can also set the pagination style on a per-view basis, using the `ListAPIVie For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods. -## Creating custom pagination serializers +--- + +# Custom pagination serializers To create a custom pagination serializer class you should override `pagination.BasePaginationSerializer` and set the fields that you want the serializer to return. You can also override the name used for the object list field, by setting the `results_field` attribute, which defaults to `'results'`. +## Example + For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this. class LinksSerializer(serializers.Serializer): diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index b9bb49004..59f00f999 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -8,17 +8,154 @@ sending more complex data than simple forms > > — Malcom Tredinnick, [Django developers group][cite] +REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts. + +## How the parser is determined + +The set of valid parsers for a view is always defined as a list of classes. When either `request.DATA` or `request.FILES` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content. + +## Setting the parsers + +The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow requests with `YAML` content. + + REST_FRAMEWORK = { + 'DEFAULT_PARSER_CLASSES': ( + 'rest_framework.parsers.YAMLParser', + ) + } + +You can also set the renderers used for an individual view, using the `APIView` class based views. + + class ExampleView(APIView): + """ + A view that can accept POST requests with YAML content. + """ + parser_classes = (YAMLParser,) + + def post(self, request, format=None): + return Response({'received data': request.DATA}) + +Or, if you're using the `@api_view` decorator with function based views. + + @api_view(['POST']) + @parser_classes((YAMLParser,)) + def example_view(request, format=None): + """ + A view that can accept POST requests with YAML content. + """ + return Response({'received data': request.DATA}) + +--- + +# API Reference ## JSONParser +Parses `JSON` request content. + +**.media_type**: `application/json` + ## YAMLParser +Parses `YAML` request content. + +**.media_type**: `application/yaml` + ## XMLParser +Parses REST framework's default style of `XML` request content. + +Note that the `XML` markup language is typically used as the base language for more strictly defined domain-specific languages, such as `RSS`, `Atom`, and `XHTML`. + +If you are considering using `XML` for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type. + +**.media_type**: `application/xml` + ## FormParser +Parses HTML form content. `request.DATA` will be populated with a `QueryDict` of data, `request.FILES` will be populated with an empty `QueryDict` of data. + +You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data. + +**.media_type**: `application/x-www-form-urlencoded` + ## MultiPartParser -## Custom parsers +Parses multipart HTML form content, which supports file uploads. Both `request.DATA` and `request.FILES` will be populated with a `QueryDict`. + +You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data. + +**.media_type**: `multipart/form-data` + +--- + +# Custom parsers + +To implement a custom parser, you should override `BaseParser`, set the `.media_type` property, and implement the `.parse(self, stream, media_type, parser_context)` method. + +The method should return the data that will be used to populate the `request.DATA` property. + +The arguments passed to `.parse()` are: + +### stream + +A stream-like object representing the body of the request. + +### media_type + +Optional. If provided, this is the media type of the incoming request content. + +Depending on the request's `Content-Type:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"text/plain; charset=utf-8"`. + +### parser_context + +Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content. + +By default this will include the following keys: `view`, `request`, `args`, `kwargs`. + +## Example + +The following is an example plaintext parser that will populate the `request.DATA` property with a string representing the body of the request. + + class PlainTextParser(BaseParser): + """ + Plain text parser. + """ + + media_type = 'text/plain' + + def parse(self, stream, media_type=None, parser_context=None): + """ + Simply return a string representing the body of the request. + """ + return stream.read() + +## Uploading file content + +If your custom parser needs to support file uploads, you may return a `DataAndFiles` object from the `.parse()` method. `DataAndFiles` should be instantiated with two arguments. The first argument will be used to populate the `request.DATA` property, and the second argument will be used to populate the `request.FILES` property. + +For example: + + class SimpleFileUploadParser(BaseParser): + """ + A naive raw file upload parser. + """ + + def parse(self, stream, media_type=None, parser_context=None): + content = stream.read() + name = 'example.dat' + content_type = 'application/octet-stream' + size = len(content) + charset = 'utf-8' + + # Write a temporary file based on the request content + temp = tempfile.NamedTemporaryFile(delete=False) + temp.write(content) + uploaded = UploadedFile(temp, name, content_type, size, charset) + + # Return the uploaded file + data = {} + files = {name: uploaded} + return DataAndFiles(data, files) [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index b6912d888..1a746fb64 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -6,7 +6,7 @@ > > — [Apple Developer Documentation][cite] -Together with [authentication] and [throttling], permissions determine wheter a request should be granted or denied access. +Together with [authentication] and [throttling], permissions determine whether a request should be granted or denied access. Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the `request.user` and `request.auth` properties to determine if the incoming request should be permitted. @@ -25,14 +25,20 @@ Object level permissions are run by REST framework's generic views when `.get_ob ## Setting the permission policy -The default permission policy may be set globally, using the `DEFAULT_PERMISSIONS` setting. For example. +The default permission policy may be set globally, using the `DEFAULT_PERMISSION_CLASSES` setting. For example. REST_FRAMEWORK = { - 'DEFAULT_PERMISSIONS': ( + 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } +If not specified, this setting defaults to allowing unrestricted access: + + 'DEFAULT_PERMISSION_CLASSES': ( + 'rest_framework.permissions.AllowAny', + ) + You can also set the authentication policy on a per-view basis, using the `APIView` class based views. class ExampleView(APIView): @@ -54,6 +60,16 @@ Or, if you're using the `@api_view` decorator with function based views. } return Response(content) +--- + +# API Reference + +## AllowAny + +The `AllowAny` permission class will allow unrestricted access, **regardless of if the request was authenticated or unauthenticated**. + +This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit. + ## IsAuthenticated The `IsAuthenticated` permission class will deny permission to any unauthenticated user, and allow permission otherwise. @@ -62,7 +78,7 @@ This permission is suitable if you want your API to only be accessible to regist ## IsAdminUser -The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff`is `True` in which case permission will be allowed. +The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff` is `True` in which case permission will be allowed. This permission is suitable is you want your API to only be accessible to a subset of trusted administrators. @@ -86,12 +102,15 @@ To use custom model permissions, override `DjangoModelPermissions` and set the ` The `DjangoModelPermissions` class also supports object-level permissions. Third-party authorization backends such as [django-guardian][guardian] that provide object-level permissions should work just fine with `DjangoModelPermissions` without any custom configuration required. -## Custom permissions +--- + +# Custom permissions To implement a custom permission, override `BasePermission` and implement the `.has_permission(self, request, view, obj=None)` method. The method should return `True` if the request should be granted access, and `False` otherwise. + [cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html [authentication]: authentication.md [throttling]: throttling.md diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index b2ebd0c7e..c3d12ddbb 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -6,7 +6,7 @@ > > — [Django documentation][cite] -REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexiblity to design your own media types. +REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types. ## How the renderer is determined @@ -18,10 +18,10 @@ For more information see the documentation on [content negotation][conneg]. ## Setting the renderers -The default set of renderers may be set globally, using the `DEFAULT_RENDERERS` setting. For example, the following settings would use `YAML` as the main media type and also include the self describing API. +The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CLASSES` setting. For example, the following settings would use `YAML` as the main media type and also include the self describing API. REST_FRAMEWORK = { - 'DEFAULT_RENDERERS': ( + 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.YAMLRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ) @@ -42,8 +42,8 @@ You can also set the renderers used for an individual view, using the `APIView` Or, if you're using the `@api_view` decorator with function based views. - @api_view('GET'), - @renderer_classes(JSONRenderer, JSONPRenderer) + @api_view(['GET']) + @renderer_classes((JSONRenderer, JSONPRenderer)) def user_count_view(request, format=None): """ A view that returns the count of active users, in JSON or JSONp. @@ -66,34 +66,52 @@ If your API includes views that can serve both regular webpages and API response ## JSONRenderer -**.media_type:** `application/json` +Renders the request data into `JSON`. -**.format:** `'.json'` +The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`. + +**.media_type**: `application/json` + +**.format**: `'.json'` ## JSONPRenderer -**.media_type:** `application/javascript` +Renders the request data into `JSONP`. The `JSONP` media type provides a mechanism of allowing cross-domain AJAX requests, by wrapping a `JSON` response in a javascript callback. -**.format:** `'.jsonp'` +The javascript callback function must be set by the client including a `callback` URL query parameter. For example `http://example.com/api/users?callback=jsonpCallback`. If the callback function is not explicitly set by the client it will default to `'callback'`. + +**Note**: If you require cross-domain AJAX requests, you may also want to consider using [CORS] as an alternative to `JSONP`. + +**.media_type**: `application/javascript` + +**.format**: `'.jsonp'` ## YAMLRenderer -**.media_type:** `application/yaml` +Renders the request data into `YAML`. -**.format:** `'.yaml'` +**.media_type**: `application/yaml` + +**.format**: `'.yaml'` ## XMLRenderer -**.media_type:** `application/xml` +Renders REST framework's default style of `XML` response content. -**.format:** `'.xml'` +Note that the `XML` markup language is used typically used as the base language for more strictly defined domain-specific languages, such as `RSS`, `Atom`, and `XHTML`. -## HTMLRenderer +If you are considering using `XML` for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type. + +**.media_type**: `application/xml` + +**.format**: `'.xml'` + +## TemplateHTMLRenderer Renders data to HTML, using Django's standard template rendering. Unlike other renderers, the data passed to the `Response` does not need to be serialized. Also, unlike other renderers, you may want to include a `template_name` argument when creating the `Response`. -The HTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context. +The TemplateHTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context. The template name is determined by (in order of preference): @@ -101,40 +119,84 @@ The template name is determined by (in order of preference): 2. An explicit `.template_name` attribute set on this class. 3. The return result of calling `view.get_template_names()`. -An example of a view that uses `HTMLRenderer`: +An example of a view that uses `TemplateHTMLRenderer`: class UserInstance(generics.RetrieveUserAPIView): """ A view that returns a templated HTML representations of a given user. """ model = Users - renderer_classes = (HTMLRenderer,) + renderer_classes = (TemplateHTMLRenderer,) def get(self, request, *args, **kwargs) self.object = self.get_object() - return Response(self.object, template_name='user_detail.html') + return Response({'user': self.object}, template_name='user_detail.html') -You can use `HTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint. +You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint. -If you're building websites that use `HTMLRenderer` along with other renderer classes, you should consider listing `HTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers. +If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers. -**.media_type:** `text/html` +**.media_type**: `text/html` -**.format:** `'.html'` +**.format**: `'.html'` + +See also: `StaticHTMLRenderer` + +## StaticHTMLRenderer + +A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned. + +An example of a view that uses `TemplateHTMLRenderer`: + + @api_view(('GET',)) + @renderer_classes((StaticHTMLRenderer,)) + def simple_html_view(request): + data = '

Hello, world

' + return Response(data) + +You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint. + +**.media_type**: `text/html` + +**.format**: `'.html'` + +See also: `TemplateHTMLRenderer` ## BrowsableAPIRenderer Renders data into HTML for the Browseable API. This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page. -**.media_type:** `text/html` +**.media_type**: `text/html` -**.format:** `'.api'` +**.format**: `'.api'` -## Custom renderers +--- + +# Custom renderers To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, media_type=None, renderer_context=None)` method. -For example: +The arguments passed to the `.render()` method are: + +### `data` + +The request data, as set by the `Response()` instantiation. + +### `media_type=None` + +Optional. If provided, this is the accepted media type, as determined by the content negotiation stage. + +Depending on the client's `Accept:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"application/json; nested=true"`. + +### `renderer_context=None` + +Optional. If provided, this is a dictionary of contextual information provided by the view. + +By default this will include the following keys: `view`, `request`, `response`, `args`, `kwargs`. + +## Example + +The following is an example plaintext renderer that will return a response with the `data` parameter as the content of the response. from django.utils.encoding import smart_unicode from rest_framework import renderers @@ -149,21 +211,6 @@ For example: return data return smart_unicode(data) -The arguments passed to the `.render()` method are: - -#### `data` - -The request data, as set by the `Response()` instantiation. - -#### `media_type=None` - -Optional. If provided, this is the accepted media type, as determined by the content negotiation stage. Depending on the client's `Accept:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"application/json; nested=true"`. - -#### `renderer_context=None` - -Optional. If provided, this is a dictionary of contextual information provided by the view. -By default this will include the following keys: `view`, `request`, `response`, `args`, `kwargs`. - --- # Advanced renderer usage @@ -182,7 +229,7 @@ In some cases you might want your view to use different serialization styles dep For example: @api_view(('GET',)) - @renderer_classes((HTMLRenderer, JSONRenderer)) + @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def list_users(request): """ A view that can return JSON or HTML representations @@ -190,9 +237,9 @@ For example: """ queryset = Users.objects.filter(active=True) - if request.accepted_media_type == 'text/html': + if request.accepted_renderer.format == 'html': # TemplateHTMLRenderer takes a context dict, - # and additionally requiresa 'template_name'. + # and additionally requires a 'template_name'. # It does not require serialization. data = {'users': queryset} return Response(data, template_name='list_users.html') @@ -204,7 +251,7 @@ For example: ## Designing your media types -For the purposes of many Web APIs, simple `JSON` responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and [HATEOAS] you'll neeed to consider the design and usage of your media types in more detail. +For the purposes of many Web APIs, simple `JSON` responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and [HATEOAS] you'll need to consider the design and usage of your media types in more detail. In [the words of Roy Fielding][quote], "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.". @@ -213,6 +260,7 @@ For good examples of custom media types, see GitHub's use of a custom [applicati [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process [conneg]: content-negotiation.md [browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers +[CORS]: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing [HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas [quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven [application/vnd.github+json]: http://developer.github.com/v3/media/ diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md index 36513cd9f..72932f5d6 100644 --- a/docs/api-guide/requests.md +++ b/docs/api-guide/requests.md @@ -6,63 +6,123 @@ > > — Malcom Tredinnick, [Django developers group][cite] -REST framework's `Request` class extends the standard `HttpRequest`, adding support for parsing multiple content types, allowing browser-based `PUT`, `DELETE` and other methods, and adding flexible per-request authentication. +REST framework's `Request` class extends the standard `HttpRequest`, adding support for REST framework's flexible request parsing and request authentication. -## .method - -`request.method` returns the uppercased string representation of the request's HTTP method. - -Browser-based `PUT`, `DELETE` and other requests are supported, and can be made by using a hidden form field named `_method` in a regular `POST` form. - - - -## .content_type - -`request.content`, returns a string object representing the mimetype of the HTTP request's body, if one exists. +--- +# Request parsing +REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data. ## .DATA -`request.DATA` returns the parsed content of the request body. This is similar to the standard `HttpRequest.POST` attribute except that: +`request.DATA` returns the parsed content of the request body. This is similar to the standard `request.POST` attribute except that: -1. It supports parsing the content of HTTP methods other than `POST`, meaning that you can access the content of `PUT` and `PATCH` requests. -2. It supports parsing multiple content types, rather than just form data. For example you can handle incoming json data in the same way that you handle incoming form data. +* It supports parsing the content of HTTP methods other than `POST`, meaning that you can access the content of `PUT` and `PATCH` requests. +* It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data. + +For more details see the [parsers documentation]. ## .FILES -`request.FILES` returns any uploaded files that may be present in the content of the request body. This is the same as the standard `HttpRequest` behavior, except that the same flexible request parsing that is used for `request.DATA`. +`request.FILES` returns any uploaded files that may be present in the content of the request body. This is the same as the standard `HttpRequest` behavior, except that the same flexible request parsing is used for `request.DATA`. -This allows you to support file uploads from multiple content-types. For example you can write a parser that supports `POST`ing the raw content of a file, instead of using form-encoded file uploads. +For more details see the [parsers documentation]. -## .user +## .QUERY_PARAMS -`request.user` returns a `django.contrib.auth.models.User` instance. +`request.QUERY_PARAMS` is a more correctly named synonym for `request.GET`. -## .auth - -`request.auth` returns any additional authentication context that may not be contained in `request.user`. The exact behavior of `request.auth` depends on what authentication has been set in `request.authentication`. For many types of authentication this will simply be `None`, but it may also be an object representing a permission scope, an expiry time, or any other information that might be contained in a token-based authentication scheme. +For clarity inside your code, we recommend using `request.QUERY_PARAMS` instead of the usual `request.GET`, as *any* HTTP method type may include query parameters. ## .parsers -`request.parsers` should be set to a list of `Parser` instances that can be used to parse the content of the request body. +The `APIView` class or `@api_view` decorator will ensure that this property is automatically set to a list of `Parser` instances, based on the `parser_classes` set on the view or based on the `DEFAULT_PARSER_CLASSES` setting. -`request.parsers` may no longer be altered once `request.DATA`, `request.FILES` or `request.POST` have been accessed. +You won't typically need to access this property. -If you're using the `rest_framework.views.View` class... **[TODO]** +--- + +**Note:** If a client sends malformed content, then accessing `request.DATA` or `request.FILES` may raise a `ParseError`. By default REST framework's `APIView` class or `@api_view` decorator will catch the error and return a `400 Bad Request` response. + +If a client sends a request with a content-type that cannot be parsed then a `UnsupportedMediaType` exception will be raised, which by default will be caught and return a `415 Unsupported Media Type` response. + +--- + +# Authentication + +REST framework provides flexible, per-request authentication, that gives you the ability to: + +* Use different authentication policies for different parts of your API. +* Support the use of multiple authentication policies. +* Provide both user and token information associated with the incoming request. + +## .user + +`request.user` typically returns an instance of `django.contrib.auth.models.User`, although the behavior depends on the authentication policy being used. + +If the request is unauthenticated the default value of `request.user` is an instance of `django.contrib.auth.models.AnonymousUser`. + +For more details see the [authentication documentation]. + +## .auth + +`request.auth` returns any additional authentication context. The exact behavior of `request.auth` depends on the authentication policy being used, but it may typically be an instance of the token that the request was authenticated against. + +If the request is unauthenticated, or if no additional context is present, the default value of `request.auth` is `None`. + +For more details see the [authentication documentation]. + +## .authenticators + +The `APIView` class or `@api_view` decorator will ensure that this property is automatically set to a list of `Authentication` instances, based on the `authentication_classes` set on the view or based on the `DEFAULT_AUTHENTICATORS` setting. + +You won't typically need to access this property. + +--- + +# Browser enhancements + +REST framework supports a few browser enhancements such as browser-based `PUT` and `DELETE` forms. + +## .method + +`request.method` returns the **uppercased** string representation of the request's HTTP method. + +Browser-based `PUT` and `DELETE` forms are transparently supported. + +For more information see the [browser enhancements documentation]. + +## .content_type + +`request.content_type`, returns a string object representing the media type of the HTTP request's body, or an empty string if no media type was provided. + +You won't typically need to directly access the request's content type, as you'll normally rely on REST framework's default request parsing behavior. + +If you do need to access the content type of the request you should use the `.content_type` property in preference to using `request.META.get('HTTP_CONTENT_TYPE')`, as it provides transparent support for browser-based non-form content. + +For more information see the [browser enhancements documentation]. ## .stream `request.stream` returns a stream representing the content of the request body. -You will not typically need to access `request.stream`, unless you're writing a `Parser` class. +You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior. -## .authentication +If you do need to access the raw content directly, you should use the `.stream` property in preference to using `request.content`, as it provides transparent support for browser-based non-form content. -`request.authentication` should be set to a list of `Authentication` instances that can be used to authenticate the request. +For more information see the [browser enhancements documentation]. -`request.authentication` may no longer be altered once `request.user` or `request.auth` have been accessed. +--- + +# Standard HttpRequest attributes + +As REST framework's `Request` extends Django's `HttpRequest`, all the other standard attributes and methods are also available. For example the `request.META` dictionary is available as normal. + +Note that due to implementation reasons the `Request` class does not inherit from `HttpRequest` class, but instead extends the class using composition. -If you're using the `rest_framework.views.View` class... **[TODO]** [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion +[parsers documentation]: parsers.md +[authentication documentation]: authentication.md +[browser enhancements documentation]: ../topics/browser-enhancements.md diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md index b0de6824e..794f93774 100644 --- a/docs/api-guide/responses.md +++ b/docs/api-guide/responses.md @@ -16,7 +16,7 @@ Unless you want to heavily customize REST framework for some reason, you should --- -# Methods +# Creating responses ## Response() @@ -35,21 +35,6 @@ Arguments: * `template_name`: A template name to use if `HTMLRenderer` is selected. * `headers`: A dictionary of HTTP headers to use in the response. -## .render() - -**Signature:** `.render()` - -This methd is called to render the serialized data of the response into the final response content. When `.render()` is called, the response content will be set to the result of calling the `.render(data, accepted_media_type)` method on the accepted renderer instance. - -You won't typically need to call `.render()` yourself, as it's handled by Django's standard response cycle. - -## Standard response methods - -The `Response` class extends `SimpleTemplateResponse`, and all the usual methods are also available on the response. For example you can set headers on the response in the standard way: - - response = Response() - response['Cache-Control'] = 'no-cache' - --- # Attributes @@ -88,5 +73,22 @@ A dictionary of additional context information that will be passed to the render Set automatically by the `APIView` or `@api_view` immediately before the response is returned from the view. +--- + +# Standard HttpResponse attributes + +The `Response` class extends `SimpleTemplateResponse`, and all the usual attributes and methods are also available on the response. For example you can set headers on the response in the standard way: + + response = Response() + response['Cache-Control'] = 'no-cache' + +## .render() + +**Signature:** `.render()` + +As with any other `TemplateResponse`, this method is called to render the serialized data of the response into the final response content. When `.render()` is called, the response content will be set to the result of calling the `.render(data, accepted_media_type, renderer_context)` method on the `accepted_renderer` instance. + +You won't typically need to call `.render()` yourself, as it's handled by Django's standard response cycle. + [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/ [statuscodes]: status-codes.md diff --git a/docs/api-guide/reverse.md b/docs/api-guide/reverse.md index 12346eb4f..19930dc3f 100644 --- a/docs/api-guide/reverse.md +++ b/docs/api-guide/reverse.md @@ -6,7 +6,7 @@ > > — Roy Fielding, [Architectural Styles and the Design of Network-based Software Architectures][cite] -As a rule, it's probably better practice to return absolute URIs from you Web APIs, such as `http://example.com/foobar`, rather than returning relative URIs, such as `/foobar`. +As a rule, it's probably better practice to return absolute URIs from your Web APIs, such as `http://example.com/foobar`, rather than returning relative URIs, such as `/foobar`. The advantages of doing so are: diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 47958fe31..c88b9b0c6 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -76,7 +76,28 @@ Deserialization is similar. First we parse a stream into python native datatype When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object. If any validation errors occur, the `.errors` and `.non_field_errors` properties will contain the resulting error messages. -**TODO: Describe validation in more depth** +### Field-level validation + +You can specify custom field-level validation by adding `validate_()` methods to your `Serializer` subclass. These are analagous to `clean_` methods on Django forms, but accept slightly different arguments. They take a dictionary of deserialized attributes as a first argument, and the field name in that dictionary as a second argument (which will be either the name of the field or the value of the `source` argument to the field, if one was provided). Your `validate_` methods should either just return the attrs dictionary or raise a `ValidationError`. For example: + + from rest_framework import serializers + + class BlogPostSerializer(serializers.Serializer): + title = serializers.CharField(max_length=100) + content = serializers.CharField() + + def validate_title(self, attrs, source): + """ + Check that the blog post is about Django + """ + value = attrs[source] + if "Django" not in value: + raise serializers.ValidationError("Blog post is not about Django") + return attrs + +### Final cross-field validation + +To do any other validation that requires access to multiple fields, add a method called `validate` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. ## Dealing with nested objects @@ -86,21 +107,21 @@ where some of the attributes of an object might not be simple datatypes such as The `Serializer` class is itself a type of `Field`, and can be used to represent relationships where one object type is nested inside another. class UserSerializer(serializers.Serializer): - email = serializers.EmailField() - username = serializers.CharField() - - def restore_object(self, attrs, instance=None): - return User(**attrs) - + email = serializers.Field() + username = serializers.Field() class CommentSerializer(serializers.Serializer): user = UserSerializer() - title = serializers.CharField() - content = serializers.CharField(max_length=200) - created = serializers.DateTimeField() - - def restore_object(self, attrs, instance=None): - return Comment(**attrs) + title = serializers.Field() + content = serializers.Field() + created = serializers.Field() + +--- + +**Note**: Nested serializers are only suitable for read-only representations, as there are cases where they would have ambiguous or non-obvious behavior if used when updating instances. For read-write representations you should always use a flat representation, by using one of the `RelatedField` subclasses. + +--- + ## Creating custom fields @@ -114,7 +135,6 @@ Let's look at an example of serializing a class that represents an RGB color val """ A color represented in the RGB colorspace. """ - def __init__(self, red, green, blue): assert(red >= 0 and green >= 0 and blue >= 0) assert(red < 256 and green < 256 and blue < 256) @@ -124,7 +144,6 @@ Let's look at an example of serializing a class that represents an RGB color val """ Color objects are serialized into "rgb(#, #, #)" notation. """ - def to_native(self, obj): return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue) @@ -169,13 +188,13 @@ The `ModelSerializer` class lets you automatically create a Serializer class wit You can add extra fields to a `ModelSerializer` or override the default fields by declaring fields on the class, just as you would for a `Serializer` class. class AccountSerializer(serializers.ModelSerializer): - url = CharField(source='get_absolute_url', readonly=True) + url = CharField(source='get_absolute_url', read_only=True) group = NaturalKeyField() class Meta: model = Account -Extra fields can corrospond to any property or callable on the model. +Extra fields can correspond to any property or callable on the model. ## Relational fields @@ -187,7 +206,7 @@ The `PrimaryKeyRelatedField` and `HyperlinkedRelatedField` fields provide altern The `ModelSerializer` class can itself be used as a field, in order to serialize relationships using nested representations. -The `RelatedField` class may be subclassed to create a custom represenation of a relationship. The subclass should override `.to_native()`, and optionally `.from_native()` if deserialization is supported. +The `RelatedField` class may be subclassed to create a custom representation of a relationship. The subclass should override `.to_native()`, and optionally `.from_native()` if deserialization is supported. All the relational fields may be used for any relationship or reverse relationship on a model. @@ -204,40 +223,54 @@ For example: ## Specifiying nested serialization -The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `nested` option: +The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account exclude = ('id',) - nested = True + depth = 1 -The `nested` option may be set to either `True`, `False`, or an integer value. If given an integer value it indicates the depth of relationships that should be traversed before reverting to a flat representation. +The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation. -When serializing objects using a nested representation any occurances of recursion will be recognised, and will fall back to using a flat representation. +## Customising the default fields -## Customising the default fields used by a ModelSerializer +You can create customized subclasses of `ModelSerializer` that use a different set of default fields for the representation, by overriding various `get__field` methods. +Each of these methods may either return a field or serializer instance, or `None`. +### get_pk_field - class AccountSerializer(serializers.ModelSerializer): - class Meta: - model = Account +**Signature**: `.get_pk_field(self, model_field)` +Returns the field instance that should be used to represent the pk field. + +### get_nested_field + +**Signature**: `.get_nested_field(self, model_field)` + +Returns the field instance that should be used to represent a related field when `depth` is specified as being non-zero. + +### get_related_field + +**Signature**: `.get_related_field(self, model_field, to_many=False)` + +Returns the field instance that should be used to represent a related field when `depth` is not specified, or when nested representations are being used and the depth reaches zero. + +### get_field + +**Signature**: `.get_field(self, model_field)` + +Returns the field instance that should be used for non-relational, non-pk fields. + +### Example: + +The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default. + + class NoPKModelSerializer(serializers.ModelSerializer): def get_pk_field(self, model_field): - return serializers.Field(readonly=True) + return None - def get_nested_field(self, model_field): - return serializers.ModelSerializer() - - def get_related_field(self, model_field, to_many=False): - queryset = model_field.rel.to._default_manager - if to_many: - return return serializers.ManyRelatedField(queryset=queryset) - return serializers.RelatedField(queryset=queryset) - - def get_field(self, model_field): - return serializers.ModelField(model_field=model_field) [cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index f473128ed..4f87b30da 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -11,10 +11,10 @@ Configuration for REST framework is all namespaced inside a single Django settin For example your project's `settings.py` file might include something like this: REST_FRAMEWORK = { - 'DEFAULT_RENDERERS': ( + 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.YAMLRenderer', - ) - 'DEFAULT_PARSERS': ( + ), + 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.YAMLParser', ) } @@ -26,11 +26,15 @@ you should use the `api_settings` object. For example. from rest_framework.settings import api_settings - print api_settings.DEFAULT_AUTHENTICATION + print api_settings.DEFAULT_AUTHENTICATION_CLASSES The `api_settings` object will check for any user-defined settings, and otherwise fallback to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal. -## DEFAULT_RENDERERS +--- + +# API Reference + +## DEFAULT_RENDERER_CLASSES A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a `Response` object. @@ -38,11 +42,11 @@ Default: ( 'rest_framework.renderers.JSONRenderer', - 'rest_framework.renderers.BrowsableAPIRenderer' + 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework.renderers.TemplateHTMLRenderer' ) -## DEFAULT_PARSERS +## DEFAULT_PARSER_CLASSES A list or tuple of parser classes, that determines the default set of parsers used when accessing the `request.DATA` property. @@ -53,7 +57,7 @@ Default: 'rest_framework.parsers.FormParser' ) -## DEFAULT_AUTHENTICATION +## DEFAULT_AUTHENTICATION_CLASSES A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the `request.user` or `request.auth` properties. @@ -64,25 +68,29 @@ Default: 'rest_framework.authentication.UserBasicAuthentication' ) -## DEFAULT_PERMISSIONS +## DEFAULT_PERMISSION_CLASSES A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. -Default: `()` +Default: -## DEFAULT_THROTTLES + ( + 'rest_framework.permissions.AllowAny', + ) + +## DEFAULT_THROTTLE_CLASSES A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view. Default: `()` -## DEFAULT_MODEL_SERIALIZER +## DEFAULT_MODEL_SERIALIZER_CLASS **TODO** Default: `rest_framework.serializers.ModelSerializer` -## DEFAULT_PAGINATION_SERIALIZER +## DEFAULT_PAGINATION_SERIALIZER_CLASS **TODO** diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index 0e228905d..b03bc9e04 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -27,13 +27,13 @@ If any throttle check fails an `exceptions.Throttled` exception will be raised, ## Setting the throttling policy -The default throttling policy may be set globally, using the `DEFAULT_THROTTLES` and `DEFAULT_THROTTLE_RATES` settings. For example. +The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_CLASSES` and `DEFAULT_THROTTLE_RATES` settings. For example. REST_FRAMEWORK = { - 'DEFAULT_THROTTLES': ( - 'rest_framework.throttles.AnonThrottle', - 'rest_framework.throttles.UserThrottle', - ) + 'DEFAULT_THROTTLE_CLASSES': ( + 'rest_framework.throttling.AnonRateThrottle', + 'rest_framework.throttling.UserRateThrottle' + ), 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '1000/day' @@ -63,6 +63,10 @@ Or, if you're using the `@api_view` decorator with function based views. } return Response(content) +--- + +# API Reference + ## AnonRateThrottle The `AnonThrottle` will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against. @@ -76,7 +80,7 @@ The allowed request rate is determined from one of the following (in order of pr ## UserRateThrottle -The `UserThrottle` will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticted requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against. +The `UserThrottle` will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against. The allowed request rate is determined from one of the following (in order of preference). @@ -96,10 +100,10 @@ For example, multiple user throttle rates could be implemented by using the foll ...and the following settings. REST_FRAMEWORK = { - 'DEFAULT_THROTTLES': ( + 'DEFAULT_THROTTLE_CLASSES': ( 'example.throttles.BurstRateThrottle', - 'example.throttles.SustainedRateThrottle', - ) + 'example.throttles.SustainedRateThrottle' + ), 'DEFAULT_THROTTLE_RATES': { 'burst': '60/min', 'sustained': '1000/day' @@ -110,7 +114,7 @@ For example, multiple user throttle rates could be implemented by using the foll ## ScopedRateThrottle -The `ScopedThrottle` class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a `.throttle_scope` property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unqiue user id or IP address. +The `ScopedThrottle` class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a `.throttle_scope` property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address. The allowed request rate is determined by the `DEFAULT_THROTTLE_RATES` setting using a key from the request "scope". @@ -131,9 +135,9 @@ For example, given the following views... ...and the following settings. REST_FRAMEWORK = { - 'DEFAULT_THROTTLES': ( - 'rest_framework.throttles.ScopedRateThrottle', - ) + 'DEFAULT_THROTTLE_CLASSES': ( + 'rest_framework.throttling.ScopedRateThrottle' + ), 'DEFAULT_THROTTLE_RATES': { 'contacts': '1000/day', 'uploads': '20/day' @@ -142,10 +146,12 @@ For example, given the following views... User requests to either `ContactListView` or `ContactDetailView` would be restricted to a total of 1000 requests per-day. User requests to `UploadView` would be restricted to 20 requests per day. -## Custom throttles +--- + +# Custom throttles To create a custom throttle, override `BaseThrottle` and implement `.allow_request(request, view)`. The method should return `True` if the request should be allowed, and `False` otherwise. -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 `.allow_request()` has previously returned `False`. +Optionally you may also override the `.wait()` method. If implemented, `.wait()` should return a recommended number of seconds to wait before attempting the next request, or `None`. The `.wait()` method will only be called if `.allow_request()` has previously returned `False`. [permissions]: permissions.md diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md index cbfa2e28e..5b072827e 100644 --- a/docs/api-guide/views.md +++ b/docs/api-guide/views.md @@ -27,14 +27,14 @@ For example: * Only admin users are able to access this view. """ authentication_classes = (authentication.TokenAuthentication,) - permission_classes = (permissions.IsAdmin,) + permission_classes = (permissions.IsAdminUser,) def get(self, request, format=None): """ Return a list of all users. """ - users = [user.username for user in User.objects.all()] - return Response(users) + usernames = [user.username for user in User.objects.all()] + return Response(usernames) ## API policy attributes @@ -118,9 +118,51 @@ You won't typically need to override this method. > > — [Nick Coghlan][cite2] -REST framework also gives you to work with regular function based views... +REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of `Request` (rather than the usual Django `HttpRequest`) and allows them to return a `Response` (instead of a Django `HttpResponse`), and allow you to configure how the request is processed. -**[TODO]** +## @api_view() + +**Signature:** `@api_view(http_method_names)` + +The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data: + + from rest_framework.decorators import api_view + + @api_view(['GET']) + def hello_world(request): + return Response({"message": "Hello, world!"}) + + +This view will use the default renderers, parsers, authentication classes etc specified in the [settings](settings). + +## API policy decorators + +To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle](throttling) to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes: + + from rest_framework.decorators import api_view, throttle_classes + from rest_framework.throttling import UserRateThrottle + + class OncePerDayUserThrottle(UserRateThrottle): + rate = '1/day' + + @api_view(['GET']) + @throttle_classes([OncePerDayUserThrottle]) + def view(request): + return Response({"message": "Hello for today! See you tomorrow!"}) + +These decorators correspond to the attributes set on `APIView` subclasses, described above. + +The available decorators are: + +* `@renderer_classes(...)` +* `@parser_classes(...)` +* `@authentication_classes(...)` +* `@throttle_classes(...)` +* `@permission_classes(...)` + +Each of these decorators takes a single argument which must be a list or tuple of classes. [cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html -[cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html \ No newline at end of file +[cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html +[settings]: api-guide/settings.md +[throttling]: api-guide/throttling.md diff --git a/docs/css/default.css b/docs/css/default.css index c1d2e885d..57446ff98 100644 --- a/docs/css/default.css +++ b/docs/css/default.css @@ -88,6 +88,10 @@ pre { font-weight: bold; } +.nav-list a { + overflow: hidden; +} + /* Set the table of contents to static so it flows back into the content when viewed on tablets and smaller. */ @media (max-width: 767px) { diff --git a/docs/index.md b/docs/index.md index b3845521d..75a1cf6e6 100644 --- a/docs/index.md +++ b/docs/index.md @@ -5,12 +5,24 @@ **A toolkit for building well-connected, self-describing Web APIs.** -**WARNING: This documentation is for the 2.0 redesign of REST framework. It is a work in progress.** +--- + +**Note**: This documentation is for the 2.0 version of REST framework. If you are looking for earlier versions please see the [0.4.x branch][0.4] on GitHub. + +--- Django REST framework is a lightweight library that makes it easy to build Web APIs. It is designed as a modular and easy to customize architecture, based on Django's class based views. Web APIs built using REST framework are fully self-describing and web browseable - a huge useability win for your developers. It also supports a wide range of media types, authentication and permission policies out of the box. +If you are considering using REST framework for your API, we recommend reading the [REST framework 2 announcment][rest-framework-2-announcement] which gives a good overview of the framework and it's capabilities. + +There is also a sandbox API you can use for testing purposes, [available here][sandbox]. + +**Below**: *Screenshot from the browseable API* + +![Screenshot][image] + ## Requirements REST framework requires the following: @@ -25,8 +37,6 @@ The following packages are optional: ## Installation -**WARNING: These instructions will only become valid once this becomes the master version** - Install using `pip`, including any optional packages you want... pip install djangorestframework @@ -47,7 +57,7 @@ Add `rest_framework` to your `INSTALLED_APPS`. 'rest_framework', ) -If you're intending to use the browserable API you'll want to add REST framework's login and logout views. Add the following to your root `urls.py` file. +If you're intending to use the browseable API you'll want to add REST framework's login and logout views. Add the following to your root `urls.py` file. urlpatterns = patterns('', ... @@ -56,9 +66,11 @@ If you're intending to use the browserable API you'll want to add REST framework Note that the URL path can be whatever you want, but you must include `rest_framework.urls` with the `rest_framework` namespace. + ## Tutorial @@ -67,9 +79,8 @@ The tutorial will walk you through the building blocks that make up REST framewo * [1 - Serialization][tut-1] * [2 - Requests & Responses][tut-2] * [3 - Class based views][tut-3] -* [4 - Authentication, permissions & throttling][tut-4] +* [4 - Authentication & permissions][tut-4] * [5 - Relationships & hyperlinked APIs][tut-5] - ## API Guide @@ -98,13 +109,11 @@ The API guide is your complete reference manual to all the functionality provide General guides to using REST framework. -* [CSRF][csrf] -* [Browser hacks][browserhacks] -* [Working with the Browsable API][browsableapi] +* [Browser enhancements][browser-enhancements] +* [The Browsable API][browsableapi] * [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas] -* [Contributing to REST framework][contributing] -* [2.0 Migration Guide][migration] -* [Change Log][changelog] +* [2.0 Announcement][rest-framework-2-announcement] +* [Release Notes][release-notes] * [Credits][credits] ## Development @@ -119,7 +128,6 @@ Run the tests: ./rest_framework/runtests/runtests.py -For more information see the [Contributing to REST framework][contributing] section. ## Support For support please see the [REST framework discussion group][group], or try the `#restframework` channel on `irc.freenode.net`. @@ -151,19 +159,21 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -[travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=restframework2 +[travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master [travis-build-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=restframework2 [urlobject]: https://github.com/zacharyvoase/urlobject [markdown]: http://pypi.python.org/pypi/Markdown/ [yaml]: http://pypi.python.org/pypi/PyYAML +[0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X +[image]: img/quickstart.png +[sandbox]: http://restframework.herokuapp.com/ [quickstart]: tutorial/quickstart.md [tut-1]: tutorial/1-serialization.md [tut-2]: tutorial/2-requests-and-responses.md [tut-3]: tutorial/3-class-based-views.md -[tut-4]: tutorial/4-authentication-permissions-and-throttling.md +[tut-4]: tutorial/4-authentication-and-permissions.md [tut-5]: tutorial/5-relationships-and-hyperlinked-apis.md -[tut-6]: tutorial/6-resource-orientated-projects.md [request]: api-guide/requests.md [response]: api-guide/responses.md @@ -185,14 +195,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [settings]: api-guide/settings.md [csrf]: topics/csrf.md -[browserhacks]: topics/browserhacks.md +[browser-enhancements]: topics/browser-enhancements.md [browsableapi]: topics/browsable-api.md [rest-hypermedia-hateoas]: topics/rest-hypermedia-hateoas.md [contributing]: topics/contributing.md -[migration]: topics/migration.md -[changelog]: topics/changelog.md +[rest-framework-2-announcement]: topics/rest-framework-2-announcement.md +[release-notes]: topics/release-notes.md [credits]: topics/credits.md [group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework [DabApps]: http://dabapps.com -[email]: mailto:tom@tomchristie.com \ No newline at end of file +[email]: mailto:tom@tomchristie.com diff --git a/docs/template.html b/docs/template.html index 016de151a..94fc269f4 100644 --- a/docs/template.html +++ b/docs/template.html @@ -1,5 +1,6 @@ - + + Django REST framework @@ -17,6 +18,21 @@ + + +
@@ -24,7 +40,7 @@