Line wrap docs to 80 chars where possible

This commit is contained in:
Luke Murphy 2016-09-08 15:27:00 +02:00
parent 5df54a711f
commit 0c67b908b4
60 changed files with 5679 additions and 2044 deletions

View File

@ -1,196 +1,280 @@
# Contributing to REST framework
> The world can only really be changed one piece at a time. The art is picking that piece.
> The world can only really be changed one piece at a time. The art is picking
> that piece.
>
> — [Tim Berners-Lee][cite]
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
There are many ways you can contribute to Django REST framework. We'd like it
to be a community-led project, so please get involved and help shape the future
of the project.
## Community
The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
The most important thing you can do to help push the REST framework project
forward is to be actively involved wherever possible. Code contributions are
often overvalued as being the primary way to get involved in a project, we
don't believe that needs to be the case.
If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with.
If you use REST framework, we'd love you to be vocal about your experiences
with it - you might consider writing a blog post about using REST framework, or
publishing a tutorial about building a project with a particular JavaScript
framework. Experiences from beginners can be particularly helpful because
you'll be in the best position to assess which bits of REST framework are more
difficult to understand and work with.
Other really great ways you can help move the community forward include helping to answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag.
Other really great ways you can help move the community forward include helping
to answer questions on the [discussion group][google-group], or setting up an
[email alert on StackOverflow][so-filter] so that you get notified of any new
questions with the `django-rest-framework` tag.
When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.
When answering questions make sure to help future contributors find their way
around by hyperlinking wherever possible to related threads and tickets, and
include backlinks from those items if relevant.
## Code of conduct
Please keep the tone polite & professional. For some users a discussion on the REST framework mailing list or ticket tracker may be their first engagement with the open source community. First impressions count, so let's try to make everyone feel welcome.
Please keep the tone polite & professional. For some users a discussion on the
REST framework mailing list or ticket tracker may be their first engagement
with the open source community. First impressions count, so let's try to make
everyone feel welcome.
Be mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations.
Be mindful in the language you choose. As an example, in an environment that
is heavily male-dominated, posts that start 'Hey guys,' can come across as
unintentionally exclusive. It's just as easy, and more inclusive to use gender
neutral language in those situations.
The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines for participating in community forums.
The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines
for participating in community forums.
# Issues
It's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the [discussion group][google-group]. Feature requests, bug reports and other issues should be raised on the GitHub [issue tracker][issues].
It's really helpful if you can make sure to address issues on the correct
channel. Usage questions should be directed to the [discussion
group][google-group]. Feature requests, bug reports and other issues should be
raised on the GitHub [issue tracker][issues].
Some tips on good issue reporting:
* When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
* Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bug fixes, and great documentation.
* Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.
* When describing issues try to phrase your ticket in terms of the *behavior*
you think needs changing rather than the *code* you think need changing.
* Search the issue list first for related items, and make sure you're running
the latest version of REST framework before reporting an issue.
* If reporting a bug, then try to include a pull request with a failing test
case. This will help us quickly identify if there is a valid issue, and make
sure that it gets fixed more quickly if there is one.
* Feature requests will often be closed with a recommendation that they be
implemented outside of the core REST framework library. Keeping new feature
requests implemented as third party libraries allows us to keep down the
maintenance overhead of REST framework, so that the focus can be on continued
stability, bug fixes, and great documentation.
* Closing an issue doesn't necessarily mean the end of a discussion. If you
believe your issue has been closed incorrectly, explain why and we'll
consider if it needs to be reopened.
## Triaging issues
Getting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to:
Getting involved in triaging incoming issues is a good way to start
contributing. Every single ticket that comes into the ticket tracker needs to
be reviewed in order to determine what the next steps should be. Anyone can
help out with this, you just need to be willing to:
* Read through the ticket - does it make sense, is it missing any context that would help explain it better?
* Is the ticket reported in the correct place, would it be better suited as a discussion on the discussion group?
* If the ticket is a bug report, can you reproduce it? Are you able to write a failing test case that demonstrates the issue and that can be submitted as a pull request?
* If the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package?
* If a ticket hasn't had much activity and it addresses something you need, then comment on the ticket and try to find out what's needed to get it moving again.
* Read through the ticket - does it make sense, is it missing any context that
would help explain it better?
* Is the ticket reported in the correct place, would it be better suited as a
discussion on the discussion group?
* If the ticket is a bug report, can you reproduce it? Are you able to write a
failing test case that demonstrates the issue and that can be submitted as a
pull request?
* If the ticket is a feature request, do you agree with it, and could the
feature request instead be implemented as a third party package?
* If a ticket hasn't had much activity and it addresses something you need,
then comment on the ticket and try to find out what's needed to get it moving
again.
# Development
To start developing on Django REST framework, clone the repo:
git clone git@github.com:tomchristie/django-rest-framework.git
git clone git@github.com:tomchristie/django-rest-framework.git
Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.
Changes should broadly follow the [PEP 8][pep-8] style conventions, and we
recommend you set up your editor to automatically indicate non-conforming
styles.
## Testing
To run the tests, clone the repository, and then:
# Setup the virtual environment
virtualenv env
source env/bin/activate
pip install -r requirements.txt
# Setup the virtual environment virtualenv env source env/bin/activate pip
install -r requirements.txt
# Run the tests
./runtests.py
# Run the tests ./runtests.py
### Test options
Run using a more concise output style.
./runtests.py -q
./runtests.py -q
Run the tests using a more concise output style, no coverage, no flake8.
./runtests.py --fast
./runtests.py --fast
Don't run the flake8 code linting.
./runtests.py --nolint
./runtests.py --nolint
Only run the flake8 code linting, don't run the tests.
./runtests.py --lintonly
./runtests.py --lintonly
Run the tests for a given test case.
./runtests.py MyTestCase
./runtests.py MyTestCase
Run the tests for a given test method.
./runtests.py MyTestCase.test_this_method
./runtests.py MyTestCase.test_this_method
Shorter form to run the tests for a given test method.
./runtests.py test_this_method
./runtests.py test_this_method
Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.
Note: The test case and test method matching is fuzzy and will sometimes run
other tests that contain a partial string match to the given command line
input.
### Running against multiple environments
You can also use the excellent [tox][tox] testing tool to run the tests against all supported versions of Python and Django. Install `tox` globally, and then simply run:
You can also use the excellent [tox][tox] testing tool to run the tests against
all supported versions of Python and Django. Install `tox` globally, and then
simply run:
tox
tox
## Pull requests
It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.
It's a good idea to make pull requests early on. A pull request represents the
start of a discussion, and doesn't necessarily need to be the final, finished
submission.
It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests.
It's also always best to make a new branch before starting work on a pull
request. This means that you'll be able to later switch back to working on
another separate issue without interfering with an ongoing pull requests.
It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests.
It's also useful to remember that if you have an outstanding pull request then
pushing new commits to your GitHub repo will also automatically update the pull
requests.
GitHub's documentation for working on pull requests is [available here][pull-requests].
GitHub's documentation for working on pull requests is [available
here][pull-requests].
Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django.
Always run the tests before submitting pull requests, and ideally run `tox` in
order to check that your modifications are compatible with both Python 2 and
Python 3, and that they run properly on all supported versions of Django.
Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect.
Once you've made a pull request take a look at the Travis build status in the
GitHub interface and make sure the tests are running as you'd expect.
## Managing compatibility issues
Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the `compat.py` module, and should provide a single common interface that the rest of the codebase can use.
Sometimes, in order to ensure your code works on various different versions of
Django, Python or third party libraries, you'll need to run slightly different
code depending on the environment. Any code that branches in this way should
be isolated into the `compat.py` module, and should provide a single common
interface that the rest of the codebase can use.
# Documentation
The documentation for REST framework is built from the [Markdown][markdown] source files in [the docs directory][docs].
The documentation for REST framework is built from the [Markdown][markdown]
source files in [the docs directory][docs].
There are many great Markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended.
There are many great Markdown editors that make working with the documentation
really easy. The [Mou editor for Mac][mou] is one such editor that comes
highly recommended.
## Building the documentation
To build the documentation, install MkDocs with `pip install mkdocs` and then run the following command.
To build the documentation, install MkDocs with `pip install mkdocs` and then
run the following command.
mkdocs build
mkdocs build
This will build the documentation into the `site` directory.
You can build the documentation and open a preview in a browser window by using the `serve` command.
You can build the documentation and open a preview in a browser window by using
the `serve` command.
mkdocs serve
mkdocs serve
## Language style
Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible.
Documentation should be in American English. The tone of the documentation is
very important - try to stick to a simple, plain, objective and well-balanced
style where possible.
Some other tips:
* Keep paragraphs reasonably short.
* Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.
* Don't use abbreviations such as 'e.g.' but instead use
the long form, such as 'For example'.
## Markdown style
There are a couple of conventions you should follow when working on the documentation.
There are a couple of conventions you should follow when working on the
documentation.
##### 1. Headers
Headers should use the hash style. For example:
Headers should use the hash style. For example:
### Some important topic
### Some important topic
The underline style should not be used. **Don't do this:**
The underline style should not be used. **Don't do this:**
Some important topic
====================
Some important topic ====================
##### 2. Links
Links should always use the reference style, with the referenced hyperlinks kept at the end of the document.
Links should always use the reference style, with the referenced hyperlinks
kept at the end of the document.
Here is a link to [some other thing][other-thing].
Here is a link to [some other thing][other-thing].
More text...
More text...
[other-thing]: http://example.com/other/thing
[other-thing]: http://example.com/other/thing
This style helps keep the documentation source consistent and readable.
If you are hyperlinking to another REST framework document, you should use a relative link, and link to the `.md` suffix. For example:
If you are hyperlinking to another REST framework document, you should use a
relative link, and link to the `.md` suffix. For example:
[authentication]: ../api-guide/authentication.md
[authentication]: ../api-guide/authentication.md
Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.
Linking in this style means you'll be able to click the hyperlink in your
Markdown editor to open the referenced document. When the documentation is
built, these links will be converted into regular links to HTML pages.
##### 3. Notes
If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:
If you want to draw attention to a note or warning, use a pair of enclosing
lines, like so:
---
---
**Note:** A useful documentation note.
**Note:** A useful documentation note.
---
---
[cite]: http://www.w3.org/People/Berners-Lee/FAQ.html

View File

@ -6,31 +6,50 @@ source: authentication.py
>
> — Jacob Kaplan-Moss, ["REST worst practices"][cite]
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted.
Authentication is the mechanism of associating an incoming request with a set
of identifying credentials, such as the user the request came from, or the
token that it was signed with. The [permission] and [throttling] policies can
then use those credentials to determine if the request should be permitted.
REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.
REST framework provides a number of authentication schemes out of the box, and
also allows you to implement custom schemes.
Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.
Authentication is always run at the very start of the view, before the
permission and throttling checks occur, and before any other code is allowed to
proceed.
The `request.user` property will typically be set to an instance of the `contrib.auth` package's `User` class.
The `request.user` property will typically be set to an instance of the
`contrib.auth` package's `User` class.
The `request.auth` property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.
The `request.auth` property is used for any additional authentication
information, for example, it may be used to represent an authentication token
that the request was signed with.
---
**Note:** Don't forget that **authentication by itself won't allow or disallow an incoming request**, it simply identifies the credentials that the request was made with.
**Note:** Don't forget that **authentication by itself won't allow or disallow
an incoming request**, it simply identifies the credentials that the request
was made with.
For information on how to setup the permission polices for your API please see the [permissions documentation][permission].
For information on how to setup the permission polices for your API please see
the [permissions documentation][permission].
---
## How authentication is determined
The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set `request.user` and `request.auth` using the return value of the first class that successfully authenticates.
The authentication schemes are always defined as a list of classes. REST
framework will attempt to authenticate with each class in the list, and will
set `request.user` and `request.auth` using the return value of the first class
that successfully authenticates.
If no class authenticates, `request.user` will be set to an instance of `django.contrib.auth.models.AnonymousUser`, and `request.auth` will be set to `None`.
If no class authenticates, `request.user` will be set to an instance of
`django.contrib.auth.models.AnonymousUser`, and `request.auth` will be set to
`None`.
The value of `request.user` and `request.auth` for unauthenticated requests can be modified using the `UNAUTHENTICATED_USER` and `UNAUTHENTICATED_TOKEN` settings.
The value of `request.user` and `request.auth` for unauthenticated requests can
be modified using the `UNAUTHENTICATED_USER` and `UNAUTHENTICATED_TOKEN`
settings.
## Setting the authentication scheme
@ -76,22 +95,37 @@ Or, if you're using the `@api_view` decorator with function based views.
## Unauthorized and Forbidden responses
When an unauthenticated request is denied permission there are two different error codes that may be appropriate.
When an unauthenticated request is denied permission there are two different
error codes that may be appropriate.
* [HTTP 401 Unauthorized][http401]
* [HTTP 403 Permission Denied][http403]
HTTP 401 responses must always include a `WWW-Authenticate` header, that instructs the client how to authenticate. HTTP 403 responses do not include the `WWW-Authenticate` header.
HTTP 401 responses must always include a `WWW-Authenticate` header, that
instructs the client how to authenticate. HTTP 403 responses do not include
the `WWW-Authenticate` header.
The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. **The first authentication class set on the view is used when determining the type of response**.
The kind of response that will be used depends on the authentication scheme.
Although multiple authentication schemes may be in use, only one scheme may be
used to determine the type of response. **The first authentication class set
on the view is used when determining the type of response**.
Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a `403 Permission Denied` response will always be used, regardless of the authentication scheme.
Note that when a request may successfully authenticate, but still be denied
permission to perform the request, in which case a `403 Permission Denied`
response will always be used, regardless of the authentication scheme.
## Apache mod_wsgi specific configuration
Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.
Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the
authorization header is not passed through to a WSGI application by default, as
it is assumed that authentication will be handled by Apache, rather than at an
application level.
If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the `WSGIPassAuthorization` directive in the appropriate context and setting it to `'On'`.
If you are deploying to Apache, and using any non-session based authentication,
you will need to explicitly configure mod_wsgi to pass the required headers
through to the application. This can be done by specifying the
`WSGIPassAuthorization` directive in the appropriate context and setting it to
`'On'`.
# this can go in either server config, virtual host, directory or .htaccess
WSGIPassAuthorization On
@ -102,24 +136,37 @@ If you are deploying to Apache, and using any non-session based authentication,
## BasicAuthentication
This authentication scheme uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
This authentication scheme uses [HTTP Basic Authentication][basicauth], signed
against a user's username and password. Basic authentication is generally only
appropriate for testing.
If successfully authenticated, `BasicAuthentication` provides the following credentials.
If successfully authenticated, `BasicAuthentication` provides the following
credentials.
* `request.user` will be a Django `User` instance.
* `request.auth` will be `None`.
Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
Unauthenticated responses that are denied permission will result in an `HTTP
401 Unauthorized` response with an appropriate WWW-Authenticate header. For
example:
WWW-Authenticate: Basic realm="api"
**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https`. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
**Note:** If you use `BasicAuthentication` in production you must ensure that
your API is only available over `https`. You should also ensure that your API
clients will always re-request the username and password at login, and will
never store those details to persistent storage.
## TokenAuthentication
This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
This authentication scheme uses a simple token-based HTTP Authentication
scheme. Token authentication is appropriate for client-server setups, such as
native desktop and mobile clients.
To use the `TokenAuthentication` scheme you'll need to [configure the authentication classes](#setting-the-authentication-scheme) to include `TokenAuthentication`, and additionally include `rest_framework.authtoken` in your `INSTALLED_APPS` setting:
To use the `TokenAuthentication` scheme you'll need to [configure the
authentication classes](#setting-the-authentication-scheme) to include
`TokenAuthentication`, and additionally include `rest_framework.authtoken` in
your `INSTALLED_APPS` setting:
INSTALLED_APPS = (
...
@ -128,7 +175,8 @@ To use the `TokenAuthentication` scheme you'll need to [configure the authentica
---
**Note:** Make sure to run `manage.py migrate` after changing your settings. The `rest_framework.authtoken` app provides Django database migrations.
**Note:** Make sure to run `manage.py migrate` after changing your settings.
The `rest_framework.authtoken` app provides Django database migrations.
---
@ -139,28 +187,37 @@ 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 separating 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
**Note:** If you want to use a different keyword in the header, such as `Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class variable.
**Note:** If you want to use a different keyword in the header, such as
`Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class
variable.
If successfully authenticated, `TokenAuthentication` provides the following credentials.
If successfully authenticated, `TokenAuthentication` provides the following
credentials.
* `request.user` will be a Django `User` instance.
* `request.auth` will be a `rest_framework.authtoken.models.BasicToken` instance.
Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
Unauthenticated responses that are denied permission will result in an `HTTP
401 Unauthorized` response with an appropriate WWW-Authenticate header. For
example:
WWW-Authenticate: Token
The `curl` command line tool may be useful for testing token authenticated APIs. For example:
The `curl` command line tool may be useful for testing token authenticated
APIs. For example:
curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
---
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https`.
**Note:** If you use `TokenAuthentication` in production you must ensure that
your API is only available over `https`.
---
@ -168,7 +225,8 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
##### By using signals
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
If you want every user to have an automatically generated Token, you can simply
catch the User's `post_save` signal.
from django.conf import settings
from django.db.models.signals import post_save
@ -180,9 +238,12 @@ If you want every user to have an automatically generated Token, you can simply
if created:
Token.objects.create(user=instance)
Note that you'll want to ensure you place this code snippet in an installed `models.py` module, or some other location that will be imported by Django on startup.
Note that you'll want to ensure you place this code snippet in an installed
`models.py` module, or some other location that will be imported by Django on
startup.
If you've already created some users, you can generate tokens for all existing users like this:
If you've already created some users, you can generate tokens for all existing
users like this:
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
@ -192,7 +253,10 @@ If you've already created some users, you can generate tokens for all existing u
##### By exposing an api endpoint
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
When using `TokenAuthentication`, you may want to provide a mechanism for
clients to obtain a token given the username and password. REST framework
provides a built-in view to provide this behavior. To use it, add the
`obtain_auth_token` view to your URLconf:
from rest_framework.authtoken import views
urlpatterns += [
@ -201,19 +265,29 @@ When using `TokenAuthentication`, you may want to provide a mechanism for client
Note that the URL part of the pattern can be whatever you want to use.
The `obtain_auth_token` view will return a JSON response when valid `username` and `password` fields are POSTed to the view using form data or JSON:
The `obtain_auth_token` view will return a JSON response when valid `username`
and `password` fields are POSTed to the view using form data or JSON:
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the `obtain_auth_token` view, you can do so by overriding the `ObtainAuthToken` view class, and using that in your url conf instead.
Note that the default `obtain_auth_token` view explicitly uses JSON requests
and responses, rather than using default renderer and parser classes in your
settings. If you need a customized version of the `obtain_auth_token` view,
you can do so by overriding the `ObtainAuthToken` view class, and using that in
your url conf instead.
By default there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
and include them using the `throttle_classes` attribute.
By default there are no permissions or throttling applied to the
`obtain_auth_token` view. If you do wish to apply throttling you'll need to
override the view class, and include them using the `throttle_classes`
attribute.
##### With Django admin
It is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
It is also possible to create Tokens manually through admin interface. In case
you are using a large user base, we recommend that you monkey patch the
`TokenAdmin` class to customize it to your needs, more specifically by
declaring the `user` field as `raw_field`.
`your_app/admin.py`:
@ -224,35 +298,57 @@ It is also possible to create Tokens manually through admin interface. In case y
## SessionAuthentication
This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
This authentication scheme uses Django's default session backend for
authentication. Session authentication is appropriate for AJAX clients that
are running in the same session context as your website.
If successfully authenticated, `SessionAuthentication` provides the following credentials.
* `request.user` will be a Django `User` instance.
* `request.auth` will be `None`.
Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response.
Unauthenticated responses that are denied permission will result in an `HTTP
403 Forbidden` response.
If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
If you're using an AJAX style API with SessionAuthentication, you'll need to
make sure you include a valid CSRF token for any "unsafe" HTTP method calls,
such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF
documentation][csrf-ajax] for more details.
**Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
**Warning**: Always use Django's standard login view when creating login pages.
This will ensure your login views are properly protected.
CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.
CSRF validation in REST framework works slightly differently to standard Django
due to the need to support both session and non-session based authentication to
the same views. This means that only authenticated requests require CSRF
tokens, and anonymous requests may be sent without CSRF tokens. This behaviour
is not suitable for login views, which should always have CSRF validation
applied.
# Custom authentication
To implement a custom authentication scheme, 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.
To implement a custom authentication scheme, 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.
In some circumstances instead of returning `None`, you may want to raise an `AuthenticationFailed` exception from the `.authenticate()` method.
In some circumstances instead of returning `None`, you may want to raise an
`AuthenticationFailed` exception from the `.authenticate()` method.
Typically the approach you should take is:
* If authentication is not attempted, return `None`. Any other authentication schemes also in use will still be checked.
* If authentication is attempted but fails, raise a `AuthenticationFailed` exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.
* If authentication is not attempted, return `None`. Any other authentication
schemes also in use will still be checked.
* If authentication is attempted but fails, raise a `AuthenticationFailed`
exception. An error response will be returned immediately, regardless of any
permissions checks, and without checking any other authentication schemes.
You *may* also override the `.authenticate_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response.
You *may* also override the `.authenticate_header(self, request)` method. If
implemented, it should return a string that will be used as the value of the
`WWW-Authenticate` header in a `HTTP 401 Unauthorized` response.
If the `.authenticate_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access.
If the `.authenticate_header()` method is not overridden, the authentication
scheme will return `HTTP 403 Forbidden` responses when an unauthenticated
request is denied access.
## Example
@ -283,7 +379,11 @@ The following third party packages are also available.
## Django OAuth Toolkit
The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by [Evonove][evonove] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.
The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0
support, and works with Python 2.7 and Python 3.3+. The package is maintained
by [Evonove][evonove] and uses the excellent [OAuthLib][oauthlib]. The package
is well documented, and well supported and is currently our **recommended
package for OAuth 2.0 support**.
#### Installation & configuration
@ -308,9 +408,11 @@ For more details see the [Django REST framework - Getting started][django-oauth-
## Django REST framework OAuth
The [Django REST framework OAuth][django-rest-framework-oauth] package provides both OAuth1 and OAuth2 support for REST framework.
The [Django REST framework OAuth][django-rest-framework-oauth] package provides
both OAuth1 and OAuth2 support for REST framework.
This package was previously included directly in REST framework but is now supported and maintained as a third party package.
This package was previously included directly in REST framework but is now
supported and maintained as a third party package.
#### Installation & configuration
@ -318,43 +420,86 @@ Install the package using `pip`.
pip install djangorestframework-oauth
For details on configuration and usage see the Django REST framework OAuth documentation for [authentication][django-rest-framework-oauth-authentication] and [permissions][django-rest-framework-oauth-permissions].
For details on configuration and usage see the Django REST framework OAuth
documentation for [authentication][django-rest-framework-oauth-authentication]
and [permissions][django-rest-framework-oauth-permissions].
## Digest Authentication
HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. [Juan Riaza][juanriaza] maintains the [djangorestframework-digestauth][djangorestframework-digestauth] package which provides HTTP digest authentication support for REST framework.
HTTP digest authentication is a widely implemented scheme that was intended to
replace HTTP basic authentication, and which provides a simple encrypted
authentication mechanism. [Juan Riaza][juanriaza] maintains the
[djangorestframework-digestauth][djangorestframework-digestauth] package which
provides HTTP digest authentication support for REST framework.
## Django OAuth2 Consumer
The [Django OAuth2 Consumer][doac] library from [Rediker Software][rediker] is another package that provides [OAuth 2.0 support for REST framework][doac-rest-framework]. The package includes token scoping permissions on tokens, which allows finer-grained access to your API.
The [Django OAuth2 Consumer][doac] library from [Rediker Software][rediker] is
another package that provides [OAuth 2.0 support for REST
framework][doac-rest-framework]. The package includes token scoping
permissions on tokens, which allows finer-grained access to your API.
## JSON Web Token Authentication
JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. [Blimp][blimp] maintains the [djangorestframework-jwt][djangorestframework-jwt] package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password.
JSON Web Token is a fairly new standard which can be used for token-based
authentication. Unlike the built-in TokenAuthentication scheme, JWT
Authentication doesn't need to use a database to validate a token.
[Blimp][blimp] maintains the [djangorestframework-jwt][djangorestframework-jwt]
package which provides a JWT Authentication class as well as a mechanism for
clients to obtain a JWT given the username and password.
## Hawk HTTP Authentication
The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let you work with [Hawk][hawk] signed requests and responses in your API. [Hawk][hawk] lets two parties securely communicate with each other using messages signed by a shared key. It is based on [HTTP MAC access authentication][mac] (which was based on parts of [OAuth 1.0][oauth-1.0a]).
The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let
you work with [Hawk][hawk] signed requests and responses in your API.
[Hawk][hawk] lets two parties securely communicate with each other using
messages signed by a shared key. It is based on [HTTP MAC access
authentication][mac] (which was based on parts of [OAuth 1.0][oauth-1.0a]).
## HTTP Signature Authentication
HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] package which provides an easy to use HTTP Signature Authentication mechanism.
HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
way to achieve origin authentication and message integrity for HTTP messages.
Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by
many of its services, it permits stateless, per-request authentication. [Elvio
Toccalino][etoccalino] maintains the
[djangorestframework-httpsignature][djangorestframework-httpsignature] package
which provides an easy to use HTTP Signature Authentication mechanism.
## Djoser
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.
[Djoser][djoser] library provides a set of views to handle basic actions such
as registration, login, logout, password reset and account activation. The
package works with a custom user model and it uses token based authentication.
This is a ready to use REST implementation of Django authentication system.
## django-rest-auth
[Django-rest-auth][django-rest-auth] library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.
[Django-rest-auth][django-rest-auth] library provides a set of REST API
endpoints for registration, authentication (including social media
authentication), password reset, retrieve and update user details, etc. By
having these API endpoints, your client apps such as AngularJS, iOS, Android,
and others can communicate to your Django backend site independently via REST
APIs for user management.
## django-rest-framework-social-oauth2
[Django-rest-framework-social-oauth2][django-rest-framework-social-oauth2] library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to "in-house" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.
[Django-rest-framework-social-oauth2][django-rest-framework-social-oauth2]
library provides an easy way to integrate social plugins (facebook, twitter,
google, etc.) to your authentication system and an easy oauth2 setup. With this
library, you will be able to authenticate users based on external tokens (e.g.
facebook access token), convert these tokens to "in-house" oauth2 tokens and
use and generate oauth2 tokens to authenticate your users.
## django-rest-knox
[Django-rest-knox][django-rest-knox] library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).
[Django-rest-knox][django-rest-knox] library provides models and views to
handle token based authentication in a more secure and extensible way than the
built-in TokenAuthentication scheme - with Single Page Applications and Mobile
clients in mind. It provides per-client tokens, and views to generate them when
provided some other authentication (usually basic authentication), to delete
the token (providing a server enforced logout) and to delete all tokens (logs
out all clients that a user is logged into).
[cite]: http://jacobian.org/writing/rest-worst-practices/
[http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2

View File

@ -2,20 +2,27 @@ source: negotiation.py
# Content negotiation
> HTTP has provisions for several mechanisms for "content negotiation" - the process of selecting the best representation for a given response when there are multiple representations available.
> HTTP has provisions for several mechanisms for "content negotiation" - the
> process of selecting the best representation for a given response when there
> are multiple representations available.
>
> — [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.
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.
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.
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:
@ -27,27 +34,41 @@ The priorities for each of the given media types would be:
* `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.
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.
**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.
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`.
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.
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.
The `select_parser()` method should return one of the parser instances from the list of available parsers, or `None` if none of the parsers can handle the incoming request.
The `select_parser()` method should return one of the parser instances from the
list of available parsers, or `None` if none of the parsers can handle the
incoming request.
The `select_renderer()` method should return a two-tuple of (renderer instance, media type), or raise a `NotAcceptable` exception.
The `select_renderer()` method should return a two-tuple of (renderer instance,
media type), or raise a `NotAcceptable` exception.
## Example
@ -71,13 +92,16 @@ request when selecting the appropriate parser or renderer.
## Setting the content negotiation
The default content negotiation class may be set globally, using the `DEFAULT_CONTENT_NEGOTIATION_CLASS` setting. For example, the following settings would use our example `IgnoreClientContentNegotiation` class.
The default content negotiation class may be set globally, using the
`DEFAULT_CONTENT_NEGOTIATION_CLASS` setting. For example, the following
settings would use our example `IgnoreClientContentNegotiation` class.
REST_FRAMEWORK = {
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation',
}
You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class-based views.
You can also set the content negotiation used for an individual view, or
viewset, using the `APIView` class-based views.
from myapp.negotiation import IgnoreClientContentNegotiation
from rest_framework.response import Response

View File

@ -2,13 +2,15 @@ source: exceptions.py
# Exceptions
> Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.
> Exceptions… allow error handling to be organized cleanly in a central or
> high-level place within the program structure.
>
> — Doug Hellmann, [Python Exception Handling Techniques][cite]
## Exception handling in REST framework views
REST framework's views handle various exceptions, and deal with returning appropriate error responses.
REST framework's views handle various exceptions, and deal with returning
appropriate error responses.
The handled exceptions are:
@ -16,7 +18,9 @@ The handled exceptions are:
* Django's `Http404` exception.
* Django's `PermissionDenied` exception.
In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error.
In each case, REST framework will return a response with an appropriate status
code and content-type. The body of the response will include any additional
details regarding the nature of the error.
Most error responses will include a key `detail` in the body of the response.
@ -25,7 +29,8 @@ For example, the following request:
DELETE http://api.example.com/foo/bar HTTP/1.1
Accept: application/json
Might receive 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
@ -33,7 +38,10 @@ Might receive an error response indicating that the `DELETE` method is not allow
{"detail": "Method 'DELETE' not allowed."}
Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the "non_field_errors" key, or whatever string value has been set for the `NON_FIELD_ERRORS_KEY` setting.
Validation errors are handled slightly differently, and will include the field
names as the keys in the response. If the validation error was not specific to
a particular field then it will use the "non_field_errors" key, or whatever
string value has been set for the `NON_FIELD_ERRORS_KEY` setting.
Any example validation error might look like this:
@ -45,11 +53,19 @@ Any example validation error might look like this:
## Custom exception handling
You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.
You can implement custom exception handling by creating a handler function that
converts exceptions raised in your API views into response objects. This
allows you to control the style of error responses used by your API.
The function must take a pair of arguments, this first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a `Response` object, or return `None` if the exception cannot be handled. If the handler returns `None` then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.
The function must take a pair of arguments, this first is the exception to be
handled, and the second is a dictionary containing any extra context such as
the view currently being handled. The exception handler function should either
return a `Response` object, or return `None` if the exception cannot be
handled. If the handler returns `None` then the exception will be re-raised
and Django will return a standard HTTP 500 'server error' response.
For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:
For example, you might want to ensure that all error responses include the HTTP
status code in the body of the response, like so:
HTTP/1.1 405 Method Not Allowed
Content-Type: application/json
@ -57,7 +73,8 @@ For example, you might want to ensure that all error responses include the HTTP
{"status_code": 405, "detail": "Method 'DELETE' not allowed."}
In order to alter the style of the response, you could write the following custom exception handler:
In order to alter the style of the response, you could write the following
custom exception handler:
from rest_framework.views import exception_handler
@ -72,21 +89,28 @@ In order to alter the style of the response, you could write the following custo
return response
The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as `context['view']`.
The context argument is not used by the default handler, but can be useful if
the exception handler needs further information such as the view currently
being handled, which can be accessed as `context['view']`.
The exception handler must also be configured in your settings, using the `EXCEPTION_HANDLER` setting key. For example:
The exception handler must also be configured in your settings, using the
`EXCEPTION_HANDLER` setting key. For example:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
If not specified, the `'EXCEPTION_HANDLER'` setting defaults to the standard exception handler provided by REST framework:
If not specified, the `'EXCEPTION_HANDLER'` setting defaults to the standard
exception handler provided by REST framework:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}
Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the `HTTP_400_BAD_REQUEST` responses that are returned by the generic views when serializer validation fails.
Note that the exception handler will only be called for responses generated by
raised exceptions. It will not be used for any responses returned directly by
the view, such as the `HTTP_400_BAD_REQUEST` responses that are returned by the
generic views when serializer validation fails.
---
@ -96,11 +120,15 @@ Note that the exception handler will only be called for responses generated by r
**Signature:** `APIException()`
The **base class** for all exceptions raised inside an `APIView` class or `@api_view`.
The **base class** for all exceptions raised inside an `APIView` class or
`@api_view`.
To provide a custom exception, subclass `APIException` and set the `.status_code` and `.default_detail` properties on the class.
To provide a custom exception, subclass `APIException` and set the
`.status_code` and `.default_detail` properties on the class.
For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so:
For example, if your API relies on a third party service that may sometimes be
unreachable, you might want to implement an exception for the "503 Service
Unavailable" HTTP response code. You could do this like so:
from rest_framework.exceptions import APIException
@ -114,7 +142,8 @@ For example, if your API relies on a third party service that may sometimes be u
Raised if the request contains malformed data when accessing `request.data`.
By default this exception results in a response with the HTTP status code "400 Bad Request".
By default this exception results in a response with the HTTP status code "400
Bad Request".
## AuthenticationFailed
@ -122,7 +151,10 @@ By default this exception results in a response with the HTTP status code "400 B
Raised when an incoming request includes incorrect authentication.
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
By default this exception results in a response with the HTTP status code "401
Unauthenticated", but it may also result in a "403 Forbidden" response,
depending on the authentication scheme in use. See the [authentication
documentation][authentication] for more details.
## NotAuthenticated
@ -130,7 +162,10 @@ By default this exception results in a response with the HTTP status code "401 U
Raised when an unauthenticated request fails the permission checks.
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
By default this exception results in a response with the HTTP status code "401
Unauthenticated", but it may also result in a "403 Forbidden" response,
depending on the authentication scheme in use. See the [authentication
documentation][authentication] for more details.
## PermissionDenied
@ -138,15 +173,18 @@ By default this exception results in a response with the HTTP status code "401 U
Raised when an authenticated request fails the permission checks.
By default this exception results in a response with the HTTP status code "403 Forbidden".
By default this exception results in a response with the HTTP status code "403
Forbidden".
## NotFound
**Signature:** `NotFound(detail=None)`
Raised when a resource does not exists at the given URL. This exception is equivalent to the standard `Http404` Django exception.
Raised when a resource does not exists at the given URL. This exception is
equivalent to the standard `Http404` Django exception.
By default this exception results in a response with the HTTP status code "404 Not Found".
By default this exception results in a response with the HTTP status code "404
Not Found".
## MethodNotAllowed
@ -160,17 +198,21 @@ By default this exception results in a response with the HTTP status code "405 M
**Signature:** `NotAcceptable(detail=None)`
Raised when an incoming request occurs with an `Accept` header that cannot be satisfied by any of the available renderers.
Raised when an incoming request occurs with an `Accept` header that cannot be
satisfied by any of the available renderers.
By default this exception results in a response with the HTTP status code "406 Not Acceptable".
By default this exception results in a response with the HTTP status code "406
Not Acceptable".
## UnsupportedMediaType
**Signature:** `UnsupportedMediaType(media_type, detail=None)`
Raised if there are no parsers that can handle the content type of the request data when accessing `request.data`.
Raised if there are no parsers that can handle the content type of the request
data when accessing `request.data`.
By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".
By default this exception results in a response with the HTTP status code "415
Unsupported Media Type".
## Throttled
@ -178,7 +220,8 @@ By default this exception results in a response with the HTTP status code "415 U
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".
By default this exception results in a response with the HTTP status code "429
Too Many Requests".
## ValidationError
@ -187,16 +230,25 @@ By default this exception results in a response with the HTTP status code "429 T
The `ValidationError` exception is slightly different from the other `APIException` classes:
* The `detail` argument is mandatory, not optional.
* The `detail` argument may be a list or dictionary of error details, and may also be a nested data structure.
* By convention you should import the serializers module and use a fully qualified `ValidationError` style, in order to differentiate it from Django's built-in validation error. For example. `raise serializers.ValidationError('This field must be an integer value.')`
* The `detail` argument may be a list or dictionary of error details, and may
also be a nested data structure.
* By convention you should import the serializers module and use a fully
qualified `ValidationError` style, in order to differentiate it from Django's
built-in validation error. For example. `raise
serializers.ValidationError('This field must be an integer value.')`
The `ValidationError` class should be used for serializer and field validation, and by validator classes. It is also raised when calling `serializer.is_valid` with the `raise_exception` keyword argument:
The `ValidationError` class should be used for serializer and field validation,
and by validator classes. It is also raised when calling `serializer.is_valid`
with the `raise_exception` keyword argument:
serializer.is_valid(raise_exception=True)
The generic views use the `raise_exception=True` flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.
The generic views use the `raise_exception=True` flag, which means that you can
override the style of validation error responses globally in your API. To do
so, use a custom exception handler, as described above.
By default this exception results in a response with the HTTP status code "400 Bad Request".
By default this exception results in a response with the HTTP status code "400
Bad Request".
[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html
[authentication]: authentication.md

View File

@ -2,72 +2,108 @@ source: fields.py
# Serializer fields
> Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format.
> Each field in a Form class is responsible not only for validating data, but
> also for "cleaning" it — normalizing it to a consistent format.
>
> — [Django documentation][cite]
Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.
Serializer fields handle converting between primitive values and internal
datatypes. They also deal with validating input values, as well as retrieving
and setting the values from their parent objects.
---
**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.<FieldName>`.
**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.<FieldName>`.
---
## 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:
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:
### `read_only`
Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.
Read-only fields are included in the API output, but should not be included in
the input during create or update operations. Any 'read_only' fields that are
incorrectly included in the serializer input will be ignored.
Set this to `True` to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.
Set this to `True` to ensure that the field is used when serializing a
representation, but is not used when creating or updating an instance during
deserialization.
Defaults to `False`
### `write_only`
Set this to `True` to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.
Set this to `True` to ensure that the field may be used when updating or
creating an instance, but is not included when serializing the representation.
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.
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.
Setting this to `False` also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.
Setting this to `False` also allows the object attribute or dictionary key to
be omitted from output when serializing the instance. If the key is not present
it will simply not be included in the output representation.
Defaults to `True`.
### `allow_null`
Normally an error will be raised if `None` is passed to a serializer field. Set this keyword argument to `True` if `None` should be considered a valid value.
Normally an error will be raised if `None` is passed to a serializer field. Set
this keyword argument to `True` if `None` should be considered a valid value.
Defaults to `False`
### `default`
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
If set, this gives the default value that will be used for the field if no
input value is supplied. If not set the default behaviour is to not populate
the attribute at all.
The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
The `default` is not applied during partial update operations. In the partial
update case only fields that are provided in the incoming data will have a
validated value returned.
May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a `set_context` method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for [validators](validators.md#using-set_context).
May be set to a function or other callable, in which case the value will be
evaluated each time it is used. When called, it will receive no arguments. If
the callable has a `set_context` method, that will be called each time before
getting the value with the field instance as only argument. This works the same
way as for [validators](validators.md#using-set_context).
Note that setting a `default` value implies that the field is not required. Including both the `default` and `required` keyword arguments is invalid and will raise an error.
Note that setting a `default` value implies that the field is not required.
Including both the `default` and `required` keyword arguments is invalid and
will raise an error.
### `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 `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`.
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
`URLField(source='get_absolute_url')`, or may use dotted notation to traverse
attributes, such as `EmailField(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, or for fields which require access to the complete object in order to determine the output representation.
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, or for fields which require access to the
complete object in order to determine the output representation.
Defaults to the name of the field.
### `validators`
A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise `serializers.ValidationError`, but Django's built-in `ValidationError` is also supported for compatibility with validators defined in the Django codebase or third party Django packages.
A list of validator functions which should be applied to the incoming field
input, and which either raise a validation error or simply return. Validator
functions should typically raise `serializers.ValidationError`, but Django's
built-in `ValidationError` is also supported for compatibility with validators
defined in the Django codebase or third party Django packages.
### `error_messages`
@ -75,16 +111,19 @@ A dictionary of error codes to error messages.
### `label`
A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
A short text string that may be used as the name of the field in HTML form
fields or other descriptive elements.
### `help_text`
A text string that may be used as a description of the field in HTML form fields or other descriptive elements.
A text string that may be used as a description of the field in HTML form
fields or other descriptive elements.
### `initial`
A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as
you may do with any regular Django `Field`:
A value that should be used for pre-populating the value of HTML form fields.
You may pass a callable to it, just as you may do with any regular Django
`Field`:
import datetime
from rest_framework import serializers
@ -93,7 +132,8 @@ you may do with any regular Django `Field`:
### `style`
A dictionary of key-value pairs that can be used to control how renderers should render the field.
A dictionary of key-value pairs that can be used to control how renderers
should render the field.
Two examples here are `'input_type'` and `'base_template'`:
@ -118,7 +158,11 @@ For more details see the [HTML & Forms][html-and-forms] documentation.
A boolean representation.
When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to `False`, even if it has a `default=True` option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.
When using HTML encoded form input be aware that omitting a value will always
be treated as setting a field to `False`, even if it has a `default=True`
option specified. This is because HTML checkbox inputs represent the unchecked
state by omitting the value, so REST framework treats omission as if it is an
empty checkbox input.
Corresponds to `django.db.models.fields.BooleanField`.
@ -138,18 +182,30 @@ Corresponds to `django.db.models.fields.NullBooleanField`.
## CharField
A text representation. Optionally validates the text to be shorter than `max_length` and longer than `min_length`.
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`.
Corresponds to `django.db.models.fields.CharField` or
`django.db.models.fields.TextField`.
**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)`
**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False,
trim_whitespace=True)`
- `max_length` - Validates that the input contains no more than this number of characters.
- `min_length` - Validates that the input contains no fewer than this number of characters.
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
- `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
- `max_length` - Validates that the input contains no more than this number of
characters.
- `min_length` - Validates that the input contains no fewer than this number of
characters.
- `allow_blank` - If set to `True` then the empty string should be considered a
valid value. If set to `False` then the empty string is considered invalid
and will raise a validation error. Defaults to `False`.
- `trim_whitespace` - If set to `True` then leading and trailing whitespace is
trimmed. Defaults to `True`.
The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.
The `allow_null` option is also available for string fields, although its usage
is discouraged in favor of `allow_blank`. It is valid to set both
`allow_blank=True` and `allow_null=True`, but doing so means that there will be
two differing types of empty value permissible for string representations,
which can lead to data inconsistencies and subtle application bugs.
## EmailField
@ -161,13 +217,16 @@ Corresponds to `django.db.models.fields.EmailField`
## RegexField
A text representation, that validates the given value matches against a certain regular expression.
A text representation, that validates the given value matches against a certain
regular expression.
Corresponds to `django.forms.fields.RegexField`.
**Signature:** `RegexField(regex, max_length=None, min_length=None, allow_blank=False)`
**Signature:** `RegexField(regex, max_length=None, min_length=None,
allow_blank=False)`
The mandatory `regex` argument may either be a string, or a compiled python regular expression object.
The mandatory `regex` argument may either be a string, or a compiled python
regular expression object.
Uses Django's `django.core.validators.RegexValidator` for validation.
@ -181,15 +240,19 @@ Corresponds to `django.db.models.fields.SlugField`.
## URLField
A `RegexField` that validates the input against a URL matching pattern. Expects fully qualified URLs of the form `http://<host>/<path>`.
A `RegexField` that validates the input against a URL matching pattern. Expects
fully qualified URLs of the form `http://<host>/<path>`.
Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation.
Corresponds to `django.db.models.fields.URLField`. Uses Django's
`django.core.validators.URLValidator` for validation.
**Signature:** `URLField(max_length=200, min_length=None, allow_blank=False)`
## UUIDField
A field that ensures the input is a valid UUID string. The `to_internal_value` method will return a `uuid.UUID` instance. On output the field will return a string in the canonical hyphenated format, for example:
A field that ensures the input is a valid UUID string. The `to_internal_value`
method will return a `uuid.UUID` instance. On output the field will return a
string in the canonical hyphenated format, for example:
"de305d54-75b4-431b-adb2-eb6b9e546013"
@ -210,11 +273,16 @@ Corresponds to `django.forms.fields.FilePathField`.
**Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)`
- `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
- `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
- `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
- `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
- `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
- `path` - The absolute filesystem path to a directory from which this
FilePathField should get its choice.
- `match` - A regular expression, as a string, that FilePathField will use to
filter filenames.
- `recursive` - Specifies whether all subdirectories of path should be
included. Default is `False`.
- `allow_files` - Specifies whether files in the specified location should be
included. Default is `True`. Either this or `allow_folders` must be `True`.
- `allow_folders` - Specifies whether folders in the specified location should
be included. Default is `False`. Either this or `allow_files` must be `True`.
## IPAddressField
@ -224,8 +292,11 @@ Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen
**Signature**: `IPAddressField(protocol='both', unpack_ipv4=False, **options)`
- `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
- `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
- `protocol` Limits valid inputs to the specified protocol. Accepted values are
'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
- `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this
option is enabled that address would be unpacked to 192.0.2.1. Default is
disabled. Can only be used when protocol is set to 'both'.
---
@ -235,7 +306,10 @@ Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen
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`.
Corresponds to `django.db.models.fields.IntegerField`,
`django.db.models.fields.SmallIntegerField`,
`django.db.models.fields.PositiveIntegerField` and
`django.db.models.fields.PositiveSmallIntegerField`.
**Signature**: `IntegerField(max_value=None, min_value=None)`
@ -261,12 +335,21 @@ Corresponds to `django.db.models.fields.DecimalField`.
**Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)`
- `max_digits` The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places.
- `max_digits` The maximum number of digits allowed in the number. Note that
this number must be greater than or equal to decimal_places.
- `decimal_places` The number of decimal places to store with the number.
- `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
- `coerce_to_string` Set to `True` if string values should be returned for the
representation, or `False` if `Decimal` objects should be returned. Defaults
to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will
be `True` unless overridden. If `Decimal` objects are returned by the
serializer, then the final output format will be determined by the renderer.
Note that setting `localize` will force the value to `True`.
- `max_value` Validate that the number provided is no greater than this value.
- `min_value` Validate that the number provided is no less than this value.
- `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
- `localize` Set to `True` to enable localization of input and output based on
the current locale. This will also force `coerce_to_string` to `True`.
Defaults to `False`. Note that data formatting is enabled if you have set
`USE_L10N=True` in your settings file.
#### Example usage
@ -294,22 +377,41 @@ Corresponds to `django.db.models.fields.DateTimeField`.
**Signature:** `DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)`
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATETIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. In this case the datetime encoding will be determined by the renderer.
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
* `format` - A string representing the output format. If not specified, this
defaults to the same value as the `DATETIME_FORMAT` settings key, which will
be `'iso-8601'` unless set. Setting to a format string indicates that
`to_representation` return values should be coerced to string output. Format
strings are described below. Setting this value to `None` indicates that
Python `datetime` objects should be returned by `to_representation`. In this
case the datetime encoding will be determined by the renderer.
* `input_formats` - A list of strings representing the input formats which may
be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS`
setting will be used, which defaults to `['iso-8601']`.
#### `DateTimeField` format strings.
Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`)
Format strings may either be [Python strftime formats][strftime] which
explicitly specify the format, or the special string `'iso-8601'`, which
indicates that [ISO 8601][iso8601] style datetimes should be used. (eg
`'2013-01-29T12:34:56.000000Z'`)
When a value of `None` is used for the format `datetime` objects will be returned by `to_representation` and the final output representation will determined by the renderer class.
When a value of `None` is used for the format `datetime` objects will be
returned by `to_representation` and the final output representation will
determined by the renderer class.
In the case of JSON this means the default datetime representation uses the [ECMA 262 date time string specification][ecma262]. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: `2013-01-29T12:34:56.123Z`.
In the case of JSON this means the default datetime representation uses the
[ECMA 262 date time string specification][ecma262]. This is a subset of ISO
8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC
timezone, for example: `2013-01-29T12:34:56.123Z`.
#### `auto_now` and `auto_now_add` model fields.
When using `ModelSerializer` or `HyperlinkedModelSerializer`, note that any model fields with `auto_now=True` or `auto_now_add=True` will use serializer fields that are `read_only=True` by default.
When using `ModelSerializer` or `HyperlinkedModelSerializer`, note that any
model fields with `auto_now=True` or `auto_now_add=True` will use serializer
fields that are `read_only=True` by default.
If you want to override this behavior, you'll need to declare the `DateTimeField` explicitly on the serializer. For example:
If you want to override this behavior, you'll need to declare the
`DateTimeField` explicitly on the serializer. For example:
class CommentSerializer(serializers.ModelSerializer):
created = serializers.DateTimeField()
@ -325,12 +427,23 @@ Corresponds to `django.db.models.fields.DateField`
**Signature:** `DateField(format=api_settings.DATE_FORMAT, input_formats=None)`
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATE_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `date` objects should be returned by `to_representation`. In this case the date encoding will be determined by the renderer.
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
* `format` - A string representing the output format. If not specified, this
defaults to the same value as the `DATE_FORMAT` settings key, which will be
`'iso-8601'` unless set. Setting to a format string indicates that
`to_representation` return values should be coerced to string output. Format
strings are described below. Setting this value to `None` indicates that
Python `date` objects should be returned by `to_representation`. In this case
the date encoding will be determined by the renderer.
* `input_formats` - A list of strings representing the input formats which may
be used to parse the date. If not specified, the `DATE_INPUT_FORMATS`
setting will be used, which defaults to `['iso-8601']`.
#### `DateField` format strings
Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`)
Format strings may either be [Python strftime formats][strftime] which
explicitly specify the format, or the special string `'iso-8601'`, which
indicates that [ISO 8601][iso8601] style dates should be used. (eg
`'2013-01-29'`)
## TimeField
@ -340,12 +453,23 @@ Corresponds to `django.db.models.fields.TimeField`
**Signature:** `TimeField(format=api_settings.TIME_FORMAT, input_formats=None)`
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `TIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `time` objects should be returned by `to_representation`. In this case the time encoding will be determined by the renderer.
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
* `format` - A string representing the output format. If not specified, this
defaults to the same value as the `TIME_FORMAT` settings key, which will be
`'iso-8601'` unless set. Setting to a format string indicates that
`to_representation` return values should be coerced to string output. Format
strings are described below. Setting this value to `None` indicates that
Python `time` objects should be returned by `to_representation`. In this case
the time encoding will be determined by the renderer.
* `input_formats` - A list of strings representing the input formats which may
be used to parse the date. If not specified, the `TIME_INPUT_FORMATS`
setting will be used, which defaults to `['iso-8601']`.
#### `TimeField` format strings
Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`)
Format strings may either be [Python strftime formats][strftime] which
explicitly specify the format, or the special string `'iso-8601'`, which
indicates that [ISO 8601][iso8601] style times should be used. (eg
`'12:34:56.000000'`)
## DurationField
@ -371,25 +495,49 @@ Used by `ModelSerializer` to automatically generate fields if the corresponding
**Signature:** `ChoiceField(choices)`
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
- `choices` - A list of valid values, or a list of `(key, display_name)`
tuples.
- `allow_blank` - If set to `True` then the empty string should be considered a
valid value. If set to `False` then the empty string is considered invalid
and will raise a validation error. Defaults to `False`.
- `html_cutoff` - If set this will be the maximum number of choices that will
be displayed by a HTML select drop down. Can be used to ensure that
automatically generated ChoiceFields with very large possible selections do
not prevent a template from rendering. Defaults to `None`.
- `html_cutoff_text` - If set this will display a textual indicator if the
maximum number of items have been cutoff in an HTML select drop down.
Defaults to `"More than {count} items…"`
Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`,
although it is highly recommended that you only use one and not both.
`allow_blank` should be preferred for textual choices, and `allow_null` should
be preferred for numeric or other non-textual choices.
## MultipleChoiceField
A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. `to_internal_value` returns a `set` containing the selected values.
A field that can accept a set of zero, one or many values, chosen from a
limited set of choices. Takes a single mandatory argument. `to_internal_value`
returns a `set` containing the selected values.
**Signature:** `MultipleChoiceField(choices)`
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
- `choices` - A list of valid values, or a list of `(key, display_name)`
tuples.
- `allow_blank` - If set to `True` then the empty string should be considered a
valid value. If set to `False` then the empty string is considered invalid
and will raise a validation error. Defaults to `False`.
- `html_cutoff` - If set this will be the maximum number of choices that will
be displayed by a HTML select drop down. Can be used to ensure that
automatically generated ChoiceFields with very large possible selections do
not prevent a template from rendering. Defaults to `None`.
- `html_cutoff_text` - If set this will display a textual indicator if the
maximum number of items have been cutoff in an HTML select drop down.
Defaults to `"More than {count} items…"`
As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
As with `ChoiceField`, both the `allow_blank` and `allow_null` options are
valid, although it is highly recommended that you only use one and not both.
`allow_blank` should be preferred for textual choices, and `allow_null` should
be preferred for numeric or other non-textual choices.
---
@ -397,8 +545,10 @@ As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid
#### Parsers and file uploads.
The `FileField` and `ImageField` classes are only suitable for use with `MultiPartParser` or `FileUploadParser`. Most parsers, such as e.g. JSON don't support file uploads.
Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
The `FileField` and `ImageField` classes are only suitable for use with
`MultiPartParser` or `FileUploadParser`. Most parsers, such as e.g. JSON don't
support file uploads. Django's regular [FILE_UPLOAD_HANDLERS] are used for
handling uploaded files.
## FileField
@ -406,25 +556,35 @@ A file representation. Performs Django's standard FileField validation.
Corresponds to `django.forms.fields.FileField`.
**Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
**Signature:** `FileField(max_length=None, allow_empty_file=False,
use_url=UPLOADED_FILES_USE_URL)`
- `max_length` - Designates the maximum length for the file name.
- `allow_empty_file` - Designates if empty files are allowed.
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
- `use_url` - If set to `True` then URL string values will be used for the
output representation. If set to `False` then filename string values will be
used for the output representation. Defaults to the value of the
`UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
## ImageField
An image representation. Validates the uploaded file content as matching a known image format.
An image representation. Validates the uploaded file content as matching a
known image format.
Corresponds to `django.forms.fields.ImageField`.
**Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
**Signature:** `ImageField(max_length=None, allow_empty_file=False,
use_url=UPLOADED_FILES_USE_URL)`
- `max_length` - Designates the maximum length for the file name.
- `allow_empty_file` - Designates if empty files are allowed.
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
- `use_url` - If set to `True` then URL string values will be used for the
output representation. If set to `False` then filename string values will be
used for the output representation. Defaults to the value of the
`UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained.
Requires either the `Pillow` package or `PIL` package. The `Pillow` package is
recommended, as `PIL` is no longer actively maintained.
---
@ -436,30 +596,39 @@ A field class that validates a list of objects.
**Signature**: `ListField(child)`
- `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
- `child` - A field instance that should be used for validating the objects in
the list. If this argument is not provided then objects in the list will not
be validated.
For example, to validate a list of integers you might use something like the following:
For example, to validate a list of integers you might use something like the
following:
scores = serializers.ListField(
child=serializers.IntegerField(min_value=0, max_value=100)
)
The `ListField` class also supports a declarative style that allows you to write reusable list field classes.
The `ListField` class also supports a declarative style that allows you to
write reusable list field classes.
class StringListField(serializers.ListField):
child = serializers.CharField()
We can now reuse our custom `StringListField` class throughout our application, without having to provide a `child` argument to it.
We can now reuse our custom `StringListField` class throughout our application,
without having to provide a `child` argument to it.
## DictField
A field class that validates a dictionary of objects. The keys in `DictField` are always assumed to be string values.
A field class that validates a dictionary of objects. The keys in `DictField`
are always assumed to be string values.
**Signature**: `DictField(child)`
- `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
- `child` - A field instance that should be used for validating the values in
the dictionary. If this argument is not provided then values in the mapping
will not be validated.
For example, to create a field that validates a mapping of strings to strings, you would write something like this:
For example, to create a field that validates a mapping of strings to strings,
you would write something like this:
document = DictField(child=CharField())
@ -470,11 +639,14 @@ You can also use the declarative style, as with `ListField`. For example:
## JSONField
A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.
A field class that validates that the incoming data structure consists of valid
JSON primitives. In its alternate binary mode, it will represent and validate
JSON-encoded binary strings.
**Signature**: `JSONField(binary)`
- `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
- `binary` - If set to `True` then the field will output and validate a JSON
encoded string, rather than a primitive data structure. Defaults to `False`.
---
@ -484,11 +656,13 @@ A field class that validates that the incoming data structure consists of valid
A field class that simply returns the value of the field without modification.
This field is used by default with `ModelSerializer` when including field names that relate to an attribute rather than a model field.
This field is used by default with `ModelSerializer` when including field names
that relate to an attribute rather than a model field.
**Signature**: `ReadOnlyField()`
For example, if `has_expired` was a property on the `Account` model, then the following serializer would automatically generate it as a `ReadOnlyField`:
For example, if `has_expired` was a property on the `Account` model, then the
following serializer would automatically generate it as a `ReadOnlyField`:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
@ -497,37 +671,54 @@ For example, if `has_expired` was a property on the `Account` model, then the fo
## HiddenField
A field class that does not take a value based on user input, but instead takes its value from a default value or callable.
A field class that does not take a value based on user input, but instead takes
its value from a default value or callable.
**Signature**: `HiddenField()`
For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:
For example, to include a field that always provides the current time as part
of the serializer validated data, you would use the following:
modified = serializers.HiddenField(default=timezone.now)
The `HiddenField` class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.
The `HiddenField` class is usually only needed if you have some validation that
needs to run based on some pre-provided field values, but you do not want to
expose all of those fields to the end user.
For further examples on `HiddenField` see the [validators](validators.md) documentation.
## ModelField
A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.
A generic field that can be tied to any arbitrary model field. The `ModelField`
class delegates the task of serialization/deserialization to its associated
model field. This field can be used to create serializer fields for custom
model fields, without having to create a new custom serializer field.
This field is used by `ModelSerializer` to correspond to custom model field classes.
This field is used by `ModelSerializer` to correspond to custom model field
classes.
**Signature:** `ModelField(model_field=<Django ModelField instance>)`
The `ModelField` class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a `ModelField`, it must be passed a field that is attached to an instantiated model. For example: `ModelField(model_field=MyModel()._meta.get_field('custom_field'))`
The `ModelField` class is generally intended for internal use, but can be used
by your API if needed. In order to properly instantiate a `ModelField`, it
must be passed a field that is attached to an instantiated model. For example:
`ModelField(model_field=MyModel()._meta.get_field('custom_field'))`
## SerializerMethodField
This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.
This is a read-only field. It gets its value by calling a method on the
serializer class it is attached to. It can be used to add any sort of data to
the serialized representation of your object.
**Signature**: `SerializerMethodField(method_name=None)`
- `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
- `method_name` - The name of the method on the serializer to be called. If not
included this defaults to `get_<field_name>`.
The serializer method referred to by the `method_name` argument should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
The serializer method referred to by the `method_name` argument should accept a
single argument (in addition to `self`), which is the object being serialized.
It should return whatever you want to be included in the serialized
representation of the object. For example:
from django.contrib.auth.models import User
from django.utils.timezone import now
@ -546,17 +737,30 @@ The serializer method referred to by the `method_name` argument should accept a
# Custom fields
If you want to create a custom field, you'll need to subclass `Field` and then override either one or both of the `.to_representation()` and `.to_internal_value()` methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, `date`/`time`/`datetime` or `None`. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.
If you want to create a custom field, you'll need to subclass `Field` and then
override either one or both of the `.to_representation()` and
`.to_internal_value()` methods. These two methods are used to convert between
the initial datatype, and a primitive, serializable datatype. Primitive
datatypes will typically be any of a number, string, boolean,
`date`/`time`/`datetime` or `None`. They may also be any list or dictionary
like object that only contains other primitive objects. Other types might be
supported, depending on the renderer that you are using.
The `.to_representation()` method is called to convert the initial datatype into a primitive, serializable datatype.
The `.to_representation()` method is called to convert the initial datatype
into a primitive, serializable datatype.
The `to_internal_value()` method is called to restore a primitive datatype into its internal python representation. This method should raise a `serializers.ValidationError` if the data is invalid.
The `to_internal_value()` method is called to restore a primitive datatype into
its internal python representation. This method should raise a
`serializers.ValidationError` if the data is invalid.
Note that the `WritableField` class that was present in version 2.x no longer exists. You should subclass `Field` and override `to_internal_value()` if the field supports data input.
Note that the `WritableField` class that was present in version 2.x no longer
exists. You should subclass `Field` and override `to_internal_value()` if the
field supports data input.
## Examples
Let's look at an example of serializing a class that represents an RGB color value:
Let's look at an example of serializing a class that represents an RGB color
value:
class Color(object):
"""
@ -579,9 +783,12 @@ Let's look at an example of serializing a class that represents an RGB color val
red, green, blue = [int(col) for col in data.split(',')]
return Color(red, green, blue)
By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override `.get_attribute()` and/or `.get_value()`.
By default field values are treated as mapping to an attribute on the object.
If you need to customize how the field value is accessed and set you need to
override `.get_attribute()` and/or `.get_value()`.
As an example, let's create a field that can be used to represent the class name of the object being serialized:
As an example, let's create a field that can be used to represent the class
name of the object being serialized:
class ClassNameField(serializers.Field):
def get_attribute(self, obj):
@ -616,7 +823,8 @@ To indicate invalid data, we should raise a `serializers.ValidationError`, like
return Color(red, green, blue)
The `.fail()` method is a shortcut for raising `ValidationError` that takes a message string from the `error_messages` dictionary. For example:
The `.fail()` method is a shortcut for raising `ValidationError` that takes a
message string from the `error_messages` dictionary. For example:
default_error_messages = {
'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',
@ -640,7 +848,8 @@ The `.fail()` method is a shortcut for raising `ValidationError` that takes a me
return Color(red, green, blue)
This style keeps you error messages more cleanly separated from your code, and should be preferred.
This style keeps you error messages more cleanly separated from your code, and
should be preferred.
# Third party packages
@ -648,23 +857,35 @@ The following third party packages are also available.
## DRF Compound Fields
The [drf-compound-fields][drf-compound-fields] package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the `many=True` option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.
The [drf-compound-fields][drf-compound-fields] package provides "compound"
serializer fields, such as lists of simple values, which can be described by
other fields rather than serializers with the `many=True` option. Also provided
are fields for typed dictionaries and values that can be either a specific type
or a list of items of that type.
## DRF Extra Fields
The [drf-extra-fields][drf-extra-fields] package provides extra serializer fields for REST framework, including `Base64ImageField` and `PointField` classes.
The [drf-extra-fields][drf-extra-fields] package provides extra serializer
fields for REST framework, including `Base64ImageField` and `PointField`
classes.
## djangrestframework-recursive
the [djangorestframework-recursive][djangorestframework-recursive] package provides a `RecursiveField` for serializing and deserializing recursive structures
the [djangorestframework-recursive][djangorestframework-recursive] package
provides a `RecursiveField` for serializing and deserializing recursive
structures
## django-rest-framework-gis
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
The [django-rest-framework-gis][django-rest-framework-gis] package provides
geographic addons for django rest framework like a `GeometryField` field and a
GeoJSON serializer.
## django-rest-framework-hstore
The [django-rest-framework-hstore][django-rest-framework-hstore] package provides an `HStoreField` to support [django-hstore][django-hstore] `DictionaryField` model field.
The [django-rest-framework-hstore][django-rest-framework-hstore] package
provides an `HStoreField` to support [django-hstore][django-hstore]
`DictionaryField` model field.
[cite]: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data
[html-and-forms]: ../topics/html-and-forms.md

View File

@ -2,19 +2,26 @@ source: filters.py
# Filtering
> The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.
> The root QuerySet provided by the Manager describes all objects in the
> database table. Usually, though, you'll need to select only a subset of the
> complete set of objects.
>
> &mdash; [Django documentation][cite]
The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.
The default behavior of REST framework's generic list views is to return the
entire queryset for a model manager. Often you will want your API to restrict
the items that are returned by the queryset.
The simplest way to filter the queryset of any view that subclasses `GenericAPIView` is to override the `.get_queryset()` method.
The simplest way to filter the queryset of any view that subclasses
`GenericAPIView` is to override the `.get_queryset()` method.
Overriding this method allows you to customize the queryset returned by the view in a number of different ways.
Overriding this method allows you to customize the queryset returned by the
view in a number of different ways.
## Filtering against the current user
You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.
You might want to filter the queryset to ensure that only results relevant to
the currently authenticated user making the request are returned.
You can do so by filtering based on the value of `request.user`.
@ -38,13 +45,15 @@ For example:
## Filtering against the URL
Another style of filtering might involve restricting the queryset based on some part of the URL.
Another style of filtering might involve restricting the queryset based on some
part of the URL.
For example if your URL config contained an entry like this:
url('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
You could then write a view that returned a purchase queryset filtered by the username portion of the URL:
You could then write a view that returned a purchase queryset filtered by the
username portion of the URL:
class PurchaseList(generics.ListAPIView):
serializer_class = PurchaseSerializer
@ -59,9 +68,12 @@ You could then write a view that returned a purchase queryset filtered by the us
## Filtering against query parameters
A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.
A final example of filtering the initial queryset would be to determine the
initial queryset based on query parameters in the url.
We can override `.get_queryset()` to deal with URLs such as `http://example.com/api/purchases?username=denvercoder9`, and filter the queryset only if the `username` parameter is included in the URL:
We can override `.get_queryset()` to deal with URLs such as
`http://example.com/api/purchases?username=denvercoder9`, and filter the
queryset only if the `username` parameter is included in the URL:
class PurchaseList(generics.ListAPIView):
serializer_class = PurchaseSerializer
@ -81,9 +93,12 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/
# Generic Filtering
As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters.
As well as being able to override the default queryset, REST framework also
includes support for generic filtering backends that allow you to easily
construct complex searches and filters.
Generic filters can also present themselves as HTML controls in the browsable API and admin API.
Generic filters can also present themselves as HTML controls in the browsable
API and admin API.
![Filter Example](../img/filter-controls.png)
@ -110,15 +125,23 @@ using the `GenericAPIView` class-based views.
## Filtering and object lookups
Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object.
Note that if a filter backend is configured for a view, then as well as being
used to filter list views, it will also be used to filter the querysets used
for returning a single object.
For instance, given the previous example, and a product with an id of `4675`, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance:
For instance, given the previous example, and a product with an id of `4675`,
the following URL would either return the corresponding object, or return a 404
response, depending on if the filtering conditions were met by the given
product instance:
http://example.com/api/products/4675/?category=clothing&max_price=10.00
## Overriding the initial queryset
Note that you can use both an overridden `.get_queryset()` and generic filtering together, and everything will work as expected. For example, if `Product` had a many-to-many relationship with `User`, named `purchase`, you might want to write a view like this:
Note that you can use both an overridden `.get_queryset()` and generic
filtering together, and everything will work as expected. For example, if
`Product` had a many-to-many relationship with `User`, named `purchase`, you
might want to write a view like this:
class PurchasedProductsList(generics.ListAPIView):
"""
@ -139,23 +162,30 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering
## DjangoFilterBackend
The `DjangoFilterBackend` class supports highly customizable field filtering, using the [django-filter package][django-filter].
The `DjangoFilterBackend` class supports highly customizable field filtering,
using the [django-filter package][django-filter].
To use REST framework's `DjangoFilterBackend`, first install `django-filter`.
pip install django-filter
If you are using the browsable API or admin API you may also want to install `django-crispy-forms`, which will enhance the presentation of the filter forms in HTML views, by allowing them to render Bootstrap 3 HTML.
If you are using the browsable API or admin API you may also want to install
`django-crispy-forms`, which will enhance the presentation of the filter forms
in HTML views, by allowing them to render Bootstrap 3 HTML.
pip install django-crispy-forms
With crispy forms installed and added to Django's `INSTALLED_APPS`, the browsable API will present a filtering control for `DjangoFilterBackend`, like so:
With crispy forms installed and added to Django's `INSTALLED_APPS`, the
browsable API will present a filtering control for `DjangoFilterBackend`, like
so:
![Django Filter](../img/django-filter.png)
#### Specifying filter fields
If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against.
If all you need is simple equality-based filtering, you can set a
`filter_fields` attribute on the view, or viewset, listing the set of fields
you wish to filter against.
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
@ -213,7 +243,9 @@ This enables us to make queries like:
http://example.com/api/products?manufacturer__name=foo
This is nice, but it exposes the Django's double underscore convention as part of the API. If you instead want to explicitly name the filter argument you can instead explicitly include it on the `FilterSet` class:
This is nice, but it exposes the Django's double underscore convention as part
of the API. If you instead want to explicitly name the filter argument you can
instead explicitly include it on the `FilterSet` class:
import django_filters
from myapp.models import Product
@ -238,21 +270,31 @@ For more details on using filter sets see the [django-filter documentation][djan
**Hints & Tips**
* By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'DEFAULT_FILTER_BACKENDS'` setting.
* When using boolean fields, you should use the values `True` and `False` in the URL query parameters, rather than `0`, `1`, `true` or `false`. (The allowed boolean values are currently hardwired in Django's [NullBooleanSelect implementation][nullbooleanselect].)
* `django-filter` supports filtering across relationships, using Django's double-underscore syntax.
* By default filtering is not enabled. If you want to use
`DjangoFilterBackend` remember to make sure it is installed by using the
`'DEFAULT_FILTER_BACKENDS'` setting.
* When using boolean fields, you should use the values `True` and `False` in
the URL query parameters, rather than `0`, `1`, `true` or `false`. (The
allowed boolean values are currently hardwired in Django's [NullBooleanSelect
implementation][nullbooleanselect].)
* `django-filter` supports filtering across relationships, using Django's
double-underscore syntax.
---
## SearchFilter
The `SearchFilter` class supports simple single query parameter based searching, and is based on the [Django admin's search functionality][search-django-admin].
The `SearchFilter` class supports simple single query parameter based
searching, and is based on the [Django admin's search
functionality][search-django-admin].
When in use, the browsable API will include a `SearchFilter` control:
![Search Filter](../img/search-filter.png)
The `SearchFilter` class will only be applied if the view has a `search_fields` attribute set. The `search_fields` attribute should be a list of names of text type fields on the model, such as `CharField` or `TextField`.
The `SearchFilter` class will only be applied if the view has a `search_fields`
attribute set. The `search_fields` attribute should be a list of names of text
type fields on the model, such as `CharField` or `TextField`.
class UserListView(generics.ListAPIView):
queryset = User.objects.all()
@ -260,17 +302,23 @@ The `SearchFilter` class will only be applied if the view has a `search_fields`
filter_backends = (filters.SearchFilter,)
search_fields = ('username', 'email')
This will allow the client to filter the items in the list by making queries such as:
This will allow the client to filter the items in the list by making queries
such as:
http://example.com/api/users?search=russell
You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:
You can also perform a related lookup on a ForeignKey or ManyToManyField with
the lookup API double-underscore notation:
search_fields = ('username', 'email', 'profile__profession')
By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.
By default, searches will use case-insensitive partial matches. The search
parameter may contain multiple search terms, which should be whitespace and/or
comma separated. If multiple search terms are used then objects will be
returned in the list only if all the provided terms are matched.
The search behavior may be restricted by prepending various characters to the `search_fields`.
The search behavior may be restricted by prepending various characters to the
`search_fields`.
* '^' Starts-with search.
* '=' Exact matches.
@ -309,7 +357,9 @@ Multiple orderings may also be specified:
### Specifying which fields may be ordered against
It's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an `ordering_fields` attribute on the view, like so:
It's recommended that you explicitly specify which fields the API should
allowing in the ordering filter. You can do this by setting an
`ordering_fields` attribute on the view, like so:
class UserListView(generics.ListAPIView):
queryset = User.objects.all()
@ -317,11 +367,17 @@ It's recommended that you explicitly specify which fields the API should allowin
filter_backends = (filters.OrderingFilter,)
ordering_fields = ('username', 'email')
This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data.
This helps prevent unexpected data leakage, such as allowing users to order
against a password hash field or other sensitive data.
If you *don't* specify an `ordering_fields` attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the `serializer_class` attribute.
If you *don't* specify an `ordering_fields` attribute on the view, the filter
class will default to allowing the user to filter on any readable fields on the
serializer specified by the `serializer_class` attribute.
If you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on *any* model field or queryset aggregate, by using the special value `'__all__'`.
If you are confident that the queryset being used by the view doesn't contain
any sensitive data, you can also explicitly specify that a view should allow
ordering on *any* model field or queryset aggregate, by using the special value
`'__all__'`.
class BookingsListView(generics.ListAPIView):
queryset = Booking.objects.all()
@ -331,9 +387,14 @@ If you are confident that the queryset being used by the view doesn't contain an
### Specifying a default ordering
If an `ordering` attribute is set on the view, this will be used as the default ordering.
If an `ordering` attribute is set on the view, this will be used as the default
ordering.
Typically you'd instead control this by setting `order_by` on the initial queryset, but using the `ordering` parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results.
Typically you'd instead control this by setting `order_by` on the initial
queryset, but using the `ordering` parameter on the view allows you to specify
the ordering in a way that it can then be passed automatically as context to a
rendered template. This makes it possible to automatically render column
headers differently if they are being used to order the results.
class UserListView(generics.ListAPIView):
queryset = User.objects.all()
@ -348,11 +409,19 @@ The `ordering` attribute may be either a string or a list/tuple of strings.
## DjangoObjectPermissionsFilter
The `DjangoObjectPermissionsFilter` is intended to be used together with the [`django-guardian`][guardian] package, with custom `'view'` permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission.
The `DjangoObjectPermissionsFilter` is intended to be used together with the
[`django-guardian`][guardian] package, with custom `'view'` permissions added.
The filter will ensure that querysets only returns objects for which the user
has the appropriate view permission.
If you're using `DjangoObjectPermissionsFilter`, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass `DjangoObjectPermissions` and add `'view'` permissions to the `perms_map` attribute.
If you're using `DjangoObjectPermissionsFilter`, you'll probably also want to
add an appropriate object permissions class, to ensure that users can only
operate on instances if they have the appropriate object permissions. The
easiest way to do this is to subclass `DjangoObjectPermissions` and add
`'view'` permissions to the `perms_map` attribute.
A complete example using both `DjangoObjectPermissionsFilter` and `DjangoObjectPermissions` might look something like this.
A complete example using both `DjangoObjectPermissionsFilter` and
`DjangoObjectPermissions` might look something like this.
**permissions.py**:
@ -389,11 +458,16 @@ For more information on adding `'view'` permissions for models, see the [relevan
# Custom generic filtering
You can also provide your own generic filtering backend, or write an installable app for other developers to use.
You can also provide your own generic filtering backend, or write an
installable app for other developers to use.
To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. The method should return a new, filtered queryset.
To do so override `BaseFilterBackend`, and override the `.filter_queryset(self,
request, queryset, view)` method. The method should return a new, filtered
queryset.
As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user.
As well as allowing clients to perform searches and filtering, generic filter
backends can be useful for restricting which objects should be visible to any
given request or user.
## Example
@ -406,11 +480,15 @@ For example, you might need to restrict users to only being able to see objects
def filter_queryset(self, request, queryset, view):
return queryset.filter(owner=request.user)
We could achieve the same behavior by overriding `get_queryset()` on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API.
We could achieve the same behavior by overriding `get_queryset()` on the views,
but using a filter backend allows you to more easily add this restriction to
multiple views, or to apply it across the entire API.
## Customizing the interface
Generic filters may also present an interface in the browsable API. To do so you should implement a `to_html()` method which returns a rendered HTML representation of the filter. This method should have the following signature:
Generic filters may also present an interface in the browsable API. To do so
you should implement a `to_html()` method which returns a rendered HTML
representation of the filter. This method should have the following signature:
`to_html(self, request, queryset, view)`
@ -422,15 +500,25 @@ The following third party packages provide additional filter implementations.
## Django REST framework filters package
The [django-rest-framework-filters package][django-rest-framework-filters] works together with the `DjangoFilterBackend` class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field.
The [django-rest-framework-filters package][django-rest-framework-filters]
works together with the `DjangoFilterBackend` class, and allows you to easily
create filters across relationships, or create multiple filter lookup types for
a given field.
## Django REST framework full word search filter
The [djangorestframework-word-filter][django-rest-framework-word-search-filter] developed as alternative to `filters.SearchFilter` which will search full word in text, or exact match.
The [djangorestframework-word-filter][django-rest-framework-word-search-filter]
developed as alternative to `filters.SearchFilter` which will search full word
in text, or exact match.
## Django URL Filter
[django-url-filter][django-url-filter] provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django `QuerySet`s.
[django-url-filter][django-url-filter] provides a safe way to filter data via
human-friendly URLs. It works very similar to DRF serializers and fields in a
sense that they can be nested except they are called filtersets and filters.
That provides easy way to filter related data. Also this library is
generic-purpose so it can be used to filter other sources of data and not only
Django `QuerySet`s.
[cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters
[django-filter]: https://github.com/alex/django-filter

View File

@ -7,21 +7,30 @@ used all the time.
>
> &mdash; Roy Fielding, [REST discuss mailing list][cite]
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.
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.
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)
**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.
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.
* **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:
@ -36,7 +45,8 @@ Example:
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:
When using `format_suffix_patterns`, you must make sure to add the `'format'`
keyword argument to the corresponding views. For example:
@api_view(('GET', 'POST'))
def comment_list(request, format=None):
@ -51,13 +61,17 @@ Or with class-based views:
def post(self, request, format=None):
# do stuff...
The name of the kwarg used may be modified by using the `FORMAT_SUFFIX_KWARG` setting.
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.
Also note that `format_suffix_patterns` does not support descending into
`include` URL patterns.
### Using with `i18n_patterns`
If using the `i18n_patterns` function provided by Django, as well as `format_suffix_patterns` you should make sure that the `i18n_patterns` function is applied as the final, or outermost function. For example:
If using the `i18n_patterns` function provided by Django, as well as
`format_suffix_patterns` you should make sure that the `i18n_patterns` function
is applied as the final, or outermost function. For example:
url patterns = [
@ -71,23 +85,34 @@ If using the `i18n_patterns` function provided by Django, as well as `format_suf
## Query parameter formats
An alternative to the format suffixes is to include the requested format in a query parameter. REST framework provides this option by default, and it is used in the browsable API to switch between differing available representations.
An alternative to the format suffixes is to include the requested format in a
query parameter. REST framework provides this option by default, and it is used
in the browsable API to switch between differing available representations.
To select a representation using its short format, use the `format` query parameter. For example: `http://example.com/organizations/?format=csv`.
To select a representation using its short format, use the `format` query
parameter. For example: `http://example.com/organizations/?format=csv`.
The name of this query parameter can be modified using the `URL_FORMAT_OVERRIDE` setting. Set the value to `None` to disable this behavior.
The name of this query parameter can be modified using the
`URL_FORMAT_OVERRIDE` setting. Set the value to `None` to disable this
behavior.
---
## 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.
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:
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:
&ldquo;That's why I always prefer extensions. Neither choice has anything to do with REST.&rdquo; &mdash; Roy Fielding, [REST discuss mailing list][cite2]
&ldquo;That's why I always prefer extensions. Neither choice has anything to
do with REST.&rdquo; &mdash; 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.
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

View File

@ -7,15 +7,21 @@ source: mixins.py
>
> &mdash; [Django Documentation][cite]
One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
One of the key benefits of class-based views is the way they allow you to
compose bits of reusable behavior. REST framework takes advantage of this by
providing a number of pre-built views that provide for commonly used patterns.
The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.
The generic views provided by REST framework allow you to quickly build API
views that map closely to your database models.
If the generic views don't suit the needs of your API, you can drop down to using the regular `APIView` class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.
If the generic views don't suit the needs of your API, you can drop down to
using the regular `APIView` class, or reuse the mixins and base classes used by
the generic views to compose your own set of reusable generic views.
## Examples
Typically when using the generic views, you'll override the view, and set several class attributes.
Typically when using the generic views, you'll override the view, and set
several class attributes.
from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
@ -27,7 +33,8 @@ Typically when using the generic views, you'll override the view, and set severa
serializer_class = UserSerializer
permission_classes = (IsAdminUser,)
For more complex cases you might also want to override various methods on the view class. For example.
For more complex cases you might also want to override various methods on the
view class. For example.
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
@ -40,7 +47,9 @@ For more complex cases you might also want to override various methods on the vi
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)
For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something like the following entry:
For very simple cases you might want to pass through any class attributes using
the `.as_view()` method. For example, your URLconf might include something
like the following entry:
url(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
@ -50,9 +59,11 @@ For very simple cases you might want to pass through any class attributes using
## GenericAPIView
This class extends REST framework's `APIView` class, adding commonly required behavior for standard list and detail views.
This class extends REST framework's `APIView` class, adding commonly required
behavior for standard list and detail views.
Each of the concrete generic views provided is built by combining `GenericAPIView`, with one or more mixin classes.
Each of the concrete generic views provided is built by combining
`GenericAPIView`, with one or more mixin classes.
### Attributes
@ -60,20 +71,38 @@ Each of the concrete generic views provided is built by combining `GenericAPIVie
The following attributes control the basic view behavior.
* `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method. If you are overriding a view method, it is important that you call `get_queryset()` instead of accessing this property directly, as `queryset` will get evaluated once, and those results will be cached for all subsequent requests.
* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method.
* `lookup_field` - The model field that should be used to for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value.
* `lookup_url_kwarg` - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as `lookup_field`.
* `queryset` - The queryset that should be used for returning objects from this
view. Typically, you must either set this attribute, or override the
`get_queryset()` method. If you are overriding a view method, it is important
that you call `get_queryset()` instead of accessing this property directly,
as `queryset` will get evaluated once, and those results will be cached for
all subsequent requests.
* `serializer_class` - The serializer class that should be used for validating
and deserializing input, and for serializing output. Typically, you must
either set this attribute, or override the `get_serializer_class()` method.
* `lookup_field` - The model field that should be used to for performing object
lookup of individual model instances. Defaults to `'pk'`. Note that when
using hyperlinked APIs you'll need to ensure that *both* the API views *and*
the serializer classes set the lookup fields if you need to use a custom
value.
* `lookup_url_kwarg` - The URL keyword argument that should be used for object
lookup. The URL conf should include a keyword argument corresponding to this
value. If unset this defaults to using the same value as `lookup_field`.
**Pagination**:
The following attributes are used to control pagination when used with list views.
The following attributes are used to control pagination when used with list
views.
* `pagination_class` - The pagination class that should be used when paginating list results. Defaults to the same value as the `DEFAULT_PAGINATION_CLASS` setting, which is `'rest_framework.pagination.PageNumberPagination'`.
* `pagination_class` - The pagination class that should be used when paginating
list results. Defaults to the same value as the `DEFAULT_PAGINATION_CLASS`
setting, which is `'rest_framework.pagination.PageNumberPagination'`.
**Filtering**:
* `filter_backends` - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the `DEFAULT_FILTER_BACKENDS` setting.
* `filter_backends` - A list of filter backend classes that should be used for
filtering the queryset. Defaults to the same value as the
`DEFAULT_FILTER_BACKENDS` setting.
### Methods
@ -81,11 +110,16 @@ The following attributes are used to control pagination when used with list view
#### `get_queryset(self)`
Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the `queryset` attribute.
Returns the queryset that should be used for list views, and that should be
used as the base for lookups in detail views. Defaults to returning the
queryset specified by the `queryset` attribute.
This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests.
This method should always be used rather than accessing `self.queryset`
directly, as `self.queryset` gets evaluated only once, and those results are
cached for all subsequent requests.
May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.
May be overridden to provide dynamic behavior, such as returning a queryset,
that is specific to the user making the request.
For example:
@ -95,9 +129,11 @@ For example:
#### `get_object(self)`
Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset.
Returns an object instance that should be used for detail views. Defaults to
using the `lookup_field` parameter to filter the base queryset.
May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.
May be overridden to provide more complex behavior, such as object lookups
based on more than one URL kwarg.
For example:
@ -111,13 +147,16 @@ For example:
self.check_object_permissions(self.request, obj)
return obj
Note that if your API doesn't include any object level permissions, you may optionally exclude the `self.check_object_permissions`, and simply return the object from the `get_object_or_404` lookup.
Note that if your API doesn't include any object level permissions, you may
optionally exclude the `self.check_object_permissions`, and simply return the
object from the `get_object_or_404` lookup.
#### `filter_queryset(self, queryset)`
#### `filter_queryset(self, queryset)`
Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
Given a queryset, filter it with whichever filter backends are in use,
returning a new queryset.
For example:
For example:
def filter_queryset(self, queryset):
filter_backends = (CategoryFilter,)
@ -134,9 +173,12 @@ For example:
#### `get_serializer_class(self)`
Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute.
Returns the class that should be used for the serializer. Defaults to
returning the `serializer_class` attribute.
May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.
May be overridden to provide dynamic behavior, such as using different
serializers for read and write operations, or providing different serializers
to different types of users.
For example:
@ -147,24 +189,32 @@ For example:
**Save and deletion hooks**:
The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.
The following methods are provided by the mixin classes, and provide easy
overriding of the object save or deletion behavior.
* `perform_create(self, serializer)` - Called by `CreateModelMixin` when saving a new object instance.
* `perform_update(self, serializer)` - Called by `UpdateModelMixin` when saving an existing object instance.
* `perform_destroy(self, instance)` - Called by `DestroyModelMixin` when deleting an object instance.
These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.
These hooks are particularly useful for setting attributes that are implicit in
the request, but are not part of the request data. For instance, you might set
an attribute on the object based on the request user, or based on a URL keyword
argument.
def perform_create(self, serializer):
serializer.save(user=self.request.user)
These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.
These override points are also particularly useful for adding behavior that
occurs before or after saving an object, such as emailing a confirmation, or
logging the update.
def perform_update(self, serializer):
instance = serializer.save()
send_email_confirmation(user=self.request.user, modified=instance)
You can also use these hooks to provide additional validation, by raising a `ValidationError()`. This can be useful if you need some validation logic to apply at the point of database save. For example:
You can also use these hooks to provide additional validation, by raising a
`ValidationError()`. This can be useful if you need some validation logic to
apply at the point of database save. For example:
def perform_create(self, serializer):
queryset = SignupRequest.objects.filter(user=self.request.user)
@ -172,69 +222,106 @@ You can also use these hooks to provide additional validation, by raising a `Val
raise ValidationError('You have already signed up')
serializer.save(user=self.request.user)
**Note**: These methods replace the old-style version 2.x `pre_save`, `post_save`, `pre_delete` and `post_delete` methods, which are no longer available.
**Note**: These methods replace the old-style version 2.x `pre_save`,
`post_save`, `pre_delete` and `post_delete` methods, which are no longer
available.
**Other methods**:
You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`.
You won't typically need to override the following methods, although you might
need to call into them if you're writing custom views using `GenericAPIView`.
* `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys.
* `get_serializer(self, instance=None, data=None, many=False, partial=False)` - Returns a serializer instance.
* `get_paginated_response(self, data)` - Returns a paginated style `Response` object.
* `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view.
* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
* `get_serializer_context(self)` - Returns a dictionary containing any extra
context that should be supplied to the serializer. Defaults to including
`'request'`, `'view'` and `'format'` keys.
* `get_serializer(self, instance=None, data=None, many=False, partial=False)` -
Returns a serializer instance.
* `get_paginated_response(self, data)` - Returns a paginated style `Response`
object.
* `paginate_queryset(self, queryset)` - Paginate a queryset if required, either
returning a page object, or `None` if pagination is not configured for this
view.
* `filter_queryset(self, queryset)` - Given a queryset, filter it with
whichever filter backends are in use, returning a new queryset.
---
# Mixins
The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as `.get()` and `.post()`, directly. This allows for more flexible composition of behavior.
The mixin classes provide the actions that are used to provide the basic view
behavior. Note that the mixin classes provide action methods rather than
defining the handler methods, such as `.get()` and `.post()`, directly. This
allows for more flexible composition of behavior.
The mixin classes can be imported from `rest_framework.mixins`.
## ListModelMixin
Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
Provides a `.list(request, *args, **kwargs)` method, that implements listing a
queryset.
If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.
If the queryset is populated, this returns a `200 OK` response, with a
serialized representation of the queryset as the body of the response. The
response data may optionally be paginated.
## CreateModelMixin
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
Provides a `.create(request, *args, **kwargs)` method, that implements creating
and saving a new model instance.
If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value.
If an object is created this returns a `201 Created` response, with a
serialized representation of the object as the body of the response. If the
representation contains a key named `url`, then the `Location` header of the
response will be populated with that value.
If the request data provided for creating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
If the request data provided for creating the object was invalid, a `400 Bad
Request` response will be returned, with the error details as the body of the
response.
## RetrieveModelMixin
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
Provides a `.retrieve(request, *args, **kwargs)` method, that implements
returning an existing model instance in a response.
If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`.
If an object can be retrieved this returns a `200 OK` response, with a
serialized representation of the object as the body of the response. Otherwise
it will return a `404 Not Found`.
## UpdateModelMixin
Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance.
Provides a `.update(request, *args, **kwargs)` method, that implements updating
and saving an existing model instance.
Also provides a `.partial_update(request, *args, **kwargs)` method, which is similar to the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests.
Also provides a `.partial_update(request, *args, **kwargs)` method, which is
similar to the `update` method, except that all fields for the update will be
optional. This allows support for HTTP `PATCH` requests.
If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response.
If an object is updated this returns a `200 OK` response, with a serialized
representation of the object as the body of the response.
If an object is created, for example when making a `DELETE` request followed by a `PUT` request to the same URL, this returns a `201 Created` response, with a serialized representation of the object as the body of the response.
If an object is created, for example when making a `DELETE` request followed by
a `PUT` request to the same URL, this returns a `201 Created` response, with a
serialized representation of the object as the body of the response.
If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
If the request data provided for updating the object was invalid, a `400 Bad
Request` response will be returned, with the error details as the body of the
response.
## DestroyModelMixin
Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance.
Provides a `.destroy(request, *args, **kwargs)` method, that implements
deletion of an existing model instance.
If an object is deleted this returns a `204 No Content` response, otherwise it will return a `404 Not Found`.
If an object is deleted this returns a `204 No Content` response, otherwise it
will return a `404 Not Found`.
---
# Concrete View Classes
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.
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.
The view classes can be imported from `rest_framework.generics`.
@ -248,7 +335,8 @@ Extends: [GenericAPIView], [CreateModelMixin]
## ListAPIView
Used for **read-only** endpoints to represent a **collection of model instances**.
Used for **read-only** endpoints to represent a **collection of model
instances**.
Provides a `get` method handler.
@ -280,7 +368,8 @@ Extends: [GenericAPIView], [UpdateModelMixin]
## ListCreateAPIView
Used for **read-write** endpoints to represent a **collection of model instances**.
Used for **read-write** endpoints to represent a **collection of model
instances**.
Provides `get` and `post` method handlers.
@ -304,21 +393,27 @@ Extends: [GenericAPIView], [RetrieveModelMixin], [DestroyModelMixin]
## RetrieveUpdateDestroyAPIView
Used for **read-write-delete** endpoints to represent a **single model instance**.
Used for **read-write-delete** endpoints to represent a **single model
instance**.
Provides `get`, `put`, `patch` and `delete` method handlers.
Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin]
Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin],
[DestroyModelMixin]
---
# Customizing the generic views
Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed.
Often you'll want to use the existing generic views, but use some slightly
customized behavior. If you find yourself reusing some bit of customized
behavior in multiple places, you might want to refactor the behavior into a
common class that you can then just apply to any view or viewset as needed.
## Creating custom mixins
For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:
For example, if you need to lookup objects based on multiple fields in the URL
conf, you could create a mixin class like the following:
class MultipleFieldLookupMixin(object):
"""
@ -344,7 +439,9 @@ Using custom mixins is a good option if you have custom behavior that needs to b
## Creating custom base classes
If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:
If you are using a mixin across multiple views, you can take this a step
further and create your own set of base views that can then be used throughout
your project. For example:
class BaseRetrieveView(MultipleFieldLookupMixin,
generics.RetrieveAPIView):
@ -354,33 +451,50 @@ If you are using a mixin across multiple views, you can take this a step further
generics.RetrieveUpdateDestroyAPIView):
pass
Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.
Using custom base classes is a good option if you have custom behavior that
consistently needs to be repeated across a large number of views throughout
your project.
---
# PUT as create
Prior to version 3.0 the REST framework mixins treated `PUT` as either an update or a create operation, depending on if the object already existed or not.
Prior to version 3.0 the REST framework mixins treated `PUT` as either an
update or a create operation, depending on if the object already existed or
not.
Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses.
Allowing `PUT` as create operations is problematic, as it necessarily exposes
information about the existence or non-existence of objects. It's also not
obvious that transparently allowing re-creating of previously deleted instances
is necessarily a better default behavior than simply returning `404` responses.
Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious.
Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different
circumstances, but from version 3.0 onwards we now use 404 behavior as the
default, due to it being simpler and more obvious.
If you need to generic PUT-as-create behavior you may want to include something like [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views.
If you need to generic PUT-as-create behavior you may want to include something
like [this `AllowPUTAsCreateMixin`
class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to
your views.
---
# Third party packages
The following third party packages provide additional generic view implementations.
The following third party packages provide additional generic view
implementations.
## Django REST Framework bulk
The [django-rest-framework-bulk package][django-rest-framework-bulk] implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.
The [django-rest-framework-bulk package][django-rest-framework-bulk] implements
generic view mixins as well as some common concrete generic views to allow to
apply bulk operations via API requests.
## Django Rest Multiple Models
[Django Rest Multiple Models][django-rest-multiple-models] provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
[Django Rest Multiple Models][django-rest-multiple-models] provides a generic
view (and mixin) for sending multiple serialized models and/or querysets via a
single API request.
[cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views

View File

@ -2,15 +2,22 @@ source: metadata.py
# Metadata
> [The `OPTIONS`] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.
> [The `OPTIONS`] method allows a client to determine the options and/or
> requirements associated with a resource, or the capabilities of a server,
> without implying a resource action or initiating a resource retrieval.
>
> &mdash; [RFC7231, Section 4.3.7.][cite]
REST framework includes a configurable mechanism for determining how your API should respond to `OPTIONS` requests. This allows you to return API schema or other resource information.
REST framework includes a configurable mechanism for determining how your API
should respond to `OPTIONS` requests. This allows you to return API schema or
other resource information.
There are not currently any widely adopted conventions for exactly what style of response should be returned for HTTP `OPTIONS` requests, so we provide an ad-hoc style that returns some useful information.
There are not currently any widely adopted conventions for exactly what style
of response should be returned for HTTP `OPTIONS` requests, so we provide an
ad-hoc style that returns some useful information.
Here's an example response that demonstrates the information that is returned by default.
Here's an example response that demonstrates the information that is returned
by default.
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
@ -59,13 +66,18 @@ Or you can set the metadata class individually for a view:
...
})
The REST framework package only includes a single metadata class implementation, named `SimpleMetadata`. If you want to use an alternative style you'll need to implement a custom metadata class.
The REST framework package only includes a single metadata class
implementation, named `SimpleMetadata`. If you want to use an alternative style
you'll need to implement a custom metadata class.
## Creating schema endpoints
If you have specific requirements for creating schema endpoints that are accessed with regular `GET` requests, you might consider re-using the metadata API for doing so.
If you have specific requirements for creating schema endpoints that are
accessed with regular `GET` requests, you might consider re-using the metadata
API for doing so.
For example, the following additional route could be used on a viewset to provide a linkable schema endpoint.
For example, the following additional route could be used on a viewset to
provide a linkable schema endpoint.
@list_route(methods=['GET'])
def schema(self, request):
@ -73,15 +85,20 @@ For example, the following additional route could be used on a viewset to provid
data = meta.determine_metadata(request, self)
return Response(data)
There are a couple of reasons that you might choose to take this approach, including that `OPTIONS` responses [are not cacheable][no-options].
There are a couple of reasons that you might choose to take this approach,
including that `OPTIONS` responses [are not cacheable][no-options].
---
# Custom metadata classes
If you want to provide a custom metadata class you should override `BaseMetadata` and implement the `determine_metadata(self, request, view)` method.
If you want to provide a custom metadata class you should override
`BaseMetadata` and implement the `determine_metadata(self, request, view)`
method.
Useful things that you might want to do could include returning schema information, using a format such as [JSON schema][json-schema], or returning debug information to admin users.
Useful things that you might want to do could include returning schema
information, using a format such as [JSON schema][json-schema], or returning
debug information to admin users.
## Example

View File

@ -2,39 +2,55 @@ source: pagination.py
# Pagination
> Django provides a few classes that help you manage paginated data that is, data thats split across several pages, with “Previous/Next” links.
> Django provides a few classes that help you manage paginated data that is,
> data thats split across several pages, with “Previous/Next” links.
>
> &mdash; [Django documentation][cite]
REST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data.
REST framework includes support for customizable pagination styles. This allows
you to modify how large result sets are split into individual pages of data.
The pagination API can support either:
* Pagination links that are provided as part of the content of the response.
* Pagination links that are included in response headers, such as `Content-Range` or `Link`.
* Pagination links that are included in response headers, such as
`Content-Range` or `Link`.
The built-in styles currently all use links included as part of the content of the response. This style is more accessible when using the browsable API.
The built-in styles currently all use links included as part of the content of
the response. This style is more accessible when using the browsable API.
Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular `APIView`, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the `mixins.ListModelMixin` and `generics.GenericAPIView` classes for an example.
Pagination is only performed automatically if you're using the generic views or
viewsets. If you're using a regular `APIView`, you'll need to call into the
pagination API yourself to ensure you return a paginated response. See the
source code for the `mixins.ListModelMixin` and `generics.GenericAPIView`
classes for an example.
Pagination can be turned off by setting the pagination class to `None`.
## Setting the pagination style
The default pagination style may be set globally, using the `DEFAULT_PAGINATION_CLASS` and `PAGE_SIZE` setting keys. For example, to use the built-in limit/offset pagination, you would do something like this:
The default pagination style may be set globally, using the
`DEFAULT_PAGINATION_CLASS` and `PAGE_SIZE` setting keys. For example, to use
the built-in limit/offset pagination, you would do something like this:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 100
}
Note that you need to set both the pagination class, and the page size that should be used.
Note that you need to set both the pagination class, and the page size that
should be used.
You can also set the pagination class on an individual view by using the `pagination_class` attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis.
You can also set the pagination class on an individual view by using the
`pagination_class` attribute. Typically you'll want to use the same pagination
style throughout your API, although you might want to vary individual aspects
of the pagination, such as default or maximum page size, on a per-view basis.
## Modifying the pagination style
If you want to modify particular aspects of the pagination style, you'll want to override one of the pagination classes, and set the attributes that you want to change.
If you want to modify particular aspects of the pagination style, you'll want
to override one of the pagination classes, and set the attributes that you want
to change.
class LargeResultsSetPagination(PageNumberPagination):
page_size = 1000
@ -85,35 +101,56 @@ This pagination style accepts a single number page number in the request query p
#### Setup
To enable the `PageNumberPagination` style globally, use the following configuration, modifying the `PAGE_SIZE` as desired:
To enable the `PageNumberPagination` style globally, use the following
configuration, modifying the `PAGE_SIZE` as desired:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 100
}
On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `PageNumberPagination` on a per-view basis.
On `GenericAPIView` subclasses you may also set the `pagination_class`
attribute to select `PageNumberPagination` on a per-view basis.
#### Configuration
The `PageNumberPagination` class includes a number of attributes that may be overridden to modify the pagination style.
The `PageNumberPagination` class includes a number of attributes that may be
overridden to modify the pagination style.
To set these attributes you should override the `PageNumberPagination` class, and then enable your custom pagination class as above.
To set these attributes you should override the `PageNumberPagination` class,
and then enable your custom pagination class as above.
* `django_paginator_class` - The Django Paginator class to use. Default is `django.core.paginator.Paginator`, which should be fine for most use cases.
* `page_size` - A numeric value indicating the page size. If set, this overrides the `PAGE_SIZE` setting. Defaults to the same value as the `PAGE_SIZE` settings key.
* `page_query_param` - A string value indicating the name of the query parameter to use for the pagination control.
* `page_size_query_param` - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to `None`, indicating that the client may not control the requested page size.
* `max_page_size` - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if `page_size_query_param` is also set.
* `last_page_strings` - A list or tuple of string values indicating values that may be used with the `page_query_param` to request the final page in the set. Defaults to `('last',)`
* `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`.
* `django_paginator_class` - The Django Paginator class to use. Default is
`django.core.paginator.Paginator`, which should be fine for most use cases.
* `page_size` - A numeric value indicating the page size. If set, this
overrides the `PAGE_SIZE` setting. Defaults to the same value as the
`PAGE_SIZE` settings key.
* `page_query_param` - A string value indicating the name of the query
parameter to use for the pagination control.
* `page_size_query_param` - If set, this is a string value indicating the name
of a query parameter that allows the client to set the page size on a
per-request basis. Defaults to `None`, indicating that the client may not
control the requested page size.
* `max_page_size` - If set, this is a numeric value indicating the maximum
allowable requested page size. This attribute is only valid if
`page_size_query_param` is also set.
* `last_page_strings` - A list or tuple of string values indicating values that
may be used with the `page_query_param` to request the final page in the set.
Defaults to `('last',)`
* `template` - The name of a template to use when rendering pagination controls
in the browsable API. May be overridden to modify the rendering style, or set
to `None` to disable HTML pagination controls completely. Defaults to
`"rest_framework/pagination/numbers.html"`.
---
## LimitOffsetPagination
This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an
"offset" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the `page_size` in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items.
This pagination style mirrors the syntax used when looking up multiple database
records. The client includes both a "limit" and an "offset" query parameter.
The limit indicates the maximum number of items to return, and is equivalent to
the `page_size` in other styles. The offset indicates the starting position of
the query in relation to the complete set of unpaginated items.
**Request**:
@ -139,88 +176,150 @@ To enable the `LimitOffsetPagination` style globally, use the following configur
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'
}
Optionally, you may also set a `PAGE_SIZE` key. If the `PAGE_SIZE` parameter is also used then the `limit` query parameter will be optional, and may be omitted by the client.
Optionally, you may also set a `PAGE_SIZE` key. If the `PAGE_SIZE` parameter is
also used then the `limit` query parameter will be optional, and may be omitted
by the client.
On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `LimitOffsetPagination` on a per-view basis.
On `GenericAPIView` subclasses you may also set the `pagination_class`
attribute to select `LimitOffsetPagination` on a per-view basis.
#### Configuration
The `LimitOffsetPagination` class includes a number of attributes that may be overridden to modify the pagination style.
The `LimitOffsetPagination` class includes a number of attributes that may be
overridden to modify the pagination style.
To set these attributes you should override the `LimitOffsetPagination` class, and then enable your custom pagination class as above.
To set these attributes you should override the `LimitOffsetPagination` class,
and then enable your custom pagination class as above.
* `default_limit` - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the `PAGE_SIZE` settings key.
* `limit_query_param` - A string value indicating the name of the "limit" query parameter. Defaults to `'limit'`.
* `offset_query_param` - A string value indicating the name of the "offset" query parameter. Defaults to `'offset'`.
* `max_limit` - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to `None`.
* `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`.
* `default_limit` - A numeric value indicating the limit to use if one is not
provided by the client in a query parameter. Defaults to the same value as
the `PAGE_SIZE` settings key.
* `limit_query_param` - A string value indicating the name of the "limit" query
parameter. Defaults to `'limit'`.
* `offset_query_param` - A string value indicating the name of the "offset"
query parameter. Defaults to `'offset'`.
* `max_limit` - If set this is a numeric value indicating the maximum allowable
limit that may be requested by the client. Defaults to `None`.
* `template` - The name of a template to use when rendering pagination controls
in the browsable API. May be overridden to modify the rendering style, or set
to `None` to disable HTML pagination controls completely. Defaults to
`"rest_framework/pagination/numbers.html"`.
---
## CursorPagination
The cursor-based pagination presents an opaque "cursor" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions.
The cursor-based pagination presents an opaque "cursor" indicator that the
client may use to page through the result set. This pagination style only
presents forward and reverse controls, and does not allow the client to
navigate to arbitrary positions.
Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against.
Cursor based pagination requires that there is a unique, unchanging ordering of
items in the result set. This ordering might typically be a creation timestamp
on the records, as this presents a consistent ordering to paginate against.
Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits:
Cursor based pagination is more complex than other schemes. It also requires
that the result set presents a fixed ordering, and does not allow the client to
arbitrarily index into the result set. However it does provide the following
benefits:
* Provides a consistent pagination view. When used properly `CursorPagination` ensures that the client will never see the same item twice when paging through records, even when new items are being inserted by other clients during the pagination process.
* Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases.
* Provides a consistent pagination view. When used properly `CursorPagination`
ensures that the client will never see the same item twice when paging
through records, even when new items are being inserted by other clients
during the pagination process.
* Supports usage with very large datasets. With extremely large datasets
pagination using offset-based pagination styles may become inefficient or
unusable. Cursor based pagination schemes instead have fixed-time properties,
and do not slow down as the dataset size increases.
#### Details and limitations
Proper use of cursor based pagination requires a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by `"-created"`. This assumes that **there must be a 'created' timestamp field** on the model instances, and will present a "timeline" style paginated view, with the most recently added items first.
Proper use of cursor based pagination requires a little attention to detail.
You'll need to think about what ordering you want the scheme to be applied
against. The default is to order by `"-created"`. This assumes that **there
must be a 'created' timestamp field** on the model instances, and will present
a "timeline" style paginated view, with the most recently added items first.
You can modify the ordering by overriding the `'ordering'` attribute on the pagination class, or by using the `OrderingFilter` filter class together with `CursorPagination`. When used with `OrderingFilter` you should strongly consider restricting the fields that the user may order by.
You can modify the ordering by overriding the `'ordering'` attribute on the
pagination class, or by using the `OrderingFilter` filter class together with
`CursorPagination`. When used with `OrderingFilter` you should strongly
consider restricting the fields that the user may order by.
Proper usage of cursor pagination should have an ordering field that satisfies the following:
Proper usage of cursor pagination should have an ordering field that satisfies
the following:
* Should be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation.
* Should be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart "position plus offset" style that allows it to properly support not-strictly-unique values as the ordering.
* Should be an unchanging value, such as a timestamp, slug, or other field that
is only set once, on creation.
* Should be unique, or nearly unique. Millisecond precision timestamps are a
good example. This implementation of cursor pagination uses a smart "position
plus offset" style that allows it to properly support not-strictly-unique
values as the ordering.
* Should be a non-nullable value that can be coerced to a string.
* The field should have a database index.
Using an ordering field that does not satisfy these constraints will generally still work, but you'll be losing some of the benefits of cursor pagination.
Using an ordering field that does not satisfy these constraints will generally
still work, but you'll be losing some of the benefits of cursor pagination.
For more technical details on the implementation we use for cursor pagination, the ["Building cursors for the Disqus API"][disqus-cursor-api] blog post gives a good overview of the basic approach.
For more technical details on the implementation we use for cursor pagination,
the ["Building cursors for the Disqus API"][disqus-cursor-api] blog post gives
a good overview of the basic approach.
#### Setup
To enable the `CursorPagination` style globally, use the following configuration, modifying the `PAGE_SIZE` as desired:
To enable the `CursorPagination` style globally, use the following
configuration, modifying the `PAGE_SIZE` as desired:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',
'PAGE_SIZE': 100
}
On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `CursorPagination` on a per-view basis.
On `GenericAPIView` subclasses you may also set the `pagination_class`
attribute to select `CursorPagination` on a per-view basis.
#### Configuration
The `CursorPagination` class includes a number of attributes that may be overridden to modify the pagination style.
The `CursorPagination` class includes a number of attributes that may be
overridden to modify the pagination style.
To set these attributes you should override the `CursorPagination` class, and then enable your custom pagination class as above.
To set these attributes you should override the `CursorPagination` class, and
then enable your custom pagination class as above.
* `page_size` = A numeric value indicating the page size. If set, this overrides the `PAGE_SIZE` setting. Defaults to the same value as the `PAGE_SIZE` settings key.
* `cursor_query_param` = A string value indicating the name of the "cursor" query parameter. Defaults to `'cursor'`.
* `ordering` = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: `ordering = 'slug'`. Defaults to `-created`. This value may also be overridden by using `OrderingFilter` on the view.
* `template` = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/previous_and_next.html"`.
* `page_size` = A numeric value indicating the page size. If set, this
overrides the `PAGE_SIZE` setting. Defaults to the same value as the
`PAGE_SIZE` settings key.
* `cursor_query_param` = A string value indicating the name of the "cursor"
query parameter. Defaults to `'cursor'`.
* `ordering` = This should be a string, or list of strings, indicating the
field against which the cursor based pagination will be applied. For example:
`ordering = 'slug'`. Defaults to `-created`. This value may also be
overridden by using `OrderingFilter` on the view.
* `template` = The name of a template to use when rendering pagination controls
in the browsable API. May be overridden to modify the rendering style, or set
to `None` to disable HTML pagination controls completely. Defaults to
`"rest_framework/pagination/previous_and_next.html"`.
---
# Custom pagination styles
To create a custom pagination serializer class you should subclass `pagination.BasePagination` and override the `paginate_queryset(self, queryset, request, view=None)` and `get_paginated_response(self, data)` methods:
To create a custom pagination serializer class you should subclass
`pagination.BasePagination` and override the `paginate_queryset(self, queryset,
request, view=None)` and `get_paginated_response(self, data)` methods:
* The `paginate_queryset` method is passed the initial queryset and should return an iterable object that contains only the data in the requested page.
* The `get_paginated_response` method is passed the serialized page data and should return a `Response` instance.
* The `paginate_queryset` method is passed the initial queryset and should
return an iterable object that contains only the data in the requested page.
* The `get_paginated_response` method is passed the serialized page data and
should return a `Response` instance.
Note that the `paginate_queryset` method may set state on the pagination instance, that may later be used by the `get_paginated_response` method.
Note that the `paginate_queryset` method may set state on the pagination
instance, that may later be used by the `get_paginated_response` method.
## Example
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
Suppose we want to replace the default pagination output style with a modified
format that includes the next and previous links under in a nested 'links'
key. We could specify a custom pagination class like so:
class CustomPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
@ -240,11 +339,15 @@ We'd then need to setup the custom class in our configuration:
'PAGE_SIZE': 100
}
Note that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an `OrderedDict` when constructing the body of paginated responses, but this is optional.
Note that if you care about how the ordering of keys is displayed in responses
in the browsable API you might choose to use an `OrderedDict` when constructing
the body of paginated responses, but this is optional.
## Header based pagination
Let's modify the built-in `PageNumberPagination` style, so that instead of include the pagination links in the body of the response, we'll instead include a `Link` header, in a [similar style to the GitHub API][github-link-pagination].
Let's modify the built-in `PageNumberPagination` style, so that instead of
include the pagination links in the body of the response, we'll instead include
a `Link` header, in a [similar style to the GitHub API][github-link-pagination].
class LinkHeaderPagination(pagination.PageNumberPagination):
def get_paginated_response(self, data):
@ -274,7 +377,9 @@ To have your custom pagination class be used by default, use the `DEFAULT_PAGINA
'PAGE_SIZE': 100
}
API responses for list endpoints will now include a `Link` header, instead of including the pagination links as part of the body of the response, for example:
API responses for list endpoints will now include a `Link` header, instead of
including the pagination links as part of the body of the response, for
example:
---
@ -286,24 +391,40 @@ API responses for list endpoints will now include a `Link` header, instead of in
# HTML pagination controls
By default using the pagination classes will cause HTML pagination controls to be displayed in the browsable API. There are two built-in display styles. The `PageNumberPagination` and `LimitOffsetPagination` classes display a list of page numbers with previous and next controls. The `CursorPagination` class displays a simpler style that only displays a previous and next control.
By default using the pagination classes will cause HTML pagination controls to
be displayed in the browsable API. There are two built-in display styles. The
`PageNumberPagination` and `LimitOffsetPagination` classes display a list of
page numbers with previous and next controls. The `CursorPagination` class
displays a simpler style that only displays a previous and next control.
## Customizing the controls
You can override the templates that render the HTML pagination controls. The two built-in styles are:
You can override the templates that render the HTML pagination controls. The
two built-in styles are:
* `rest_framework/pagination/numbers.html`
* `rest_framework/pagination/previous_and_next.html`
Providing a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes.
Providing a template with either of these paths in a global template directory
will override the default rendering for the relevant pagination classes.
Alternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting `template = None` as an attribute on the class. You'll then need to configure your `DEFAULT_PAGINATION_CLASS` settings key to use your custom class as the default pagination style.
Alternatively you can disable HTML pagination controls completely by
subclassing on of the existing classes, setting `template = None` as an
attribute on the class. You'll then need to configure your
`DEFAULT_PAGINATION_CLASS` settings key to use your custom class as the default
pagination style.
#### Low-level API
The low-level API for determining if a pagination class should display the controls or not is exposed as a `display_page_controls` attribute on the pagination instance. Custom pagination classes should be set to `True` in the `paginate_queryset` method if they require the HTML pagination controls to be displayed.
The low-level API for determining if a pagination class should display the
controls or not is exposed as a `display_page_controls` attribute on the
pagination instance. Custom pagination classes should be set to `True` in the
`paginate_queryset` method if they require the HTML pagination controls to be
displayed.
The `.to_html()` and `.get_html_context()` methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered.
The `.to_html()` and `.get_html_context()` methods may also be overridden in a
custom pagination class in order to further customize how the controls are
rendered.
---
@ -313,7 +434,9 @@ The following third party packages are also available.
## DRF-extensions
The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin` mixin class][paginate-by-max-mixin] that allows your API clients to specify `?page_size=max` to obtain the maximum allowed page size.
The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin`
mixin class][paginate-by-max-mixin] that allows your API clients to specify
`?page_size=max` to obtain the maximum allowed page size.
[cite]: https://docs.djangoproject.com/en/dev/topics/pagination/
[github-link-pagination]: https://developer.github.com/guides/traversing-with-pagination/

View File

@ -8,25 +8,38 @@ sending more complex data than simple forms
>
> &mdash; 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.
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 `request.data` 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.
The set of valid parsers for a view is always defined as a list of classes.
When `request.data` 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.
---
**Note**: When developing client applications always remember to make sure you're setting the `Content-Type` header when sending data in an HTTP request.
**Note**: When developing client applications always remember to make sure
you're setting the `Content-Type` header when sending data in an HTTP request.
If you don't set the content type, most clients will default to using `'application/x-www-form-urlencoded'`, which may not be what you wanted.
If you don't set the content type, most clients will default to using
`'application/x-www-form-urlencoded'`, which may not be what you wanted.
As an example, if you are sending `json` encoded data using jQuery with the [.ajax() method][jquery-ajax], you should make sure to include the `contentType: 'application/json'` setting.
As an example, if you are sending `json` encoded data using jQuery with the
[.ajax() method][jquery-ajax], you should make sure to include the
`contentType: 'application/json'` setting.
---
## 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 only requests with `JSON` content, instead of the default of JSON or form data.
The default set of parsers may be set globally, using the
`DEFAULT_PARSER_CLASSES` setting. For example, the following settings would
allow only requests with `JSON` content, instead of the default of JSON or form
data.
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
@ -34,8 +47,8 @@ The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSE
)
}
You can also set the parsers used for an individual view, or viewset,
using the `APIView` class-based views.
You can also set the parsers used for an individual view, or viewset, using the
`APIView` class-based views.
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
@ -77,33 +90,46 @@ Parses `JSON` request content.
Parses HTML form content. `request.data` will be populated with a `QueryDict` of data.
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form 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
Parses multipart HTML form content, which supports file uploads. Both `request.data` will be populated with a `QueryDict`.
Parses multipart HTML form content, which supports file uploads. Both
`request.data` 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.
You will typically want to use both `FormParser` and `MultiPartParser` together
in order to fully support HTML form data.
**.media_type**: `multipart/form-data`
## FileUploadParser
Parses raw file upload content. The `request.data` property will be a dictionary with a single key `'file'` containing the uploaded file.
Parses raw file upload content. The `request.data` property will be a
dictionary with a single key `'file'` containing the uploaded file.
If the view used with `FileUploadParser` is called with a `filename` URL keyword argument, then that argument will be used as the filename.
If the view used with `FileUploadParser` is called with a `filename` URL
keyword argument, then that argument will be used as the filename.
If it is called without a `filename` URL keyword argument, then the client must set the filename in the `Content-Disposition` HTTP header. For example `Content-Disposition: attachment; filename=upload.jpg`.
If it is called without a `filename` URL keyword argument, then the client must
set the filename in the `Content-Disposition` HTTP header. For example
`Content-Disposition: attachment; filename=upload.jpg`.
**.media_type**: `*/*`
##### Notes:
* The `FileUploadParser` is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the `MultiPartParser` parser instead.
* Since this parser's `media_type` matches any content type, `FileUploadParser` should generally be the only parser set on an API view.
* `FileUploadParser` respects Django's standard `FILE_UPLOAD_HANDLERS` setting, and the `request.upload_handlers` attribute. See the [Django documentation][upload-handlers] for more details.
* The `FileUploadParser` is for usage with native clients that can upload the
file as a raw data request. For web-based uploads, or for native clients
with multipart upload support, you should use the `MultiPartParser` parser
instead.
* Since this parser's `media_type` matches any content type, `FileUploadParser`
should generally be the only parser set on an API view.
* `FileUploadParser` respects Django's standard `FILE_UPLOAD_HANDLERS` setting,
and the `request.upload_handlers` attribute. See the [Django documentation][upload-handlers]
for more details.
##### Basic usage example:
@ -128,9 +154,12 @@ If it is called without a `filename` URL keyword argument, then the client must
# 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.
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 method should return the data that will be used to populate the
`request.data` property.
The arguments passed to `.parse()` are:
@ -142,17 +171,22 @@ A stream-like object representing the body of the request.
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"`.
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.
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`.
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.
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):
"""
@ -174,7 +208,9 @@ The following third party packages are also available.
## YAML
[REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
[REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and
rendering support. It was previously included directly in the REST framework
package, and is now instead supported as a third-party package.
#### Installation & configuration
@ -195,7 +231,9 @@ Modify your REST framework settings.
## XML
[REST Framework XML][rest-framework-xml] provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
[REST Framework XML][rest-framework-xml] provides a simple informal XML format.
It was previously included directly in the REST framework package, and is now
instead supported as a third-party package.
#### Installation & configuration
@ -216,11 +254,17 @@ Modify your REST framework settings.
## MessagePack
[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
[MessagePack][messagepack] is a fast, efficient binary serialization format.
[Juan Riaza][juanriaza] maintains the
[djangorestframework-msgpack][djangorestframework-msgpack] package which
provides MessagePack renderer and parser support for REST framework.
## CamelCase JSON
[djangorestframework-camel-case] provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by [Vitaly Babiy][vbabiy].
[djangorestframework-camel-case] provides camel case JSON renderers and parsers
for REST framework. This allows serializers to use Python-style underscored
field names, but be exposed in the API as Javascript-style camel case
field names. It is maintained by [Vitaly Babiy][vbabiy].
[jquery-ajax]: http://api.jquery.com/jQuery.ajax/
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion

View File

@ -2,44 +2,72 @@ source: permissions.py
# Permissions
> Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.
> Authentication or identification by itself is not usually sufficient to gain
> access to information or code. For that, the entity requesting access must
> have authorization.
>
> &mdash; [Apple Developer Documentation][cite]
Together with [authentication] and [throttling], permissions determine whether 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.
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.
Permissions are used to grant or deny access different classes of users to different parts of the API.
Permissions are used to grant or deny access different classes of users to
different parts of the API.
The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds the `IsAuthenticated` class in REST framework.
The simplest style of permission would be to allow access to any authenticated
user, and deny access to any unauthenticated user. This corresponds the
`IsAuthenticated` class in REST framework.
A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the `IsAuthenticatedOrReadOnly` class in REST framework.
A slightly less strict style of permission would be to allow full access to
authenticated users, but allow read-only access to unauthenticated users. This
corresponds to the `IsAuthenticatedOrReadOnly` class in REST framework.
## How permissions are determined
Permissions in REST framework are always defined as a list of permission classes.
Permissions in REST framework are always defined as a list of permission
classes.
Before running the main body of the view each permission in the list is checked.
If any permission check fails an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run.
Before running the main body of the view each permission in the list is
checked. If any permission check fails an `exceptions.PermissionDenied` or
`exceptions.NotAuthenticated` exception will be raised, and the main body of
the view will not run.
When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:
When the permissions checks fail either a "403 Forbidden" or a "401
Unauthorized" response will be returned, according to the following rules:
* The request was successfully authenticated, but permission was denied. *&mdash; An HTTP 403 Forbidden response will be returned.*
* The request was not successfully authenticated, and the highest priority authentication class *does not* use `WWW-Authenticate` headers. *&mdash; An HTTP 403 Forbidden response will be returned.*
* The request was not successfully authenticated, and the highest priority authentication class *does* use `WWW-Authenticate` headers. *&mdash; An HTTP 401 Unauthorized response, with an appropriate `WWW-Authenticate` header will be returned.*
* The request was successfully authenticated, but permission was denied.
*&mdash; An HTTP 403 Forbidden response will be returned.*
* The request was not successfully authenticated, and the highest priority
authentication class *does not* use `WWW-Authenticate` headers. *&mdash; An
HTTP 403 Forbidden response will be returned.*
* The request was not successfully authenticated, and the highest priority
authentication class *does* use `WWW-Authenticate` headers. *&mdash; An HTTP
401 Unauthorized response, with an appropriate `WWW-Authenticate` header will
be returned.*
## Object level permissions
REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance.
REST framework permissions also support object-level permissioning. Object
level permissions are used to determine if a user should be allowed to act on a
particular object, which will typically be a model instance.
Object level permissions are run by REST framework's generic views when `.get_object()` is called.
As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object.
Object level permissions are run by REST framework's generic views when
`.get_object()` is called. As with view level permissions, an
`exceptions.PermissionDenied` exception will be raised if the user is not
allowed to act on the given object.
If you're writing your own views and want to enforce object level permissions,
or if you override the `get_object` method on a generic view, then you'll need to explicitly call the `.check_object_permissions(request, obj)` method on the view at the point at which you've retrieved the object.
or if you override the `get_object` method on a generic view, then you'll need
to explicitly call the `.check_object_permissions(request, obj)` method on the
view at the point at which you've retrieved the object.
This will either raise a `PermissionDenied` or `NotAuthenticated` exception, or simply return if the view has the appropriate permissions.
This will either raise a `PermissionDenied` or `NotAuthenticated` exception, or
simply return if the view has the appropriate permissions.
For example:
@ -50,9 +78,13 @@ For example:
#### Limitations of object level permissions
For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects.
For performance reasons the generic views will not automatically apply object
level permissions to each instance in a queryset when returning a list of
objects.
Often when you're using object level permissions you'll also want to [filter the queryset][filtering] appropriately, to ensure that users only have visibility onto instances that they are permitted to view.
Often when you're using object level permissions you'll also want to [filter
the queryset][filtering] appropriately, to ensure that users only have
visibility onto instances that they are permitted to view.
## Setting the permission policy
@ -100,7 +132,9 @@ Or, if you're using the `@api_view` decorator with function based views.
}
return Response(content)
__Note:__ when you set new permission classes through class attribute or decorators you're telling the view to ignore the default list set over the __settings.py__ file.
__Note:__ when you set new permission classes through class attribute or
decorators you're telling the view to ignore the default list set over the
__settings.py__ file.
---
@ -108,67 +142,102 @@ __Note:__ when you set new permission classes through class attribute or decorat
## AllowAny
The `AllowAny` permission class will allow unrestricted access, **regardless of if the request was authenticated or unauthenticated**.
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.
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.
The `IsAuthenticated` permission class will deny permission to any
unauthenticated user, and allow permission otherwise.
This permission is suitable if you want your API to only be accessible to registered users.
This permission is suitable if you want your API to only be accessible to
registered users.
## 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 if you want your API to only be accessible to a subset of trusted administrators.
This permission is suitable if you want your API to only be accessible to a
subset of trusted administrators.
## IsAuthenticatedOrReadOnly
The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`.
The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any
request. Requests for unauthorised users will only be permitted if the request
method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`.
This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.
This permission is suitable if you want to your API to allow read permissions
to anonymous users, and only allow write permissions to authenticated users.
## DjangoModelPermissions
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property set. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned.
This permission class ties into Django's standard `django.contrib.auth` [model
permissions][contribauth]. This permission must only be applied to views that
have a `.queryset` property set. Authorization will only be granted if the user
*is authenticated* and has the *relevant model permissions* assigned.
* `POST` requests require the user to have the `add` permission on the model.
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
* `DELETE` requests require the user to have the `delete` permission on the model.
* `PUT` and `PATCH` requests require the user to have the `change` permission
on the model.
* `DELETE` requests require the user to have the `delete` permission on the
model.
The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
The default behaviour can also be overridden to support custom model
permissions. For example, you might want to include a `view` model permission
for `GET` requests.
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
To use custom model permissions, override `DjangoModelPermissions` and set the
`.perms_map` property. Refer to the source code for details.
#### Using with views that do not include a `queryset` attribute.
If you're using this permission with a view that uses an overridden `get_queryset()` method there may not be a `queryset` attribute on the view. In this case we suggest also marking the view with a sentinel queryset, so that this class can determine the required permissions. For example:
If you're using this permission with a view that uses an overridden
`get_queryset()` method there may not be a `queryset` attribute on the view. In
this case we suggest also marking the view with a sentinel queryset, so that
this class can determine the required permissions. For example:
queryset = User.objects.none() # Required for DjangoModelPermissions
## DjangoModelPermissionsOrAnonReadOnly
Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API.
Similar to `DjangoModelPermissions`, but also allows unauthenticated users to
have read-only access to the API.
## DjangoObjectPermissions
This permission class ties into Django's standard [object permissions framework][objectpermissions] that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as [django-guardian][guardian].
This permission class ties into Django's standard [object permissions
framework][objectpermissions] that allows per-object permissions on models. In
order to use this permission class, you'll also need to add a permission
backend that supports object-level permissions, such as
[django-guardian][guardian].
As with `DjangoModelPermissions`, this permission must only be applied to views that have a `.queryset` property or `.get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant per-object permissions* and *relevant model permissions* assigned.
As with `DjangoModelPermissions`, this permission must only be applied to views
that have a `.queryset` property or `.get_queryset()` method. Authorization
will only be granted if the user *is authenticated* and has the *relevant
per-object permissions* and *relevant model permissions* assigned.
* `POST` requests require the user to have the `add` permission on the model instance.
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model instance.
* `DELETE` requests require the user to have the `delete` permission on the model instance.
Note that `DjangoObjectPermissions` **does not** require the `django-guardian` package, and should support other object-level backends equally well.
Note that `DjangoObjectPermissions` **does not** require the `django-guardian`
package, and should support other object-level backends equally well.
As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoModelPermissions` and setting the `.perms_map` property. Refer to the source code for details.
As with `DjangoModelPermissions` you can use custom model permissions by
overriding `DjangoModelPermissions` and setting the `.perms_map` property.
Refer to the source code for details.
---
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests, you'll want to consider also adding the `DjangoObjectPermissionsFilter` class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions.
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and
`OPTIONS` requests, you'll want to consider also adding the
`DjangoObjectPermissionsFilter` class to ensure that list endpoints only return
results including objects for which the user has appropriate view permissions.
---
@ -176,14 +245,17 @@ As with `DjangoModelPermissions` you can use custom model permissions by overrid
# Custom permissions
To implement a custom permission, override `BasePermission` and implement either, or both, of the following methods:
To implement a custom permission, override `BasePermission` and implement
either, or both, of the following methods:
* `.has_permission(self, request, view)`
* `.has_object_permission(self, request, view, obj)`
The methods should return `True` if the request should be granted access, and `False` otherwise.
If you need to test if a request is a read operation or a write operation, you should check the request method against the constant `SAFE_METHODS`, which is a tuple containing `'GET'`, `'OPTIONS'` and `'HEAD'`. For example:
If you need to test if a request is a read operation or a write operation, you
should check the request method against the constant `SAFE_METHODS`, which is a
tuple containing `'GET'`, `'OPTIONS'` and `'HEAD'`. For example:
if request.method in permissions.SAFE_METHODS:
# Check permissions for read-only request
@ -192,23 +264,32 @@ If you need to test if a request is a read operation or a write operation, you s
---
**Note**: The instance-level `has_object_permission` method will only be called if the view-level `has_permission` checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call `.check_object_permissions(request, obj)`. If you are using the generic views then this will be handled for you by default.
**Note**: The instance-level `has_object_permission` method will only be called
if the view-level `has_permission` checks have already passed. Also note that
in order for the instance-level checks to run, the view code should
explicitly call `.check_object_permissions(request, obj)`. If you are
using the generic views then this will be handled for you by default.
---
Custom permissions will raise a `PermissionDenied` exception if the test fails. To change the error message associated with the exception, implement a `message` attribute directly on your custom permission. Otherwise the `default_detail` attribute from `PermissionDenied` will be used.
Custom permissions will raise a `PermissionDenied` exception if the test fails.
To change the error message associated with the exception, implement a
`message` attribute directly on your custom permission. Otherwise the
`default_detail` attribute from `PermissionDenied` will be used.
from rest_framework import permissions
class CustomerAccessPermission(permissions.BasePermission):
message = 'Adding customers not allowed.'
def has_permission(self, request, view):
...
## Examples
The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted.
The following is an example of a permission class that checks the incoming
request's IP address against a blacklist, and denies the request if the IP has
been blacklisted.
from rest_framework import permissions
@ -222,7 +303,9 @@ The following is an example of a permission class that checks the incoming reque
blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists()
return not blacklisted
As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example:
As well as global permissions, that are run against all incoming requests, you
can also create object-level permissions, that are only run against operations
that affect a particular object instance. For example:
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
@ -239,9 +322,17 @@ As well as global permissions, that are run against all incoming requests, you c
# Instance must have an attribute named `owner`.
return obj.owner == request.user
Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling `self.check_object_permissions(request, obj)` from the view once you have the object instance. This call will raise an appropriate `APIException` if any object-level permission checks fail, and will otherwise simply return.
Note that the generic views will check the appropriate object level
permissions, but if you're writing your own custom views, you'll need to make
sure you check the object level permission checks yourself. You can do so by
calling `self.check_object_permissions(request, obj)` from the view once you
have the object instance. This call will raise an appropriate `APIException`
if any object-level permission checks fail, and will otherwise simply return.
Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the [filtering documentation][filtering] for more details.
Also note that the generic views will only check the object-level permissions
for views that retrieve a single model instance. If you require object-level
filtering of list views, you'll need to filter the queryset separately.
See the [filtering documentation][filtering] for more details.
---
@ -251,19 +342,30 @@ The following third party packages are also available.
## Composed Permissions
The [Composed Permissions][composed-permissions] package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components.
The [Composed Permissions][composed-permissions] package provides a simple way
to define complex and multi-depth (with logic operators) permission objects,
using small and reusable components.
## REST Condition
The [REST Condition][rest-condition] package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators.
The [REST Condition][rest-condition] package is another extension for building
complex permissions in a simple and convenient way. The extension allows you
to combine permissions with logical operators.
## DRY Rest Permissions
The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrive per user.
The [DRY Rest Permissions][dry-rest-permissions] package provides the ability
to define different permissions for individual default and custom actions. This
package is made for apps with permissions that are derived from relationships
defined in the app's data model. It also supports permission checks being
returned to a client app through the API's serializer. Additionally it supports
adding permissions to the default and custom list actions to restrict the data
they retrive per user.
## Django Rest Framework Roles
The [Django Rest Framework Roles][django-rest-framework-roles] package makes it easier to parameterize your API over multiple types of users.
The [Django Rest Framework Roles][django-rest-framework-roles] package makes it
easier to parameterize your API over multiple types of users.
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
[authentication]: authentication.md

View File

@ -8,19 +8,29 @@ source: relations.py
> &mdash; [Linus Torvalds][cite]
Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`.
Relational fields are used to represent model relationships. They can be
applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships,
as well as to reverse relationships, and custom relationships such as
`GenericForeignKey`.
---
**Note:** The relational fields are declared in `relations.py`, but by convention you should import them from the `serializers` module, using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
**Note:** The relational fields are declared in `relations.py`, but by
convention you should import them from the `serializers` module, using `from
rest_framework import serializers` and refer to fields as
`serializers.<FieldName>`.
---
#### Inspecting relationships.
When using the `ModelSerializer` class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style.
When using the `ModelSerializer` class, serializer fields and relationships
will be automatically generated for you. Inspecting these automatically
generated fields can be a useful tool for determining how to customize the
relationship style.
To do so, open the Django shell, using `python manage.py shell`, then import the serializer class, instantiate it, and print the object representation…
To do so, open the Django shell, using `python manage.py shell`, then import
the serializer class, instantiate it, and print the object representation…
>>> from myapp.serializers import AccountSerializer
>>> serializer = AccountSerializer()
@ -32,7 +42,9 @@ To do so, open the Django shell, using `python manage.py shell`, then import the
# API Reference
In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album.
In order to explain the various types of relational fields, we'll use a couple
of simple models for our examples. Our models will be for music albums, and
the tracks listed on each album.
class Album(models.Model):
album_name = models.CharField(max_length=100)
@ -53,7 +65,8 @@ In order to explain the various types of relational fields, we'll use a couple o
## StringRelatedField
`StringRelatedField` may be used to represent the target of the relationship using its `__unicode__` method.
`StringRelatedField` may be used to represent the target of the relationship
using its `__unicode__` method.
For example, the following serializer.
@ -113,15 +126,22 @@ By default this field is read-write, although you can change this behavior using
**Arguments**:
* `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`.
* `many` - If applied to a to-many relationship, you should set this argument to `True`.
* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`.
* `pk_field` - Set to a field to control serialization/deserialization of the primary key's value. For example, `pk_field=UUIDField(format='hex')` would serialize a UUID primary key into its compact hex representation.
* `queryset` - The queryset used for model instance lookups when validating the
field input. Relationships must either set a queryset explicitly, or set
`read_only=True`.
* `many` - If applied to a to-many relationship, you should set this argument
to `True`.
* `allow_null` - If set to `True`, the field will accept values of `None` or
the empty string for nullable relationships. Defaults to `False`.
* `pk_field` - Set to a field to control serialization/deserialization of the
primary key's value. For example, `pk_field=UUIDField(format='hex')` would
serialize a UUID primary key into its compact hex representation.
## HyperlinkedRelatedField
`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink.
`HyperlinkedRelatedField` may be used to represent the target of the
relationship using a hyperlink.
For example, the following serializer:
@ -153,27 +173,45 @@ By default this field is read-write, although you can change this behavior using
---
**Note**: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the `lookup_field` and `lookup_url_kwarg` arguments.
**Note**: This field is designed for objects that map to a URL that accepts a
single URL keyword argument, as set using the `lookup_field` and
`lookup_url_kwarg` arguments.
This is suitable for URLs that contain a single primary key or slug argument as part of the URL.
This is suitable for URLs that contain a single primary key or slug argument as
part of the URL.
If you require more complex hyperlinked representation you'll need to customize the field, as described in the [custom hyperlinked fields](#custom-hyperlinked-fields) section, below.
If you require more complex hyperlinked representation you'll need to customize
the field, as described in the [custom hyperlinked
fields](#custom-hyperlinked-fields) section, below.
---
**Arguments**:
* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `<modelname>-detail`. **required**.
* `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`.
* `many` - If applied to a to-many relationship, you should set this argument to `True`.
* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`.
* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
* `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as `lookup_field`.
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
* `view_name` - The view name that should be used as the target of the
relationship. If you're using [the standard router classes][routers] this
will be a string with the format `<modelname>-detail`. **required**.
* `queryset` - The queryset used for model instance lookups when validating the
field input. Relationships must either set a queryset explicitly, or set
`read_only=True`.
* `many` - If applied to a to-many relationship, you should set this argument
to `True`.
* `allow_null` - If set to `True`, the field will accept values of `None` or
the empty string for nullable relationships. Defaults to `False`.
* `lookup_field` - The field on the target that should be used for the lookup.
Should correspond to a URL keyword argument on the referenced view. Default
is `'pk'`.
* `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf
that corresponds to the lookup field. Defaults to using the same value as
`lookup_field`.
* `format` - If using format suffixes, hyperlinked fields will use the same
format suffix for the target unless overridden by using the `format`
argument.
## SlugRelatedField
`SlugRelatedField` may be used to represent the target of the relationship using a field on the target.
`SlugRelatedField` may be used to represent the target of the relationship
using a field on the target.
For example, the following serializer:
@ -201,20 +239,30 @@ Would serialize to a representation like this:
]
}
By default this field is read-write, although you can change this behavior using the `read_only` flag.
By default this field is read-write, although you can change this behavior
using the `read_only` flag.
When using `SlugRelatedField` as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with `unique=True`.
When using `SlugRelatedField` as a read-write field, you will normally want to
ensure that the slug field corresponds to a model field with `unique=True`.
**Arguments**:
* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. **required**
* `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`.
* `many` - If applied to a to-many relationship, you should set this argument to `True`.
* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`.
* `slug_field` - The field on the target that should be used to represent it.
This should be a field that uniquely identifies any given instance. For
example, `username`. **required**
* `queryset` - The queryset used for model instance lookups when validating the
field input. Relationships must either set a queryset explicitly, or set
`read_only=True`.
* `many` - If applied to a to-many relationship, you should set this argument
to `True`.
* `allow_null` - If set to `True`, the field will accept values of `None` or
the empty string for nullable relationships. Defaults to `False`.
## HyperlinkedIdentityField
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
This field can be applied as an identity relationship, such as the `'url'`
field on a HyperlinkedModelSerializer. It can also be used for an attribute
on the object. For example, the following serializer:
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
@ -235,10 +283,18 @@ This field is always read-only.
**Arguments**:
* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `<model_name>-detail`. **required**.
* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
* `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as `lookup_field`.
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
* `view_name` - The view name that should be used as the target of the
relationship. If you're using [the standard router classes][routers] this
will be a string with the format `<model_name>-detail`. **required**.
* `lookup_field` - The field on the target that should be used for the lookup.
Should correspond to a URL keyword argument on the referenced view. Default
is `'pk'`.
* `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf
that corresponds to the lookup field. Defaults to using the same value as
`lookup_field`.
* `format` - If using format suffixes, hyperlinked fields will use the same
format suffix for the target unless overridden by using the `format`
argument.
---
@ -246,7 +302,8 @@ This field is always read-only.
Nested relationships can be expressed by using serializers as fields.
If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field.
If the field is used to represent a to-many relationship, you should add the
`many=True` flag to the serializer field.
## Example
@ -288,7 +345,10 @@ Would serialize to a nested representation like this:
# Writable nested serializers
By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create `create()` and/or `update()` methods in order to explicitly specify how the child relationships should be saved.
By default nested serializers are read-only. If you want to support
write-operations to a nested serializer field you'll need to create `create()`
and/or `update()` methods in order to explicitly specify how the child
relationships should be saved.
class TrackSerializer(serializers.ModelSerializer):
class Meta:
@ -326,15 +386,23 @@ By default nested serializers are read-only. If you want to support write-operat
# Custom relational fields
To implement a custom relational field, you should override `RelatedField`, and implement the `.to_representation(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. The `value` argument will typically be a model instance.
To implement a custom relational field, you should override `RelatedField`, and
implement the `.to_representation(self, value)` method. This method takes the
target of the field as the `value` argument, and should return the
representation that should be used to serialize the target. The `value`
argument will typically be a model instance.
If you want to implement a read-write relational field, you must also implement the `.to_internal_value(self, data)` method.
If you want to implement a read-write relational field, you must also implement
the `.to_internal_value(self, data)` method.
To provide a dynamic queryset based on the `context`, you can also override `.get_queryset(self)` instead of specifying `.queryset` on the class or when initializing the field.
To provide a dynamic queryset based on the `context`, you can also override
`.get_queryset(self)` instead of specifying `.queryset` on the class or when
initializing the field.
## Example
For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration.
For example, we could define a relational field to serialize a track to a
custom string representation, using its ordering, title, and duration.
import time
@ -367,22 +435,29 @@ This custom field would then serialize to the following representation.
# Custom hyperlinked fields
In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field.
In some cases you may need to customize the behavior of a hyperlinked field, in
order to represent URLs that require more than a single lookup field.
You can achieve this by overriding `HyperlinkedRelatedField`. There are two methods that may be overridden:
You can achieve this by overriding `HyperlinkedRelatedField`. There are two
methods that may be overridden:
**get_url(self, obj, view_name, request, format)**
The `get_url` method is used to map the object instance to its URL representation.
The `get_url` method is used to map the object instance to its URL
representation.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field` attributes
are not configured to correctly match the URL conf.
**get_object(self, queryset, view_name, view_args, view_kwargs)**
If you want to support a writable hyperlinked field then you'll also want to override `get_object`, in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method.
If you want to support a writable hyperlinked field then you'll also want to
override `get_object`, in order to map incoming URLs back to the object they
represent. For read-only hyperlinked fields there is no need to override this
method.
The return value of this method should the object that corresponds to the matched URL conf arguments.
The return value of this method should the object that corresponds to the
matched URL conf arguments.
May raise an `ObjectDoesNotExist` exception.
@ -418,9 +493,12 @@ In this case we'd need to override `HyperlinkedRelatedField` to get the behavior
}
return self.get_queryset().get(**lookup_kwargs)
Note that if you wanted to use this style together with the generic views then you'd also need to override `.get_object` on the view in order to get the correct lookup behavior.
Note that if you wanted to use this style together with the generic views then
you'd also need to override `.get_object` on the view in order to get the
correct lookup behavior.
Generally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation.
Generally we recommend a flat style for API representations where possible, but
the nested URL style can also be reasonable when used in moderation.
---
@ -428,19 +506,31 @@ Generally we recommend a flat style for API representations where possible, but
## The `queryset` argument
The `queryset` argument is only ever required for *writable* relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance.
The `queryset` argument is only ever required for *writable* relationship
field, in which case it is used for performing the model instance lookup, that
maps from the primitive user input, into a model instance.
In version 2.x a serializer class could *sometimes* automatically determine the `queryset` argument *if* a `ModelSerializer` class was being used.
In version 2.x a serializer class could *sometimes* automatically determine the
`queryset` argument *if* a `ModelSerializer` class was being used.
This behavior is now replaced with *always* using an explicit `queryset` argument for writable relational fields.
This behavior is now replaced with *always* using an explicit `queryset`
argument for writable relational fields.
Doing so reduces the amount of hidden 'magic' that `ModelSerializer` provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the `ModelSerializer` shortcut, or using fully explicit `Serializer` classes.
Doing so reduces the amount of hidden 'magic' that `ModelSerializer` provides,
makes the behavior of the field more clear, and ensures that it is trivial to
move between using the `ModelSerializer` shortcut, or using fully explicit
`Serializer` classes.
## Customizing the HTML display
The built-in `__str__` method of the model will be used to generate string representations of the objects used to populate the `choices` property. These choices are used to populate select HTML inputs in the browsable API.
The built-in `__str__` method of the model will be used to generate string
representations of the objects used to populate the `choices` property. These
choices are used to populate select HTML inputs in the browsable API.
To provide customized representations for such inputs, override `display_value()` of a `RelatedField` subclass. This method will receive a model object, and should return a string suitable for representing it. For example:
To provide customized representations for such inputs, override
`display_value()` of a `RelatedField` subclass. This method will receive a
model object, and should return a string suitable for representing it. For
example:
class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
def display_value(self, instance):
@ -448,16 +538,26 @@ To provide customized representations for such inputs, override `display_value()
## Select field cutoffs
When rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with "More than 1000 items…" will be displayed.
When rendered in the browsable API relational fields will default to only
displaying a maximum of 1000 selectable items. If more items are present then a
disabled option with "More than 1000 items…" will be displayed.
This behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed.
This behavior is intended to prevent a template from being unable to render in
an acceptable timespan due to a very large number of relationships being
displayed.
There are two keyword arguments you can use to control this behavior:
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`.
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
- `html_cutoff` - If set this will be the maximum number of choices that will
be displayed by a HTML select drop down. Set to `None` to disable any
limiting. Defaults to `1000`.
- `html_cutoff_text` - If set this will display a textual indicator if the
maximum number of items have been cutoff in an HTML select drop down.
Defaults to `"More than {count} items…"`
In cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the `style` keyword argument. For example:
In cases where the cutoff is being enforced you may want to instead use a plain
input field in the HTML form. You can do so using the `style` keyword argument.
For example:
assigned_to = serializers.SlugRelatedField(
queryset=User.objects.all(),
@ -467,31 +567,41 @@ In cases where the cutoff is being enforced you may want to instead use a plain
## Reverse relations
Note that reverse relationships are not automatically included by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you must explicitly add it to the fields list. For example:
Note that reverse relationships are not automatically included by the
`ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a
reverse relationship, you must explicitly add it to the fields list. For
example:
class AlbumSerializer(serializers.ModelSerializer):
class Meta:
fields = ('tracks', ...)
You'll normally want to ensure that you've set an appropriate `related_name` argument on the relationship, that you can use as the field name. For example:
You'll normally want to ensure that you've set an appropriate `related_name`
argument on the relationship, that you can use as the field name. For example:
class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks')
...
If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the `fields` argument. For example:
If you have not set a related name for the reverse relationship, you'll need to
use the automatically generated related name in the `fields` argument. For
example:
class AlbumSerializer(serializers.ModelSerializer):
class Meta:
fields = ('track_set', ...)
See the Django documentation on [reverse relationships][reverse-relationships] for more details.
See the Django documentation on [reverse relationships][reverse-relationships]
for more details.
## Generic relationships
If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want to serialize the targets of the relationship.
If you want to serialize a generic foreign key, you need to define a custom
field, to determine explicitly how you want to serialize the targets of the
relationship.
For example, given the following model for a tag, which has a generic relationship with other arbitrary models:
For example, given the following model for a tag, which has a generic
relationship with other arbitrary models:
class TaggedItem(models.Model):
"""
@ -524,7 +634,9 @@ And the following two models, which may have associated tags:
text = models.CharField(max_length=1000)
tags = GenericRelation(TaggedItem)
We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized.
We could define a custom field that could be used to serialize tagged
instances, using the type of each instance to determine how it should be
serialized.
class TaggedObjectRelatedField(serializers.RelatedField):
"""
@ -541,7 +653,8 @@ We could define a custom field that could be used to serialize tagged instances,
return 'Note: ' + value.text
raise Exception('Unexpected type of tagged object')
If you need the target of the relationship to have a nested representation, you can use the required serializers inside the `.to_representation()` method:
If you need the target of the relationship to have a nested representation, you
can use the required serializers inside the `.to_representation()` method:
def to_representation(self, value):
"""
@ -557,7 +670,9 @@ If you need the target of the relationship to have a nested representation, you
return serializer.data
Note that reverse generic keys, expressed using the `GenericRelation` field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known.
Note that reverse generic keys, expressed using the `GenericRelation` field,
can be serialized using the regular relational field types, since the type of
the target in the relationship is always known.
For more information see [the Django documentation on generic relations][generic-relations].
@ -578,11 +693,13 @@ The following third party packages are also available.
## DRF Nested Routers
The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources.
The [drf-nested-routers package][drf-nested-routers] provides routers and
relationship fields for working with nested resources.
## Rest Framework Generic Relations
The [rest-framework-generic-relations][drf-nested-relations] library provides read/write serialization for generic foreign keys.
The [rest-framework-generic-relations][drf-nested-relations] library provides
read/write serialization for generic foreign keys.
[cite]: http://lwn.net/Articles/193245/
[reverse-relationships]: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

View File

@ -2,23 +2,39 @@ source: renderers.py
# Renderers
> Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client.
> Before a TemplateResponse instance can be returned to the client, it must be
> rendered. The rendering process takes the intermediate representation of
> template and context, and turns it into the final byte stream that can be
> served to the client.
>
> &mdash; [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 flexibility 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
The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request.
The set of valid renderers for a view is always defined as a list of classes.
When a view is entered REST framework will perform content negotiation on the
incoming request, and determine the most appropriate renderer to satisfy the
request.
The basic process of content negotiation involves examining the request's `Accept` header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL `http://example.com/api/users_count.json` might be an endpoint that always returns JSON data.
The basic process of content negotiation involves examining the request's
`Accept` header, to determine which media types it expects in the response.
Optionally, format suffixes on the URL may be used to explicitly request a
particular representation. For example the URL
`http://example.com/api/users_count.json` might be an endpoint that always
returns JSON data.
For more information see the documentation on [content negotiation][conneg].
## Setting the renderers
The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CLASSES` setting. For example, the following settings would use `JSON` 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 `JSON` as the main media type and also include the self describing API.
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
@ -60,11 +76,20 @@ Or, if you're using the `@api_view` decorator with function based views.
## Ordering of renderer classes
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.
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 browsable 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.
For example if your API serves JSON responses and the HTML browsable 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][browser-accept-headers].
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][browser-accept-headers].
---
@ -74,18 +99,22 @@ If your API includes views that can serve both regular webpages and API response
Renders the request data into `JSON`, using utf-8 encoding.
Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace:
Note that the default style is to include unicode characters, and render the
response using a compact style with no unnecessary whitespace:
{"unicode black star":"★","value":999}
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`.
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`.
{
"unicode black star": "★",
"value": 999
}
The default JSON encoding style can be altered using the `UNICODE_JSON` and `COMPACT_JSON` settings keys.
The default JSON encoding style can be altered using the `UNICODE_JSON` and
`COMPACT_JSON` settings keys.
**.media_type**: `application/json`
@ -95,10 +124,14 @@ The default JSON encoding style can be altered using the `UNICODE_JSON` and `COM
## 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`.
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 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 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):
@ -119,9 +152,14 @@ An example of a view that uses `TemplateHTMLRenderer`:
self.object = self.get_object()
return Response({'user': self.object}, template_name='user_detail.html')
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.
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 `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.
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`
@ -133,7 +171,9 @@ 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.
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 `StaticHTMLRenderer`:
@ -143,7 +183,8 @@ An example of a view that uses `StaticHTMLRenderer`:
data = '<html><body><h1>Hello, world</h1></body></html>'
return Response(data)
You can use `StaticHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
You can use `StaticHTMLRenderer` 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`
@ -159,7 +200,8 @@ Renders data into HTML for the Browsable API:
![The BrowsableAPIRenderer](../img/quickstart.png)
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.
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`
@ -171,7 +213,11 @@ This renderer will determine which other renderer would have been given highest
#### Customizing BrowsableAPIRenderer
By default the response content will be rendered with the highest priority renderer apart from `BrowsableAPIRenderer`. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the `get_default_renderer()` method. For example:
By default the response content will be rendered with the highest priority
renderer apart from `BrowsableAPIRenderer`. If you need to customize this
behavior, for example to use HTML as the default return format, but use JSON in
the browsable API, you can do so by overriding the `get_default_renderer()`
method. For example:
class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
def get_default_renderer(self, view):
@ -183,9 +229,12 @@ Renders data into HTML for an admin-like display:
![The AdminRender view](../img/admin.png)
This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data.
This renderer is suitable for CRUD-style web APIs that should also present a
user-friendly interface for managing the data.
Note that views that have nested or list serializers for their input won't work well with the `AdminRenderer`, as the HTML forms are unable to properly support them.
Note that views that have nested or list serializers for their input won't work
well with the `AdminRenderer`, as the HTML forms are unable to properly support
them.
**Note**: The `AdminRenderer` is only able to include links to detail pages when a properly configured `URL_FIELD_NAME` (`url` by default) attribute is present in the data. For `HyperlinkedModelSerializer` this will be the case, but for `ModelSerializer` or plain `Serializer` classes you'll need to make sure to include the field explicitly. For example here we use models `get_absolute_url` method:
@ -206,9 +255,12 @@ Note that views that have nested or list serializers for their input won't work
## HTMLFormRenderer
Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing `<form>` tags, a hidden CSRF input or any submit buttons.
Renders data returned by a serializer into an HTML form. The output of this
renderer does not include the enclosing `<form>` tags, a hidden CSRF input or
any submit buttons.
This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the `render_form` template tag.
This renderer is not intended to be used directly, but can instead be used in
templates by passing a serializer instance to the `render_form` template tag.
{% load rest_framework %}
@ -230,7 +282,10 @@ For more information see the [HTML & Forms][html-and-forms] documentation.
## MultiPartRenderer
This renderer is used for rendering HTML multipart form data. **It is not suitable as a response renderer**, but is instead used for creating test requests, using REST framework's [test client and test request factory][testing].
This renderer is used for rendering HTML multipart form data. **It is not
suitable as a response renderer**, but is instead used for creating test
requests, using REST framework's [test client and test request
factory][testing].
**.media_type**: `multipart/form-data; boundary=BoUnDaRyStRiNg`
@ -242,9 +297,12 @@ This renderer is used for rendering HTML multipart form data. **It is not suita
# 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.
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.
The method should return a bytestring, which will be used as the body of the HTTP response.
The method should return a bytestring, which will be used as the body of the
HTTP response.
The arguments passed to the `.render()` method are:
@ -254,19 +312,25 @@ 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.
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"`.
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.
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`.
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.
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
@ -281,7 +345,8 @@ The following is an example plaintext renderer that will return a response with
## Setting the character set
By default renderer classes are assumed to be using the `UTF-8` encoding. To use a different encoding, set the `charset` attribute on the renderer.
By default renderer classes are assumed to be using the `UTF-8` encoding. To
use a different encoding, set the `charset` attribute on the renderer.
class PlainTextRenderer(renderers.BaseRenderer):
media_type = 'text/plain'
@ -291,11 +356,17 @@ By default renderer classes are assumed to be using the `UTF-8` encoding. To us
def render(self, data, media_type=None, renderer_context=None):
return data.encode(self.charset)
Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the `Response` class, with the `charset` attribute set on the renderer used to determine the encoding.
Note that if a renderer class returns a unicode string, then the response
content will be coerced into a bytestring by the `Response` class, with the
`charset` attribute set on the renderer used to determine the encoding.
If the renderer returns a bytestring representing raw binary content, you should set a charset value of `None`, which will ensure the `Content-Type` header of the response will not have a `charset` value set.
If the renderer returns a bytestring representing raw binary content, you
should set a charset value of `None`, which will ensure the `Content-Type`
header of the response will not have a `charset` value set.
In some cases you may also want to set the `render_style` attribute to `'binary'`. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string.
In some cases you may also want to set the `render_style` attribute to
`'binary'`. Doing so will also ensure that the browsable API will not attempt
to display the binary content as a string.
class JPEGRenderer(renderers.BaseRenderer):
media_type = 'image/jpeg'
@ -312,14 +383,20 @@ In some cases you may also want to set the `render_style` attribute to `'binary'
You can do some pretty flexible things using REST framework's renderers. Some examples...
* Provide either flat or nested representations from the same endpoint, depending on the requested media type.
* Serve both regular HTML webpages, and JSON based API responses from the same endpoints.
* Provide either flat or nested representations from the same endpoint,
depending on the requested media type.
* Serve both regular HTML webpages, and JSON based API responses from the same
endpoints.
* Specify multiple types of HTML representation for API clients to use.
* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
* Underspecify a renderer's media type, such as using `media_type = 'image/*'`,
and use the `Accept` header to vary the encoding of the response.
## Varying behaviour by media type
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.
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:
@ -346,36 +423,55 @@ For example:
## Underspecifying the media type
In some cases you might want a renderer to serve a range of media types.
In this case you can underspecify the media types it should respond to, by using a `media_type` value such as `image/*`, or `*/*`.
In some cases you might want a renderer to serve a range of media types. In
this case you can underspecify the media types it should respond to, by using a
`media_type` value such as `image/*`, or `*/*`.
If you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the `content_type` attribute. For example:
If you underspecify the renderer's media type, you should make sure to specify
the media type explicitly when you return the response, using the
`content_type` attribute. For example:
return Response(data, content_type='image/png')
## 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 need 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.".
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.".
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.
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.
## HTML error views
Typically a renderer will behave the same regardless of if it's dealing with a regular response, or with a response caused by an exception being raised, such as an `Http404` or `PermissionDenied` exception, or a subclass of `APIException`.
Typically a renderer will behave the same regardless of if it's dealing with a
regular response, or with a response caused by an exception being raised, such
as an `Http404` or `PermissionDenied` exception, or a subclass of
`APIException`.
If you're using either the `TemplateHTMLRenderer` or the `StaticHTMLRenderer` and an exception is raised, the behavior is slightly different, and mirrors [Django's default handling of error views][django-error-views].
If you're using either the `TemplateHTMLRenderer` or the `StaticHTMLRenderer`
and an exception is raised, the behavior is slightly different, and mirrors
[Django's default handling of error views][django-error-views].
Exceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence.
Exceptions raised and handled by an HTML renderer will attempt to render using
one of the following methods, by order of precedence.
* Load and render a template named `{status_code}.html`.
* Load and render a template named `api_exception.html`.
* Render the HTTP status code and text, for example "404 Not Found".
Templates will render with a `RequestContext` which includes the `status_code` and `details` keys.
Templates will render with a `RequestContext` which includes the `status_code`
and `details` keys.
**Note**: If `DEBUG=True`, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text.
**Note**: If `DEBUG=True`, Django's standard traceback error page will be
displayed instead of rendering the HTTP status code and text.
---
@ -385,7 +481,9 @@ The following third party packages are also available.
## YAML
[REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
[REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and
rendering support. It was previously included directly in the REST framework
package, and is now instead supported as a third-party package.
#### Installation & configuration
@ -406,7 +504,9 @@ Modify your REST framework settings.
## XML
[REST Framework XML][rest-framework-xml] provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
[REST Framework XML][rest-framework-xml] provides a simple informal XML format.
It was previously included directly in the REST framework package, and is now
instead supported as a third-party package.
#### Installation & configuration
@ -427,13 +527,19 @@ Modify your REST framework settings.
## JSONP
[REST framework JSONP][rest-framework-jsonp] provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
[REST framework JSONP][rest-framework-jsonp] provides JSONP rendering support.
It was previously included directly in the REST framework package, and is now
instead supported as a third-party package.
---
**Warning**: If you require cross-domain AJAX requests, you should generally be using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details.
**Warning**: If you require cross-domain AJAX requests, you should generally be
using the more modern approach of [CORS][cors] as an alternative to `JSONP`.
See the [CORS documentation][cors-docs] for more details.
The `jsonp` approach is essentially a browser hack, and is [only appropriate for globally readable API endpoints][jsonp-security], where `GET` requests are unauthenticated and do not require any user permissions.
The `jsonp` approach is essentially a browser hack, and is [only appropriate
for globally readable API endpoints][jsonp-security], where `GET` requests are
unauthenticated and do not require any user permissions.
---
@ -453,27 +559,44 @@ Modify your REST framework settings.
## MessagePack
[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
[MessagePack][messagepack] is a fast, efficient binary serialization format.
[Juan Riaza][juanriaza] maintains the
[djangorestframework-msgpack][djangorestframework-msgpack] package which
provides MessagePack renderer and parser support for REST framework.
## CSV
Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework.
Comma-separated values are a plain-text tabular data format, that can be easily
imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the
[djangorestframework-csv][djangorestframework-csv] package which provides CSV
renderer support for REST framework.
## UltraJSON
[UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Jacob Haslehurst][hzy] maintains the [drf-ujson-renderer][drf-ujson-renderer] package which implements JSON rendering using the UJSON package.
[UltraJSON][ultrajson] is an optimized C JSON encoder which can give
significantly faster JSON rendering. [Jacob Haslehurst][hzy] maintains the
[drf-ujson-renderer][drf-ujson-renderer] package which implements JSON
rendering using the UJSON package.
## CamelCase JSON
[djangorestframework-camel-case] provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by [Vitaly Babiy][vbabiy].
[djangorestframework-camel-case] provides camel case JSON renderers and parsers
for REST framework. This allows serializers to use Python-style underscored
field names, but be exposed in the API as Javascript-style camel case
field names. It is maintained by [Vitaly Babiy][vbabiy].
## Pandas (CSV, Excel, PNG)
[Django REST Pandas] provides a serializer and renderers that support additional data processing and output via the [Pandas] DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both `.xls` and `.xlsx`), and a number of [other formats]. It is maintained by [S. Andrew Sheppard][sheppard] as part of the [wq Project][wq].
[Django REST Pandas] provides a serializer and renderers that support
additional data processing and output via the [Pandas] DataFrame API. Django
REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks
(both `.xls` and `.xlsx`), and a number of [other formats]. It is maintained by
[S. Andrew Sheppard][sheppard] as part of the [wq Project][wq].
## LaTeX
[Rest Framework Latex] provides a renderer that outputs PDFs using Laulatex. It is maintained by [Pebble (S/F Software)][mypebble].
[Rest Framework Latex] provides a renderer that outputs PDFs using Laulatex. It
is maintained by [Pebble (S/F Software)][mypebble].
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process

View File

@ -6,21 +6,29 @@ source: request.py
>
> &mdash; Malcom Tredinnick, [Django developers group][cite]
REST framework's `Request` class extends the standard `HttpRequest`, adding support for REST framework's flexible request parsing and request authentication.
REST framework's `Request` class extends the standard `HttpRequest`, adding
support for REST framework's flexible request parsing and request
authentication.
---
# 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.
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 `request.POST` and `request.FILES` attributes except that:
`request.data` returns the parsed content of the request body. This is similar
to the standard `request.POST` and `request.FILES` attributes except that:
* It includes all parsed content, including *file and non-file* inputs.
* 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.
* 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].
@ -28,25 +36,38 @@ For more details see the [parsers documentation].
`request.query_params` is a more correctly named synonym for `request.GET`.
For clarity inside your code, we recommend using `request.query_params` instead of the Django's standard `request.GET`. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just `GET` requests.
For clarity inside your code, we recommend using `request.query_params` instead
of the Django's standard `request.GET`. Doing so will help keep your codebase
more correct and obvious - any HTTP method type may include query parameters,
not just `GET` requests.
## .parsers
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.
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.
You won't typically need to access this property.
---
**Note:** If a client sends malformed content, then accessing `request.data` 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.
**Note:** If a client sends malformed content, then accessing `request.data`
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.
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.
---
# Content negotiation
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialisation schemes for different media types.
The request exposes some properties that allow you to determine the result of
the content negotiation stage. This allows you to implement behaviour such as
selecting a different serialisation schemes for different media types.
## .accepted_renderer
@ -54,13 +75,15 @@ The renderer instance what was selected by the content negotiation stage.
## .accepted_media_type
A string representing the media type that was accepted by the content negotiation stage.
A string representing the media type that was accepted by the content
negotiation stage.
---
# Authentication
REST framework provides flexible, per-request authentication, that gives you the ability to:
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.
@ -68,23 +91,33 @@ REST framework provides flexible, per-request authentication, that gives you the
## .user
`request.user` typically returns an instance of `django.contrib.auth.models.User`, although the behavior depends on the authentication policy being used.
`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`.
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.
`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`.
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.
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.
@ -92,11 +125,13 @@ You won't typically need to access this property.
# Browser enhancements
REST framework supports a few browser enhancements such as browser-based `PUT`, `PATCH` and `DELETE` forms.
REST framework supports a few browser enhancements such as browser-based `PUT`,
`PATCH` and `DELETE` forms.
## .method
`request.method` returns the **uppercased** string representation of the request's HTTP method.
`request.method` returns the **uppercased** string representation of the
request's HTTP method.
Browser-based `PUT`, `PATCH` and `DELETE` forms are transparently supported.
@ -104,11 +139,16 @@ 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.
`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.
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.
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].
@ -116,15 +156,19 @@ For more information see the [browser enhancements documentation].
`request.stream` returns a stream representing the content of the request body.
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.
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.
---
# 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` and `request.session` dictionaries are available as normal.
As REST framework's `Request` extends Django's `HttpRequest`, all the other
standard attributes and methods are also available. For example the
`request.META` and `request.session` dictionaries are 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.
Note that due to implementation reasons the `Request` class does not inherit
from `HttpRequest` class, but instead extends the class using composition.
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion

View File

@ -2,17 +2,33 @@ source: response.py
# Responses
> Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.
> Unlike basic HttpResponse objects, TemplateResponse objects retain the
> details of the context that was provided by the view to compute the response.
> The final output of the response is not computed until it is needed, later in
> the response process.
>
> &mdash; [Django documentation][cite]
REST framework supports HTTP content negotiation by providing a `Response` class which allows you to return content that can be rendered into multiple content types, depending on the client request.
REST framework supports HTTP content negotiation by providing a `Response`
class which allows you to return content that can be rendered into multiple
content types, depending on the client request.
The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response` objects are initialised with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.
The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response`
objects are initialised with data, which should consist of native Python
primitives. REST framework then uses standard HTTP content negotiation to
determine how it should render the final response content.
There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` or `StreamingHttpResponse` objects from your views if required. Using the `Response` class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats.
There's no requirement for you to use the `Response` class, you can also return
regular `HttpResponse` or `StreamingHttpResponse` objects from your views if
required. Using the `Response` class simply provides a nicer interface for
returning content-negotiated Web API responses, that can be rendered to
multiple formats.
Unless you want to heavily customize REST framework for some reason, you should always use an `APIView` class or `@api_view` function for views that return `Response` objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view.
Unless you want to heavily customize REST framework for some reason, you should
always use an `APIView` class or `@api_view` function for views that return
`Response` objects. Doing so ensures that the view can perform content
negotiation and select the appropriate renderer for the response, before it is
returned from the view.
---
@ -20,21 +36,31 @@ Unless you want to heavily customize REST framework for some reason, you should
## Response()
**Signature:** `Response(data, status=None, template_name=None, headers=None, content_type=None)`
**Signature:** `Response(data, status=None, template_name=None, headers=None,
content_type=None)`
Unlike regular `HttpResponse` objects, you do not instantiate `Response` objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives.
Unlike regular `HttpResponse` objects, you do not instantiate `Response`
objects with rendered content. Instead you pass in unrendered data, which may
consist of any Python primitives.
The renderers used by the `Response` class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the `Response` object.
The renderers used by the `Response` class cannot natively handle complex
datatypes such as Django model instances, so you need to serialize the data
into primitive datatypes before creating the `Response` object.
You can use REST framework's `Serializer` classes to perform this data serialization, or use your own custom serialization.
You can use REST framework's `Serializer` classes to perform this data
serialization, or use your own custom serialization.
Arguments:
* `data`: The serialized data for the response.
* `status`: A status code for the response. Defaults to 200. See also [status codes][statuscodes].
* `status`: A status code for the response. Defaults to 200.
See also [status codes][statuscodes].
* `template_name`: A template name to use if `HTMLRenderer` is selected.
* `headers`: A dictionary of HTTP headers to use in the response.
* `content_type`: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly.
* `content_type`: The content type of the response. Typically, this will be
set automatically by the renderer as determined by content negotiation, but
there may be some cases where you need to specify the content type
explicitly.
---
@ -50,35 +76,43 @@ The numeric status code of the HTTP response.
## .content
The rendered content of the response. The `.render()` method 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.
## .template_name
The `template_name`, if supplied. Only required if `HTMLRenderer` or some other custom template renderer is the accepted renderer for the response.
The `template_name`, if supplied. Only required if `HTMLRenderer` or some
other custom template renderer is the accepted renderer for the response.
## .accepted_renderer
The renderer instance that will be used to render the response.
Set automatically by the `APIView` or `@api_view` immediately before the response is returned from the view.
Set automatically by the `APIView` or `@api_view` immediately before the
response is returned from the view.
## .accepted_media_type
The media type that was selected by the content negotiation stage.
Set automatically by the `APIView` or `@api_view` immediately before the response is returned from the view.
Set automatically by the `APIView` or `@api_view` immediately before the
response is returned from the view.
## .renderer_context
A dictionary of additional context information that will be passed to the renderer's `.render()` method.
A dictionary of additional context information that will be passed to the
renderer's `.render()` method.
Set automatically by the `APIView` or `@api_view` immediately before the response is returned from the view.
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:
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'
@ -87,9 +121,14 @@ The `Response` class extends `SimpleTemplateResponse`, and all the usual attribu
**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.
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.
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

View File

@ -2,30 +2,43 @@ source: reverse.py
# Returning URLs
> The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.
> The central feature that distinguishes the REST architectural style from
> other network-based styles is its emphasis on a uniform interface between
> components.
>
> &mdash; Roy Fielding, [Architectural Styles and the Design of Network-based Software Architectures][cite]
> &mdash; 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 your 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:
* It's more explicit.
* It leaves less work for your API clients.
* There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type.
* It makes it easy to do things like markup HTML representations with hyperlinks.
* There's no ambiguity about the meaning of the string when it's found in
representations such as JSON that do not have a native URI type.
* It makes it easy to do things like markup HTML representations with
hyperlinks.
REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.
REST framework provides two utility functions to make it more simple to return
absolute URIs from your Web API.
There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier.
There's no requirement for you to use them, but if you do then the
self-describing API will be able to automatically hyperlink its output for you,
which makes browsing the API much easier.
## reverse
**Signature:** `reverse(viewname, *args, **kwargs)`
Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port.
Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except
that it returns a fully qualified URL, using the request to determine the host
and port.
You should **include the request as a keyword argument** to the function, for example:
You should **include the request as a keyword argument** to the function, for
example:
from rest_framework.reverse import reverse
from rest_framework.views import APIView
@ -44,9 +57,12 @@ You should **include the request as a keyword argument** to the function, for ex
**Signature:** `reverse_lazy(viewname, *args, **kwargs)`
Has the same behavior as [`django.core.urlresolvers.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port.
Has the same behavior as
[`django.core.urlresolvers.reverse_lazy`][reverse-lazy], except that it returns
a fully qualified URL, using the request to determine the host and port.
As with the `reverse` function, you should **include the request as a keyword argument** to the function, for example:
As with the `reverse` function, you should **include the request as a keyword
argument** to the function, for example:
api_root = reverse_lazy('api-root', request=request)

View File

@ -2,13 +2,19 @@ source: routers.py
# Routers
> Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.
> Resource routing allows you to quickly declare all of the common routes for a
> given resourceful controller. Instead of declaring separate routes for your
> index... a resourceful route declares them in a single line of code.
>
> &mdash; [Ruby on Rails Documentation][cite]
Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.
Some Web frameworks such as Rails provide functionality for automatically
determining how the URLs for an application should be mapped to the logic that
deals with handling incoming requests.
REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.
REST framework adds support for automatic URL routing to Django, and provides
you with a simple, quick and consistent way of wiring your view logic to a set
of URLs.
## Usage
@ -28,7 +34,11 @@ There are two mandatory arguments to the `register()` method:
Optionally, you may also specify an additional argument:
* `base_name` - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the `queryset` attribute of the viewset, if it has one. Note that if the viewset does not include a `queryset` attribute then you must set `base_name` when registering the viewset.
* `base_name` - The base to use for the URL names that are created. If unset
the basename will be automatically generated based on the `queryset`
attribute of the viewset, if it has one. Note that if the viewset does not
include a `queryset` attribute then you must set `base_name` when registering
the viewset.
The example above would generate the following URL patterns:
@ -39,30 +49,39 @@ The example above would generate the following URL patterns:
---
**Note**: The `base_name` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part.
**Note**: The `base_name` argument is used to specify the initial part of the
view name pattern. In the example above, that's the `user` or `account` part.
Typically you won't *need* to specify the `base_name` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this:
Typically you won't *need* to specify the `base_name` argument, but if you have
a viewset where you've defined a custom `get_queryset` method, then the viewset
may not have a `.queryset` attribute set. If you try to register that viewset
you'll see an error like this:
'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
'base_name' argument not specified, and could not automatically determine
the name from the viewset, as it does not have a '.queryset' attribute.
This means you'll need to explicitly set the `base_name` argument when registering the viewset, as it could not be automatically determined from the model name.
This means you'll need to explicitly set the `base_name` argument when
registering the viewset, as it could not be automatically determined from the
model name.
---
### Using `include` with routers
The `.urls` attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs.
The `.urls` attribute on a router instance is simply a standard list of URL
patterns. There are a number of different styles for how you can include these
URLs.
For example, you can append `router.urls` to a list of existing views…
router = routers.SimpleRouter()
router.register(r'users', UserViewSet)
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
]
urlpatterns += router.urls
Alternatively you can use Django's `include` function, like so…
@ -79,12 +98,17 @@ Router URL patterns can also be namespaces.
url(r'^api/', include(router.urls, namespace='api')),
]
If using namespacing with hyperlinked serializers you'll also need to ensure that any `view_name` parameters on the serializers correctly reflect the namespace. In the example above you'd need to include a parameter such as `view_name='api:user-detail'` for serializer fields hyperlinked to the user detail view.
If using namespacing with hyperlinked serializers you'll also need to ensure
that any `view_name` parameters on the serializers correctly reflect the
namespace. In the example above you'd need to include a parameter such as
`view_name='api:user-detail'` for serializer fields hyperlinked to the user
detail view.
### Extra link and actions
Any methods on the viewset decorated with `@detail_route` or `@list_route` will also be routed.
For example, given a method like this on the `UserViewSet` class:
Any methods on the viewset decorated with `@detail_route` or `@list_route` will
also be routed. For example, given a method like this on the `UserViewSet`
class:
from myapp.permissions import IsAdminOrIsSelf
from rest_framework.decorators import detail_route
@ -100,16 +124,18 @@ The following URL pattern would additionally be generated:
* URL pattern: `^users/{pk}/set_password/$` Name: `'user-set-password'`
If you do not want to use the default URL generated for your custom action, you can instead use the url_path parameter to customize it.
If you do not want to use the default URL generated for your custom action, you
can instead use the url_path parameter to customize it.
For example, if you want to change the URL for our custom action to `^users/{pk}/change-password/$`, you could write:
For example, if you want to change the URL for our custom action to
`^users/{pk}/change-password/$`, you could write:
from myapp.permissions import IsAdminOrIsSelf
from rest_framework.decorators import detail_route
class UserViewSet(ModelViewSet):
...
@detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf], url_path='change-password')
def set_password(self, request, pk=None):
...
@ -124,7 +150,10 @@ For more information see the viewset documentation on [marking extra actions for
## SimpleRouter
This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@detail_route` or `@list_route` decorators.
This router includes routes for the standard set of `list`, `create`,
`retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can
also mark additional methods to be routed, using the `@detail_route` or
`@list_route` decorators.
<table border=1>
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
@ -138,14 +167,21 @@ This router includes routes for the standard set of `list`, `create`, `retrieve`
<tr><td>{prefix}/{lookup}/{methodname}/</td><td>GET, or as specified by `methods` argument</td><td>`@detail_route` decorated method</td><td>{basename}-{methodname}</td></tr>
</table>
By default the URLs created by `SimpleRouter` are appended with a trailing slash.
This behavior can be modified by setting the `trailing_slash` argument to `False` when instantiating the router. For example:
By default the URLs created by `SimpleRouter` are appended with a trailing
slash. This behavior can be modified by setting the `trailing_slash` argument
to `False` when instantiating the router. For example:
router = SimpleRouter(trailing_slash=False)
Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.
Trailing slashes are conventional in Django, but are not used by default in
some other frameworks such as Rails. Which style you choose to use is largely
a matter of preference, although some javascript frameworks may expect a
particular routing style.
The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs:
The router will match lookup values containing any characters except slashes
and period characters. For a more restrictive (or lenient) lookup pattern, set
the `lookup_value_regex` attribute on the viewset. For example, you can limit
the lookup to valid UUIDs:
class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
lookup_field = 'my_model_id'
@ -153,7 +189,10 @@ The router will match lookup values containing any characters except slashes and
## DefaultRouter
This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes.
This router is similar to `SimpleRouter` as above, but additionally includes a
default API root view, that returns a response containing hyperlinks to all the
list views. It also generates routes for optional `.json` style format
suffixes.
<table border=1>
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
@ -168,48 +207,70 @@ This router is similar to `SimpleRouter` as above, but additionally includes a d
<tr><td>{prefix}/{lookup}/{methodname}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@detail_route` decorated method</td><td>{basename}-{methodname}</td></tr>
</table>
As with `SimpleRouter` the trailing slashes on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router.
As with `SimpleRouter` the trailing slashes on the URL routes can be removed by
setting the `trailing_slash` argument to `False` when instantiating the router.
router = DefaultRouter(trailing_slash=False)
# Custom Routers
Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the your URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.
Implementing a custom router isn't something you'd need to do very often, but
it can be useful if you have specific requirements about how the your URLs for
your API are structured. Doing so allows you to encapsulate the URL structure
in a reusable way that ensures you don't have to write your URL patterns
explicitly for each new view.
The simplest way to implement a custom router is to subclass one of the existing router classes. The `.routes` attribute is used to template the URL patterns that will be mapped to each viewset. The `.routes` attribute is a list of `Route` named tuples.
The simplest way to implement a custom router is to subclass one of the
existing router classes. The `.routes` attribute is used to template the URL
patterns that will be mapped to each viewset. The `.routes` attribute is a list
of `Route` named tuples.
The arguments to the `Route` named tuple are:
**url**: A string representing the URL to be routed. May include the following format strings:
**url**: A string representing the URL to be routed. May include the following
format strings:
* `{prefix}` - The URL prefix to use for this set of routes.
* `{lookup}` - The lookup field used to match against a single instance.
* `{trailing_slash}` - Either a '/' or an empty string, depending on the `trailing_slash` argument.
* `{trailing_slash}` - Either a '/' or an empty string, depending on the
`trailing_slash` argument.
**mapping**: A mapping of HTTP method names to the view methods
**name**: The name of the URL as used in `reverse` calls. May include the following format string:
**name**: The name of the URL as used in `reverse` calls. May include the
following format string:
* `{basename}` - The base to use for the URL names that are created.
**initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the `suffix` argument is reserved for identifying the viewset type, used when generating the view name and breadcrumb links.
**initkwargs**: A dictionary of any additional arguments that should be passed
when instantiating the view. Note that the `suffix` argument is reserved for
identifying the viewset type, used when generating the view name and breadcrumb
links.
## Customizing dynamic routes
You can also customize how the `@list_route` and `@detail_route` decorators are routed.
To route either or both of these decorators, include a `DynamicListRoute` and/or `DynamicDetailRoute` named tuple in the `.routes` list.
You can also customize how the `@list_route` and `@detail_route` decorators are
routed. To route either or both of these decorators, include a
`DynamicListRoute` and/or `DynamicDetailRoute` named tuple in the `.routes`
list.
The arguments to `DynamicListRoute` and `DynamicDetailRoute` are:
**url**: A string representing the URL to be routed. May include the same format strings as `Route`, and additionally accepts the `{methodname}` and `{methodnamehyphen}` format strings.
**url**: A string representing the URL to be routed. May include the same
format strings as `Route`, and additionally accepts the `{methodname}` and
`{methodnamehyphen}` format strings.
**name**: The name of the URL as used in `reverse` calls. May include the following format strings: `{basename}`, `{methodname}` and `{methodnamehyphen}`.
**name**: The name of the URL as used in `reverse` calls. May include the
following format strings: `{basename}`, `{methodname}` and
`{methodnamehyphen}`.
**initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view.
**initkwargs**: A dictionary of any additional arguments that should be passed
when instantiating the view.
## Example
The following example will only route to the `list` and `retrieve` actions, and does not use the trailing slash convention.
The following example will only route to the `list` and `retrieve` actions, and
does not use the trailing slash convention.
from rest_framework.routers import Route, DynamicDetailRoute, SimpleRouter
@ -278,9 +339,15 @@ For another example of setting the `.routes` attribute, see the source code for
## Advanced custom routers
If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute.
If you want to provide totally custom behavior, you can override `BaseRouter`
and override the `get_urls(self)` method. The method should inspect the
registered viewsets and return a list of URL patterns. The registered prefix,
viewset and basename tuples may be inspected by accessing the `self.registry`
attribute.
You may also want to override the `get_default_base_name(self, viewset)` method, or else always explicitly set the `base_name` argument when registering your viewsets with the router.
You may also want to override the `get_default_base_name(self, viewset)`
method, or else always explicitly set the `base_name` argument when registering
your viewsets with the router.
# Third Party Packages
@ -288,11 +355,17 @@ The following third party packages are also available.
## DRF Nested Routers
The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources.
The [drf-nested-routers package][drf-nested-routers] provides routers and
relationship fields for working with nested resources.
## ModelRouter (wq.db.rest)
The [wq.db package][wq.db] provides an advanced [ModelRouter][wq.db-router] class (and singleton instance) that extends `DefaultRouter` with a `register_model()` API. Much like Django's `admin.site.register`, the only required argument to `rest.router.register_model` is a model class. Reasonable defaults for a url prefix, serializer, and viewset will be inferred from the model and global configuration.
The [wq.db package][wq.db] provides an advanced [ModelRouter][wq.db-router]
class (and singleton instance) that extends `DefaultRouter` with a
`register_model()` API. Much like Django's `admin.site.register`, the only
required argument to `rest.router.register_model` is a model class. Reasonable
defaults for a url prefix, serializer, and viewset will be inferred from the
model and global configuration.
from wq.db import rest
from myapp.models import MyModel
@ -301,7 +374,11 @@ The [wq.db package][wq.db] provides an advanced [ModelRouter][wq.db-router] clas
## DRF-extensions
The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions-routers] for creating [nested viewsets][drf-extensions-nested-viewsets], [collection level controllers][drf-extensions-collection-level-controllers] with [customizable endpoint names][drf-extensions-customizable-endpoint-names].
The [`DRF-extensions` package][drf-extensions] provides
[routers][drf-extensions-routers] for creating [nested
viewsets][drf-extensions-nested-viewsets], [collection level
controllers][drf-extensions-collection-level-controllers] with [customizable
endpoint names][drf-extensions-customizable-endpoint-names].
[cite]: http://guides.rubyonrails.org/routing.html
[route-decorators]: viewsets.md#marking-extra-actions-for-routing

View File

@ -2,7 +2,9 @@ source: schemas.py
# Schemas
> A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.
> A machine-readable [schema] describes what resources are available via the
> API, what their URLs are, how they are represented and what operations they
> support.
>
> &mdash; Heroku, [JSON Schema for the Heroku Platform API][cite]
@ -281,9 +283,12 @@ Typically you'll instantiate `SchemaGenerator` with a single argument, like so:
Arguments:
* `title` - The name of the API. **required**
* `url` - The root URL of the API schema. This option is not required unless the schema is included under path prefix.
* `patterns` - A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.
* `urlconf` - A URL conf module name to use when generating the schema. Defaults to `settings.ROOT_URLCONF`.
* `url` - The root URL of the API schema. This option is not required unless
the schema is included under path prefix.
* `patterns` - A list of URLs to inspect when generating the schema. Defaults
to the project's URL conf.
* `urlconf` - A URL conf module name to use when generating the schema.
Defaults to `settings.ROOT_URLCONF`.
### get_schema()
@ -382,27 +387,37 @@ the following strings:
**"path"**
Included in a templated URI. For example a `url` value of `/products/{product_code}/` could be used together with a `"path"` field, to handle API inputs in a URL path such as `/products/slim-fit-jeans/`.
Included in a templated URI. For example a `url` value of
`/products/{product_code}/` could be used together with a `"path"` field, to
handle API inputs in a URL path such as `/products/slim-fit-jeans/`.
These fields will normally correspond with [named arguments in the project URL conf][named-arguments].
These fields will normally correspond with [named arguments in the project URL
conf][named-arguments].
**"query"**
Included as a URL query parameter. For example `?search=sale`. Typically for `GET` requests.
Included as a URL query parameter. For example `?search=sale`. Typically for
`GET` requests.
These fields will normally correspond with pagination and filtering controls on a view.
These fields will normally correspond with pagination and filtering controls on
a view.
**"form"**
Included in the request body, as a single item of a JSON object or HTML form. For example `{"colour": "blue", ...}`. Typically for `POST`, `PUT` and `PATCH` requests. Multiple `"form"` fields may be included on a single link.
Included in the request body, as a single item of a JSON object or HTML form.
For example `{"colour": "blue", ...}`. Typically for `POST`, `PUT` and `PATCH`
requests. Multiple `"form"` fields may be included on a single link.
These fields will normally correspond with serializer fields on a view.
**"body"**
Included as the complete request body. Typically for `POST`, `PUT` and `PATCH` requests. No more than one `"body"` field may exist on a link. May not be used together with `"form"` fields.
Included as the complete request body. Typically for `POST`, `PUT` and `PATCH`
requests. No more than one `"body"` field may exist on a link. May not be used
together with `"form"` fields.
These fields will normally correspond with views that use `ListSerializer` to validate the request input, or with file upload views.
These fields will normally correspond with views that use `ListSerializer` to
validate the request input, or with file upload views.
#### `encoding`

File diff suppressed because it is too large Load Diff

View File

@ -6,9 +6,11 @@ source: settings.py
>
> &mdash; [The Zen of Python][cite]
Configuration for REST framework is all namespaced inside a single Django setting, named `REST_FRAMEWORK`.
Configuration for REST framework is all namespaced inside a single Django
setting, named `REST_FRAMEWORK`.
For example your project's `settings.py` file might include something like this:
For example your project's `settings.py` file might include something like
this:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
@ -21,14 +23,17 @@ For example your project's `settings.py` file might include something like this:
## Accessing settings
If you need to access the values of REST framework's API settings in your project,
you should use the `api_settings` object. For example.
If you need to access the values of REST framework's API settings in your
project, you should use the `api_settings` object. For example.
from rest_framework.settings import api_settings
print api_settings.DEFAULT_AUTHENTICATION_CLASSES
The `api_settings` object will check for any user-defined settings, and otherwise fall back 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.
The `api_settings` object will check for any user-defined settings, and
otherwise fall back 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.
---
@ -36,11 +41,13 @@ The `api_settings` object will check for any user-defined settings, and otherwis
## API policy settings
*The following settings control the basic API policies, and are applied to every `APIView` class-based view, or `@api_view` function based view.*
*The following settings control the basic API policies, and are applied to
every `APIView` class-based view, or `@api_view` function based view.*
#### 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.
A list or tuple of renderer classes, that determines the default set of
renderers that may be used when returning a `Response` object.
Default:
@ -51,7 +58,8 @@ Default:
#### DEFAULT_PARSER_CLASSES
A list or tuple of parser classes, that determines the default set of parsers used when accessing the `request.data` property.
A list or tuple of parser classes, that determines the default set of parsers
used when accessing the `request.data` property.
Default:
@ -63,7 +71,9 @@ Default:
#### 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.
A list or tuple of authentication classes, that determines the default set of
authenticators used when accessing the `request.user` or `request.auth`
properties.
Default:
@ -74,7 +84,9 @@ Default:
#### DEFAULT_PERMISSION_CLASSES
A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list.
A list or tuple of permission classes, that determines the default set of
permissions checked at the start of a view. Permission must be granted by every
class in the list.
Default:
@ -84,13 +96,15 @@ Default:
#### DEFAULT_THROTTLE_CLASSES
A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.
A list or tuple of throttle classes, that determines the default set of
throttles checked at the start of a view.
Default: `()`
#### DEFAULT_CONTENT_NEGOTIATION_CLASS
A content negotiation class, that determines how a renderer is selected for the response, given an incoming request.
A content negotiation class, that determines how a renderer is selected for the
response, given an incoming request.
Default: `'rest_framework.negotiation.DefaultContentNegotiation'`
@ -123,13 +137,15 @@ If set to `None` then generic filtering is disabled.
**This setting has been removed.**
See the pagination documentation for further guidance on [setting the pagination style](pagination.md#modifying-the-pagination-style).
See the pagination documentation for further guidance on [setting the
pagination style](pagination.md#modifying-the-pagination-style).
---
#### PAGE_SIZE
The default page size to use for pagination. If set to `None`, pagination is disabled by default.
The default page size to use for pagination. If set to `None`, pagination is
disabled by default.
Default: `None`
@ -139,7 +155,8 @@ Default: `None`
**This setting has been removed.**
See the pagination documentation for further guidance on [setting the pagination style](pagination.md#modifying-the-pagination-style).
See the pagination documentation for further guidance on [setting the
pagination style](pagination.md#modifying-the-pagination-style).
---
@ -149,19 +166,22 @@ See the pagination documentation for further guidance on [setting the pagination
**This setting is pending deprecation.**
See the pagination documentation for further guidance on [setting the pagination style](pagination.md#modifying-the-pagination-style).
See the pagination documentation for further guidance on [setting the
pagination style](pagination.md#modifying-the-pagination-style).
---
### SEARCH_PARAM
The name of a query parameter, which can be used to specify the search term used by `SearchFilter`.
The name of a query parameter, which can be used to specify the search term
used by `SearchFilter`.
Default: `search`
#### ORDERING_PARAM
The name of a query parameter, which can be used to specify the ordering of results returned by `OrderingFilter`.
The name of a query parameter, which can be used to specify the ordering of
results returned by `OrderingFilter`.
Default: `ordering`
@ -171,19 +191,23 @@ Default: `ordering`
#### DEFAULT_VERSION
The value that should be used for `request.version` when no versioning information is present.
The value that should be used for `request.version` when no versioning
information is present.
Default: `None`
#### ALLOWED_VERSIONS
If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set.
If set, this value will restrict the set of versions that may be returned by
the versioning scheme, and will raise an error if the provided version if not
in this set.
Default: `None`
#### VERSION_PARAM
The string that should used for any versioning parameters, such as in the media type or URL query parameters.
The string that should used for any versioning parameters, such as in the media
type or URL query parameters.
Default: `'version'`
@ -195,13 +219,15 @@ Default: `'version'`
#### UNAUTHENTICATED_USER
The class that should be used to initialize `request.user` for unauthenticated requests.
The class that should be used to initialize `request.user` for unauthenticated
requests.
Default: `django.contrib.auth.models.AnonymousUser`
#### UNAUTHENTICATED_TOKEN
The class that should be used to initialize `request.auth` for unauthenticated requests.
The class that should be used to initialize `request.auth` for unauthenticated
requests.
Default: `None`
@ -223,7 +249,9 @@ Default: `'multipart'`
The renderer classes that are supported when building test requests.
The format of any of these renderer classes may be used when constructing a test request, for example: `client.post('/users', {'username': 'jamie'}, format='json')`
The format of any of these renderer classes may be used when constructing a
test request, for example: `client.post('/users', {'username': 'jamie'},
format='json')`
Default:
@ -238,7 +266,9 @@ Default:
#### URL_FORMAT_OVERRIDE
The name of a URL parameter that may be used to override the default content negotiation `Accept` header behavior, by using a `format=…` query parameter in the request URL.
The name of a URL parameter that may be used to override the default content
negotiation `Accept` header behavior, by using a `format=…` query parameter in
the request URL.
For example: `http://example.com/organizations/?format=csv`
@ -248,7 +278,9 @@ Default: `'format'`
#### FORMAT_SUFFIX_KWARG
The name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using `format_suffix_patterns` to include suffixed URL patterns.
The name of a parameter in the URL conf that may be used to provide a format
suffix. This setting is applied when using `format_suffix_patterns` to include
suffixed URL patterns.
For example: `http://example.com/organizations.csv/`
@ -258,11 +290,15 @@ Default: `'format'`
## Date and time formatting
*The following settings are used to control how date and time representations may be parsed and rendered.*
*The following settings are used to control how date and time representations
may be parsed and rendered.*
#### DATETIME_FORMAT
A format string that should be used by default for rendering the output of `DateTimeField` serializer fields. If `None`, then `DateTimeField` serializer fields will return Python `datetime` objects, and the datetime encoding will be determined by the renderer.
A format string that should be used by default for rendering the output of
`DateTimeField` serializer fields. If `None`, then `DateTimeField` serializer
fields will return Python `datetime` objects, and the datetime encoding will be
determined by the renderer.
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
@ -270,41 +306,55 @@ Default: `'iso-8601'`
#### DATETIME_INPUT_FORMATS
A list of format strings that should be used by default for parsing inputs to `DateTimeField` serializer fields.
A list of format strings that should be used by default for parsing inputs to
`DateTimeField` serializer fields.
May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings.
May be a list including the string `'iso-8601'` or Python [strftime
format][strftime] strings.
Default: `['iso-8601']`
#### DATE_FORMAT
A format string that should be used by default for rendering the output of `DateField` serializer fields. If `None`, then `DateField` serializer fields will return Python `date` objects, and the date encoding will be determined by the renderer.
A format string that should be used by default for rendering the output of
`DateField` serializer fields. If `None`, then `DateField` serializer fields
will return Python `date` objects, and the date encoding will be determined by
the renderer.
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime]
string.
Default: `'iso-8601'`
#### DATE_INPUT_FORMATS
A list of format strings that should be used by default for parsing inputs to `DateField` serializer fields.
A list of format strings that should be used by default for parsing inputs to
`DateField` serializer fields.
May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings.
May be a list including the string `'iso-8601'` or Python [strftime
format][strftime] strings.
Default: `['iso-8601']`
#### TIME_FORMAT
A format string that should be used by default for rendering the output of `TimeField` serializer fields. If `None`, then `TimeField` serializer fields will return Python `time` objects, and the time encoding will be determined by the renderer.
A format string that should be used by default for rendering the output of
`TimeField` serializer fields. If `None`, then `TimeField` serializer fields
will return Python `time` objects, and the time encoding will be determined by
the renderer.
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string.
May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime]
string.
Default: `'iso-8601'`
#### TIME_INPUT_FORMATS
A list of format strings that should be used by default for parsing inputs to `TimeField` serializer fields.
A list of format strings that should be used by default for parsing inputs to
`TimeField` serializer fields.
May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings.
May be a list including the string `'iso-8601'` or Python [strftime
format][strftime] strings.
Default: `['iso-8601']`
@ -322,29 +372,39 @@ When set to `False`, JSON responses will escape non-ascii characters, like so:
{"unicode black star":"\u2605"}
Both styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses.
Both styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON.
The unicode style is preferred as being more user-friendly when inspecting API
responses.
Default: `True`
#### COMPACT_JSON
When set to `True`, JSON responses will return compact representations, with no spacing after `':'` and `','` characters. For example:
When set to `True`, JSON responses will return compact representations, with no
spacing after `':'` and `','` characters. For example:
{"is_admin":false,"email":"jane@example"}
When set to `False`, JSON responses will return slightly more verbose representations, like so:
When set to `False`, JSON responses will return slightly more verbose
representations, like so:
{"is_admin": false, "email": "jane@example"}
The default style is to return minified responses, in line with [Heroku's API design guidelines][heroku-minified-json].
The default style is to return minified responses, in line with [Heroku's API
design guidelines][heroku-minified-json].
Default: `True`
#### COERCE_DECIMAL_TO_STRING
When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations.
When returning decimal objects in API representations that do not support a
native decimal type, it is normally best to return the value as a string. This
avoids the loss of precision that occurs with binary floating point
implementations.
When set to `True`, the serializer `DecimalField` class will return strings instead of `Decimal` objects. When set to `False`, serializers will return `Decimal` objects, which the default JSON encoder will return as floats.
When set to `True`, the serializer `DecimalField` class will return strings
instead of `Decimal` objects. When set to `False`, serializers will return
`Decimal` objects, which the default JSON encoder will return as floats.
Default: `True`
@ -352,7 +412,8 @@ Default: `True`
## View names and descriptions
**The following settings are used to generate the view names and descriptions, as used in responses to `OPTIONS` requests, and as used in the browsable API.**
**The following settings are used to generate the view names and descriptions,
as used in responses to `OPTIONS` requests, and as used in the browsable API.**
#### VIEW_NAME_FUNCTION
@ -362,23 +423,31 @@ This should be a function with the following signature:
view_name(cls, suffix=None)
* `cls`: The view class. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing `cls.__name__`.
* `suffix`: The optional suffix used when differentiating individual views in a viewset.
* `cls`: The view class. Typically the name function would inspect the name of
the class when generating a descriptive name, by accessing `cls.__name__`.
* `suffix`: The optional suffix used when differentiating individual views in a
viewset.
Default: `'rest_framework.views.get_view_name'`
#### VIEW_DESCRIPTION_FUNCTION
A string representing the function that should be used when generating view descriptions.
A string representing the function that should be used when generating view
descriptions.
This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support `rst` markup in your view docstrings being output in the browsable API.
This setting can be changed to support markup styles other than the default
markdown. For example, you can use it to support `rst` markup in your view
docstrings being output in the browsable API.
This should be a function with the following signature:
view_description(cls, html=False)
* `cls`: The view class. Typically the description function would inspect the docstring of the class when generating a description, by accessing `cls.__doc__`
* `html`: A boolean indicating if HTML output is required. `True` when used in the browsable API, and `False` when used in generating `OPTIONS` responses.
* `cls`: The view class. Typically the description function would inspect the
docstring of the class when generating a description, by accessing
`cls.__doc__`
* `html`: A boolean indicating if HTML output is required. `True` when used in
the browsable API, and `False` when used in generating `OPTIONS` responses.
Default: `'rest_framework.views.get_view_description'`
@ -388,9 +457,13 @@ Default: `'rest_framework.views.get_view_description'`
#### EXCEPTION_HANDLER
A string representing the function that should be used when returning a response for any given exception. If the function returns `None`, a 500 error will be raised.
A string representing the function that should be used when returning a
response for any given exception. If the function returns `None`, a 500 error
will be raised.
This setting can be changed to support error responses other than the default `{"detail": "Failure..."}` responses. For example, you can use it to provide API responses like `{"errors": [{"message": "Failure...", "code": ""} ...]}`.
This setting can be changed to support error responses other than the default
`{"detail": "Failure..."}` responses. For example, you can use it to provide
API responses like `{"errors": [{"message": "Failure...", "code": ""} ...]}`.
This should be a function with the following signature:
@ -402,19 +475,24 @@ Default: `'rest_framework.views.exception_handler'`
#### NON_FIELD_ERRORS_KEY
A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors.
A string representing the key that should be used for serializer errors that do
not refer to a specific field, but are instead general errors.
Default: `'non_field_errors'`
#### URL_FIELD_NAME
A string representing the key that should be used for the URL fields generated by `HyperlinkedModelSerializer`.
A string representing the key that should be used for the URL fields generated
by `HyperlinkedModelSerializer`.
Default: `'url'`
#### NUM_PROXIES
An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to `None` then less strict IP matching will be used by the throttle classes.
An integer of 0 or more, that may be used to specify the number of application
proxies that the API runs behind. This allows throttling to more accurately
identify client IP addresses. If set to `None` then less strict IP matching
will be used by the throttle classes.
Default: `None`

View File

@ -2,11 +2,15 @@ source: status.py
# Status Codes
> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in
> the error code "418 I'm a teapot". The resulting entity body MAY be short
> and stout.
>
> &mdash; [RFC 2324][rfc2324], Hyper Text Coffee Pot Control Protocol
Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make more code more obvious and readable.
Using bare status codes in your responses isn't recommended. REST framework
includes a set of named constants that you can use to make more code more
obvious and readable.
from rest_framework import status
from rest_framework.response import Response
@ -15,9 +19,11 @@ Using bare status codes in your responses isn't recommended. REST framework inc
content = {'please move along': 'nothing to see here'}
return Response(content, status=status.HTTP_404_NOT_FOUND)
The full set of HTTP status codes included in the `status` module is listed below.
The full set of HTTP status codes included in the `status` module is listed
below.
The module also includes a set of helper functions for testing if a status code is in a given range.
The module also includes a set of helper functions for testing if a status code
is in a given range.
from rest_framework import status
from rest_framework.test import APITestCase
@ -34,14 +40,16 @@ and [RFC 6585][rfc6585].
## Informational - 1xx
This class of status code indicates a provisional response. There are no 1xx status codes used in REST framework by default.
This class of status code indicates a provisional response. There are no 1xx
status codes used in REST framework by default.
HTTP_100_CONTINUE
HTTP_101_SWITCHING_PROTOCOLS
## Successful - 2xx
This class of status code indicates that the client's request was successfully received, understood, and accepted.
This class of status code indicates that the client's request was successfully
received, understood, and accepted.
HTTP_200_OK
HTTP_201_CREATED
@ -54,7 +62,8 @@ This class of status code indicates that the client's request was successfully r
## Redirection - 3xx
This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.
This class of status code indicates that further action needs to be taken by
the user agent in order to fulfill the request.
HTTP_300_MULTIPLE_CHOICES
HTTP_301_MOVED_PERMANENTLY
@ -67,7 +76,10 @@ This class of status code indicates that further action needs to be taken by the
## Client Error - 4xx
The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
The 4xx class of status code is intended for cases in which the client seems to
have erred. Except when responding to a HEAD request, the server SHOULD
include an entity containing an explanation of the error situation, and whether
it is a temporary or permanent condition.
HTTP_400_BAD_REQUEST
HTTP_401_UNAUTHORIZED
@ -97,7 +109,11 @@ The 4xx class of status code is intended for cases in which the client seems to
## Server Error - 5xx
Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
Response status codes beginning with the digit "5" indicate cases in which the
server is aware that it has erred or is incapable of performing the request.
Except when responding to a HEAD request, the server SHOULD include an entity
containing an explanation of the error situation, and whether it is a temporary
or permanent condition.
HTTP_500_INTERNAL_SERVER_ERROR
HTTP_501_NOT_IMPLEMENTED
@ -110,7 +126,8 @@ Response status codes beginning with the digit "5" indicate cases in which the s
## Helper functions
The following helper functions are available for identifying the category of the response code.
The following helper functions are available for identifying the category of
the response code.
is_informational() # 1xx
is_success() # 2xx

View File

@ -6,7 +6,8 @@ source: test.py
>
> &mdash; [Jacob Kaplan-Moss][cite]
REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests.
REST framework includes a few helper classes that extend Django's existing test
framework, and improve support for making API requests.
# APIRequestFactory
@ -14,7 +15,10 @@ Extends [Django's existing `RequestFactory` class][requestfactory].
## Creating test requests
The `APIRequestFactory` class supports an almost identical API to Django's standard `RequestFactory` class. This means that the standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available.
The `APIRequestFactory` class supports an almost identical API to Django's
standard `RequestFactory` class. This means that the standard `.get()`,
`.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()`
methods are all available.
from rest_framework.test import APIRequestFactory
@ -24,32 +28,41 @@ The `APIRequestFactory` class supports an almost identical API to Django's stand
#### Using the `format` argument
Methods which create a request body, such as `post`, `put` and `patch`, include a `format` argument, which make it easy to generate requests using a content type other than multipart form data. For example:
Methods which create a request body, such as `post`, `put` and `patch`, include
a `format` argument, which make it easy to generate requests using a content
type other than multipart form data. For example:
# Create a JSON POST request
factory = APIRequestFactory()
request = factory.post('/notes/', {'title': 'new idea'}, format='json')
By default the available formats are `'multipart'` and `'json'`. For compatibility with Django's existing `RequestFactory` the default format is `'multipart'`.
By default the available formats are `'multipart'` and `'json'`. For
compatibility with Django's existing `RequestFactory` the default format is
`'multipart'`.
To support a wider set of request formats, or change the default format, [see the configuration section][configuration].
To support a wider set of request formats, or change the default format, [see
the configuration section][configuration].
#### Explicitly encoding the request body
If you need to explicitly encode the request body, you can do so by setting the `content_type` flag. For example:
If you need to explicitly encode the request body, you can do so by setting the
`content_type` flag. For example:
request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')
#### PUT and PATCH with form data
One difference worth noting between Django's `RequestFactory` and REST framework's `APIRequestFactory` is that multipart form data will be encoded for methods other than just `.post()`.
One difference worth noting between Django's `RequestFactory` and REST
framework's `APIRequestFactory` is that multipart form data will be encoded for
methods other than just `.post()`.
For example, using `APIRequestFactory`, you can make a form PUT request like so:
factory = APIRequestFactory()
request = factory.put('/notes/547/', {'title': 'remember to email dave'})
Using Django's `RequestFactory`, you'd need to explicitly encode the data yourself:
Using Django's `RequestFactory`, you'd need to explicitly encode the data
yourself:
from django.test.client import encode_multipart, RequestFactory
@ -61,7 +74,9 @@ Using Django's `RequestFactory`, you'd need to explicitly encode the data yourse
## Forcing authentication
When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials.
When testing views directly using a request factory, it's often convenient to
be able to directly authenticate the request, rather than having to construct
the correct authentication credentials.
To forcibly authenticate a request, use the `force_authenticate()` method.
@ -76,9 +91,12 @@ To forcibly authenticate a request, use the `force_authenticate()` method.
force_authenticate(request, user=user)
response = view(request)
The signature for the method is `force_authenticate(request, user=None, token=None)`. When making the call, either or both of the user and token may be set.
The signature for the method is `force_authenticate(request, user=None,
token=None)`. When making the call, either or both of the user and token may
be set.
For example, when forcibly authenticating using a token, you might do something like the following:
For example, when forcibly authenticating using a token, you might do something
like the following:
user = User.objects.get(username='olivia')
request = factory.get('/accounts/django-superstars/')
@ -86,9 +104,14 @@ For example, when forcibly authenticating using a token, you might do something
---
**Note**: When using `APIRequestFactory`, the object that is returned is Django's standard `HttpRequest`, and not REST framework's `Request` object, which is only generated once the view is called.
**Note**: When using `APIRequestFactory`, the object that is returned is
Django's standard `HttpRequest`, and not REST framework's `Request` object,
which is only generated once the view is called.
This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting `.token` directly will have no effect, and setting `.user` directly will only work if session authentication is being used.
This means that setting attributes directly on the request object may not
always have the effect you expect. For example, setting `.token` directly will
have no effect, and setting `.user` directly will only work if session
authentication is being used.
# Request will only authenticate if `SessionAuthentication` is in use.
request = factory.get('/accounts/django-superstars/')
@ -99,13 +122,20 @@ This means that setting attributes directly on the request object may not always
## Forcing CSRF validation
By default, requests created with `APIRequestFactory` will not have CSRF validation applied when passed to a REST framework view. If you need to explicitly turn CSRF validation on, you can do so by setting the `enforce_csrf_checks` flag when instantiating the factory.
By default, requests created with `APIRequestFactory` will not have CSRF
validation applied when passed to a REST framework view. If you need to
explicitly turn CSRF validation on, you can do so by setting the
`enforce_csrf_checks` flag when instantiating the factory.
factory = APIRequestFactory(enforce_csrf_checks=True)
---
**Note**: It's worth noting that Django's standard `RequestFactory` doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks.
**Note**: It's worth noting that Django's standard `RequestFactory` doesn't
need to include this option, because when using regular Django the CSRF
validation takes place in middleware, which is not run when testing views
directly. When using REST framework, CSRF validation takes place inside the
view, so the request factory needs to disable view-level CSRF checks.
---
@ -115,20 +145,26 @@ Extends [Django's existing `Client` class][client].
## Making requests
The `APIClient` class supports the same request interface as Django's standard `Client` class. This means the that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. For example:
The `APIClient` class supports the same request interface as Django's standard
`Client` class. This means the that standard `.get()`, `.post()`, `.put()`,
`.patch()`, `.delete()`, `.head()` and `.options()` methods are all available.
For example:
from rest_framework.test import APIClient
client = APIClient()
client.post('/notes/', {'title': 'new idea'}, format='json')
To support a wider set of request formats, or change the default format, [see the configuration section][configuration].
To support a wider set of request formats, or change the default format, [see
the configuration section][configuration].
## Authenticating
#### .login(**kwargs)
The `login` method functions exactly as it does with Django's regular `Client` class. This allows you to authenticate requests against any views which include `SessionAuthentication`.
The `login` method functions exactly as it does with Django's regular `Client`
class. This allows you to authenticate requests against any views which
include `SessionAuthentication`.
# Make all requests in the context of a logged in session.
client = APIClient()
@ -139,11 +175,14 @@ To logout, call the `logout` method as usual.
# Log out
client.logout()
The `login` method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API.
The `login` method is appropriate for testing APIs that use session
authentication, for example web sites which include AJAX interaction with the
API.
#### .credentials(**kwargs)
The `credentials` method can be used to set headers that will then be included on all subsequent requests by the test client.
The `credentials` method can be used to set headers that will then be included
on all subsequent requests by the test client.
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
@ -153,40 +192,53 @@ The `credentials` method can be used to set headers that will then be included o
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
Note that calling `credentials` a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments.
Note that calling `credentials` a second time overwrites any existing
credentials. You can unset any existing credentials by calling the method with
no arguments.
# Stop including any credentials
client.credentials()
The `credentials` method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes.
The `credentials` method is appropriate for testing APIs that require
authentication headers, such as basic authentication, OAuth1a and OAuth2
authentication, and simple token authentication schemes.
#### .force_authenticate(user=None, token=None)
Sometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated.
Sometimes you may want to bypass authentication, and simple force all requests
by the test client to be automatically treated as authenticated.
This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests.
This can be a useful shortcut if you're testing the API but don't want to have
to construct valid authentication credentials in order to make test requests.
user = User.objects.get(username='lauren')
client = APIClient()
client.force_authenticate(user=user)
To unauthenticate subsequent requests, call `force_authenticate` setting the user and/or token to `None`.
To unauthenticate subsequent requests, call `force_authenticate` setting the
user and/or token to `None`.
client.force_authenticate(user=None)
## CSRF validation
By default CSRF validation is not applied when using `APIClient`. If you need to explicitly enable CSRF validation, you can do so by setting the `enforce_csrf_checks` flag when instantiating the client.
By default CSRF validation is not applied when using `APIClient`. If you need
to explicitly enable CSRF validation, you can do so by setting the
`enforce_csrf_checks` flag when instantiating the client.
client = APIClient(enforce_csrf_checks=True)
As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling `login()`.
As usual CSRF validation will only apply to any session authenticated views.
This means CSRF validation will only occur if the client has been logged in by
calling `login()`.
---
# Test cases
REST framework includes the following test case classes, that mirror the existing Django test case classes, but use `APIClient` instead of Django's default `Client`.
REST framework includes the following test case classes, that mirror the
existing Django test case classes, but use `APIClient` instead of Django's
default `Client`.
* `APISimpleTestCase`
* `APITransactionTestCase`
@ -195,7 +247,9 @@ REST framework includes the following test case classes, that mirror the existin
## Example
You can use any of REST framework's test case classes as you would for the regular Django test case classes. The `self.client` attribute will be an `APIClient` instance.
You can use any of REST framework's test case classes as you would for the
regular Django test case classes. The `self.client` attribute will be an
`APIClient` instance.
from django.core.urlresolvers import reverse
from rest_framework import status
@ -220,7 +274,9 @@ You can use any of REST framework's test case classes as you would for the regul
## Checking the response data
When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response.
When checking the validity of test responses it's often more convenient to
inspect the data that the response was created with, rather than inspecting the
fully rendered response.
For example, it's easier to inspect `response.data`:
@ -234,7 +290,10 @@ Instead of inspecting the result of parsing `response.content`:
## Rendering responses
If you're testing views directly using `APIRequestFactory`, the responses that are returned will not yet be rendered, as rendering of template responses is performed by Django's internal request-response cycle. In order to access `response.content`, you'll first need to render the response.
If you're testing views directly using `APIRequestFactory`, the responses that
are returned will not yet be rendered, as rendering of template responses is
performed by Django's internal request-response cycle. In order to access
`response.content`, you'll first need to render the response.
view = UserDetail.as_view()
request = factory.get('/users/4')
@ -248,7 +307,10 @@ If you're testing views directly using `APIRequestFactory`, the responses that a
## Setting the default format
The default format used to make test requests may be set using the `TEST_REQUEST_DEFAULT_FORMAT` setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your `settings.py` file:
The default format used to make test requests may be set using the
`TEST_REQUEST_DEFAULT_FORMAT` setting key. For example, to always use JSON for
test requests by default instead of standard multipart form requests, set the
following in your `settings.py` file:
REST_FRAMEWORK = {
...
@ -257,9 +319,11 @@ The default format used to make test requests may be set using the `TEST_REQUEST
## Setting the available formats
If you need to test requests using something other than multipart or json requests, you can do so by setting the `TEST_REQUEST_RENDERER_CLASSES` setting.
If you need to test requests using something other than multipart or json
requests, you can do so by setting the `TEST_REQUEST_RENDERER_CLASSES` setting.
For example, to add support for using `format='html'` in test requests, you might have something like this in your `settings.py` file.
For example, to add support for using `format='html'` in test requests, you
might have something like this in your `settings.py` file.
REST_FRAMEWORK = {
...

View File

@ -6,26 +6,40 @@ source: throttling.py
>
> [Twitter API rate limiting response][cite]
Throttling is similar to [permissions], in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.
Throttling is similar to [permissions], in that it determines if a request
should be authorized. Throttles indicate a temporary state, and are used to
control the rate of requests that clients can make to an API.
As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.
As with permissions, multiple throttles may be used. Your API might have a
restrictive throttle for unauthenticated requests, and a less restrictive
throttle for authenticated requests.
Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.
Another scenario where you might want to use multiple throttles would be if you
need to impose different constraints on different parts of the API, due to some
services being particularly resource-intensive.
Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.
Multiple throttles can also be used if you want to impose both burst throttling
rates, and sustained throttling rates. For example, you might want to limit a
user to a maximum of 60 requests per minute, and 1000 requests per day.
Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.
Throttles do not necessarily only refer to rate-limiting requests. For example
a storage service might also need to throttle against bandwidth, and a paid
data service might want to throttle against a certain number of a records being
accessed.
## How throttling is determined
As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
As with permissions and authentication, throttling in REST framework is always
defined as a list of classes.
Before running the main body of the view each throttle in the list is checked.
If any throttle check fails an `exceptions.Throttled` exception will be raised, and the main body of the view will not run.
If any throttle check fails an `exceptions.Throttled` exception will be raised,
and the main body of the view will not run.
## Setting the throttling policy
The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_CLASSES` 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_THROTTLE_CLASSES': (
@ -38,7 +52,8 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C
}
}
The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period.
The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`,
`minute`, `hour` or `day` as the throttle period.
You can also set the throttling policy on a per-view or per-viewset basis,
using the `APIView` class-based views.
@ -68,24 +83,44 @@ Or, if you're using the `@api_view` decorator with function based views.
## How clients are identified
The `X-Forwarded-For` and `Remote-Addr` HTTP headers are used to uniquely identify client IP addresses for throttling. If the `X-Forwarded-For` header is present then it will be used, otherwise the value of the `Remote-Addr` header will be used.
The `X-Forwarded-For` and `Remote-Addr` HTTP headers are used to uniquely
identify client IP addresses for throttling. If the `X-Forwarded-For` header
is present then it will be used, otherwise the value of the `Remote-Addr`
header will be used.
If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the `NUM_PROXIES` setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the `X-Forwarded-For` header, once any application proxy IP addresses have first been excluded. If set to zero, then the `Remote-Addr` header will always be used as the identifying IP address.
If you need to strictly identify unique client IP addresses, you'll need to
first configure the number of application proxies that the API runs behind by
setting the `NUM_PROXIES` setting. This setting should be an integer of zero
or more. If set to non-zero then the client IP will be identified as being the
last IP address in the `X-Forwarded-For` header, once any application proxy IP
addresses have first been excluded. If set to zero, then the `Remote-Addr`
header will always be used as the identifying IP address.
It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client.
It is important to understand that if you configure the `NUM_PROXIES` setting,
then all clients behind a unique
[NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will
be treated as a single client.
Further context on how the `X-Forwarded-For` header works, and identifying a remote client IP can be [found here][identifing-clients].
Further context on how the `X-Forwarded-For` header works, and identifying a
remote client IP can be [found here][identifing-clients].
## Setting up the cache
The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate [cache settings][cache-setting]. The default value of `LocMemCache` backend should be okay for simple setups. See Django's [cache documentation][cache-docs] for more details.
The throttle classes provided by REST framework use Django's cache backend.
You should make sure that you've set appropriate [cache
settings][cache-setting]. The default value of `LocMemCache` backend should be
okay for simple setups. See Django's [cache documentation][cache-docs] for
more details.
If you need to use a cache other than `'default'`, you can do so by creating a custom throttle class and setting the `cache` attribute. For example:
If you need to use a cache other than `'default'`, you can do so by creating a
custom throttle class and setting the `cache` attribute. For example:
class CustomAnonRateThrottle(AnonRateThrottle):
cache = get_cache('alternate')
You'll need to remember to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute.
You'll need to remember to also set your custom throttle class in the
`'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view
attribute.
---
@ -93,27 +128,39 @@ You'll need to remember to also set your custom throttle class in the `'DEFAULT_
## AnonRateThrottle
The `AnonRateThrottle` will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.
The `AnonRateThrottle` will only ever throttle unauthenticated users. The IP
address of the incoming request is used to generate a unique key to throttle
against.
The allowed request rate is determined from one of the following (in order of preference).
The allowed request rate is determined from one of the following (in order of
preference).
* The `rate` property on the class, which may be provided by overriding `AnonRateThrottle` and setting the property.
* The `rate` property on the class, which may be provided by overriding
`AnonRateThrottle` and setting the property.
* The `DEFAULT_THROTTLE_RATES['anon']` setting.
`AnonRateThrottle` is suitable if you want to restrict the rate of requests from unknown sources.
`AnonRateThrottle` is suitable if you want to restrict the rate of requests
from unknown sources.
## UserRateThrottle
The `UserRateThrottle` 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 `UserRateThrottle` 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).
The allowed request rate is determined from one of the following (in order of
preference).
* The `rate` property on the class, which may be provided by overriding `UserRateThrottle` and setting the property.
* The `rate` property on the class, which may be provided by overriding
`UserRateThrottle` and setting the property.
* The `DEFAULT_THROTTLE_RATES['user']` setting.
An API may have multiple `UserRateThrottles` in place at the same time. To do so, override `UserRateThrottle` and set a unique "scope" for each class.
An API may have multiple `UserRateThrottles` in place at the same time. To do
so, override `UserRateThrottle` and set a unique "scope" for each class.
For example, multiple user throttle rates could be implemented by using the following classes...
For example, multiple user throttle rates could be implemented by using the
following classes...
class BurstRateThrottle(UserRateThrottle):
scope = 'burst'
@ -138,9 +185,14 @@ For example, multiple user throttle rates could be implemented by using the foll
## ScopedRateThrottle
The `ScopedRateThrottle` 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 `ScopedRateThrottle` 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".
The allowed request rate is determined by the `DEFAULT_THROTTLE_RATES` setting
using a key from the request "scope".
For example, given the following views...
@ -168,21 +220,30 @@ 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.
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
To create a custom throttle, override `BaseThrottle` and implement `.allow_request(self, request, view)`. The method should return `True` if the request should be allowed, and `False` otherwise.
To create a custom throttle, override `BaseThrottle` and implement
`.allow_request(self, 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 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`.
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`.
If the `.wait()` method is implemented and the request is throttled, then a `Retry-After` header will be included in the response.
If the `.wait()` method is implemented and the request is throttled, then a
`Retry-After` header will be included in the response.
## Example
The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.
The following is an example of a rate throttle, that will randomly throttle 1
in every 10 requests.
import random

View File

@ -6,32 +6,49 @@ source: validators.py
>
> &mdash; [Django documentation][cite]
Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes.
Most of the time you're dealing with validation in REST framework you'll simply
be relying on the default field validation, or writing explicit validation
methods on serializer or field classes.
However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.
However, sometimes you'll want to place your validation logic into reusable
components, so that it can easily be reused throughout your codebase. This can
be achieved by using validator functions and validator classes.
## Validation in REST framework
Validation in Django REST framework serializers is handled a little differently to how validation works in Django's `ModelForm` class.
Validation in Django REST framework serializers is handled a little differently
to how validation works in Django's `ModelForm` class.
With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
With `ModelForm` the validation is performed partially on the form, and
partially on the model instance. With REST framework the validation is
performed entirely on the serializer class. This is advantageous for the
following reasons:
* It introduces a proper separation of concerns, making your code behavior more obvious.
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.
* It introduces a proper separation of concerns, making your code behavior more
obvious.
* It is easy to switch between using shortcut `ModelSerializer` classes and
using explicit `Serializer` classes. Any validation behavior being used for
`ModelSerializer` is simple to replicate.
* Printing the `repr` of a serializer instance will show you exactly what
validation rules it applies. There's no extra hidden validation behavior
being called on the model instance.
When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using a `Serializer` classes instead, then you need to define the validation rules explicitly.
When you're using `ModelSerializer` all of this is handled automatically for
you. If you want to drop down to using a `Serializer` classes instead, then you
need to define the validation rules explicitly.
#### Example
As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.
As an example of how REST framework uses explicit validation, we'll take a
simple model class that has a field with a uniqueness constraint.
class CustomerReportRecord(models.Model):
time_raised = models.DateTimeField(default=timezone.now, editable=False)
reference = models.CharField(unique=True, max_length=20)
description = models.TextField()
Here's a basic `ModelSerializer` that we can use for creating or updating instances of `CustomerReportRecord`:
Here's a basic `ModelSerializer` that we can use for creating or updating
instances of `CustomerReportRecord`:
class CustomerReportSerializer(serializers.ModelSerializer):
class Meta:
@ -48,9 +65,13 @@ If we open up the Django shell using `manage.py shell` we can now
reference = CharField(max_length=20, validators=[<UniqueValidator(queryset=CustomerReportRecord.objects.all())>])
description = CharField(style={'type': 'textarea'})
The interesting bit here is the `reference` field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.
The interesting bit here is the `reference` field. We can see that the
uniqueness constraint is being explicitly enforced by a validator on the
serializer field.
Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.
Because of this more explicit style REST framework includes a few validator
classes that are not available in core Django. These classes are detailed
below.
---
@ -76,14 +97,16 @@ This validator should be applied to *serializer fields*, like so:
This validator can be used to enforce `unique_together` constraints on model instances.
It has two required arguments, and a single optional `messages` argument:
* `queryset` *required* - This is the queryset against which uniqueness should be enforced.
* `fields` *required* - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.
* `queryset` *required* - This is the queryset against which uniqueness should
be enforced.
* `fields` *required* - A list or tuple of field names which should make a
unique set. These must exist as fields on the serializer class.
* `message` - The error message that should be used when validation fails.
The validator should be applied to *serializer classes*, like so:
from rest_framework.validators import UniqueTogetherValidator
class ExampleSerializer(serializers.Serializer):
# ...
class Meta:
@ -99,7 +122,10 @@ The validator should be applied to *serializer classes*, like so:
---
**Note**: The `UniqueTogetherValidation` class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
**Note**: The `UniqueTogetherValidation` class always imposes an implicit
constraint that all the fields it applies to are always treated as required.
Fields with `default` values are an exception to this as they always supply a
value even when omitted from user input.
---
@ -109,11 +135,17 @@ The validator should be applied to *serializer classes*, like so:
## UniqueForYearValidator
These validators can be used to enforce the `unique_for_date`, `unique_for_month` and `unique_for_year` constraints on model instances. They take the following arguments:
These validators can be used to enforce the `unique_for_date`,
`unique_for_month` and `unique_for_year` constraints on model instances. They
take the following arguments:
* `queryset` *required* - This is the queryset against which uniqueness should be enforced.
* `field` *required* - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.
* `date_field` *required* - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.
* `queryset` *required* - This is the queryset against which uniqueness should
be enforced.
* `field` *required* - A field name against which uniqueness in the given date
range will be validated. This must exist as a field on the serializer class.
* `date_field` *required* - A field name which will be used to determine date
range for the uniqueness constrain. This must exist as a field on the
serializer class.
* `message` - The error message that should be used when validation fails.
The validator should be applied to *serializer classes*, like so:
@ -132,50 +164,74 @@ The validator should be applied to *serializer classes*, like so:
)
]
The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class `default=...`, because the value being used for the default wouldn't be generated until after the validation has run.
The date field that is used for the validation is always required to be present
on the serializer class. You can't simply rely on a model class `default=...`,
because the value being used for the default wouldn't be generated until after
the validation has run.
There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using `ModelSerializer` you'll probably simply rely on the defaults that REST framework generates for you, but if you are using `Serializer` or simply want more explicit control, use on of the styles demonstrated below.
There are a couple of styles you may want to use for this depending on how you
want your API to behave. If you're using `ModelSerializer` you'll probably
simply rely on the defaults that REST framework generates for you, but if you
are using `Serializer` or simply want more explicit control, use on of the
styles demonstrated below.
#### Using with a writable date field.
If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a `default` argument, or by setting `required=True`.
If you want the date field to be writable the only thing worth noting is that
you should ensure that it is always available in the input data, either by
setting a `default` argument, or by setting `required=True`.
published = serializers.DateTimeField(required=True)
#### Using with a read-only date field.
If you want the date field to be visible, but not editable by the user, then set `read_only=True` and additionally set a `default=...` argument.
If you want the date field to be visible, but not editable by the user, then
set `read_only=True` and additionally set a `default=...` argument.
published = serializers.DateTimeField(read_only=True, default=timezone.now)
The field will not be writable to the user, but the default value will still be passed through to the `validated_data`.
The field will not be writable to the user, but the default value will still be
passed through to the `validated_data`.
#### Using with a hidden date field.
If you want the date field to be entirely hidden from the user, then use `HiddenField`. This field type does not accept user input, but instead always returns it's default value to the `validated_data` in the serializer.
If you want the date field to be entirely hidden from the user, then use
`HiddenField`. This field type does not accept user input, but instead always
returns it's default value to the `validated_data` in the serializer.
published = serializers.HiddenField(default=timezone.now)
---
**Note**: The `UniqueFor<Range>Validation` classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input.
**Note**: The `UniqueFor<Range>Validation` classes always imposes an implicit
constraint that the fields they are applied to are always treated as required.
Fields with `default` values are an exception to this as they always supply a
value even when omitted from user input.
---
# Advanced field defaults
Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that *is* available as input to the validator.
Validators that are applied across multiple fields in the serializer can
sometimes require a field input that should not be provided by the API client,
but that *is* available as input to the validator.
Two patterns that you may want to use for this sort of validation include:
* Using `HiddenField`. This field will be present in `validated_data` but *will not* be used in the serializer output representation.
* Using a standard field with `read_only=True`, but that also includes a `default=…` argument. This field *will* be used in the serializer output representation, but cannot be set directly by the user.
* Using `HiddenField`. This field will be present in `validated_data` but *will
not* be used in the serializer output representation.
* Using a standard field with `read_only=True`, but that also includes a
`default=…` argument. This field *will* be used in the serializer output
representation, but cannot be set directly by the user.
REST framework includes a couple of defaults that may be useful in this context.
REST framework includes a couple of defaults that may be useful in this
context.
#### CurrentUserDefault
A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.
A default class that can be used to represent the current user. In order to use
this, the 'request' must have been provided as part of the context dictionary
when instantiating the serializer.
owner = serializers.HiddenField(
default=serializers.CurrentUserDefault()
@ -183,9 +239,11 @@ A default class that can be used to represent the current user. In order to use
#### CreateOnlyDefault
A default class that can be used to *only set a default argument during create operations*. During updates the field is omitted.
A default class that can be used to *only set a default argument during create
operations*. During updates the field is omitted.
It takes a single argument, which is the default value or callable that should be used during create operations.
It takes a single argument, which is the default value or callable that should
be used during create operations.
created_at = serializers.DateTimeField(
read_only=True,
@ -273,7 +331,8 @@ A validator may be any callable that raises a `serializers.ValidationError` on f
## Class-based
To write a class-based validator, use the `__call__` method. Class-based validators are useful as they allow you to parameterize and reuse behavior.
To write a class-based validator, use the `__call__` method. Class-based
validators are useful as they allow you to parameterize and reuse behavior.
class MultipleOf(object):
def __init__(self, base):
@ -286,7 +345,9 @@ To write a class-based validator, use the `__call__` method. Class-based validat
#### Using `set_context()`
In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a `set_context` method on a class-based validator.
In some advanced cases you might want a validator to be passed the serializer
field it is being used with as additional context. You can do so by declaring a
`set_context` method on a class-based validator.
def set_context(self, serializer_field):
# Determine if this is an update or a create operation.

View File

@ -6,21 +6,31 @@ source: versioning.py
>
> &mdash; [Roy Fielding][cite].
API versioning allows you to alter behavior between different clients. REST framework provides for a number of different versioning schemes.
API versioning allows you to alter behavior between different clients. REST
framework provides for a number of different versioning schemes.
Versioning is determined by the incoming client request, and may either be based on the request URL, or based on the request headers.
Versioning is determined by the incoming client request, and may either be
based on the request URL, or based on the request headers.
There are a number of valid approaches to approaching versioning. [Non-versioned systems can also be appropriate][roy-fielding-on-versioning], particularly if you're engineering for very long-term systems with multiple clients outside of your control.
There are a number of valid approaches to approaching versioning.
[Non-versioned systems can also be appropriate][roy-fielding-on-versioning],
particularly if you're engineering for very long-term systems with multiple
clients outside of your control.
## Versioning with REST framework
When API versioning is enabled, the `request.version` attribute will contain a string that corresponds to the version requested in the incoming client request.
When API versioning is enabled, the `request.version` attribute will contain a
string that corresponds to the version requested in the incoming client
request.
By default, versioning is not enabled, and `request.version` will always return `None`.
By default, versioning is not enabled, and `request.version` will always return
`None`.
#### Varying behavior based on the version
How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example:
How you vary the API behavior is up to you, but one example you might typically
want is to switch to a different serialization style in a newer version. For
example:
def get_serializer_class(self):
if self.request.version == 'v1':
@ -29,20 +39,29 @@ How you vary the API behavior is up to you, but one example you might typically
#### Reversing URLs for versioned APIs
The `reverse` function included by REST framework ties in with the versioning scheme. You need to make sure to include the current `request` as a keyword argument, like so.
The `reverse` function included by REST framework ties in with the versioning
scheme. You need to make sure to include the current `request` as a keyword
argument, like so.
from rest_framework.reverse import reverse
reverse('bookings-list', request=request)
The above function will apply any URL transformations appropriate to the request version. For example:
The above function will apply any URL transformations appropriate to the
request version. For example:
* If `NamespacedVersioning` was being used, and the API version was 'v1', then the URL lookup used would be `'v1:bookings-list'`, which might resolve to a URL like `http://example.org/v1/bookings/`.
* If `QueryParameterVersioning` was being used, and the API version was `1.0`, then the returned URL might be something like `http://example.org/bookings/?version=1.0`
* If `NamespacedVersioning` was being used, and the API version was 'v1', then
the URL lookup used would be `'v1:bookings-list'`, which might resolve to a
URL like `http://example.org/v1/bookings/`.
* If `QueryParameterVersioning` was being used, and the API version was `1.0`,
then the returned URL might be something like
`http://example.org/bookings/?version=1.0`
#### Versioned APIs and hyperlinked serializers
When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer.
When using hyperlinked serialization styles together with a URL based
versioning scheme make sure to include the request as context to the
serializer.
def get(self, request):
queryset = Booking.objects.all()
@ -59,9 +78,13 @@ The versioning scheme is defined by the `DEFAULT_VERSIONING_CLASS` settings key.
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'
}
Unless it is explicitly set, the value for `DEFAULT_VERSIONING_CLASS` will be `None`. In this case the `request.version` attribute will always return `None`.
Unless it is explicitly set, the value for `DEFAULT_VERSIONING_CLASS` will be
`None`. In this case the `request.version` attribute will always return `None`.
You can also set the versioning scheme on an individual view. Typically you won't need to do this, as it makes more sense to have a single versioning scheme used globally. If you do need to do so, use the `versioning_class` attribute.
You can also set the versioning scheme on an individual view. Typically you
won't need to do this, as it makes more sense to have a single versioning
scheme used globally. If you do need to do so, use the `versioning_class`
attribute.
class ProfileList(APIView):
versioning_class = versioning.QueryParameterVersioning
@ -70,11 +93,21 @@ You can also set the versioning scheme on an individual view. Typically you won'
The following settings keys are also used to control versioning:
* `DEFAULT_VERSION`. The value that should be used for `request.version` when no versioning information is present. Defaults to `None`.
* `ALLOWED_VERSIONS`. If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version is not in this set. Note that the value used for the `DEFAULT_VERSION` setting is always considered to be part of the `ALLOWED_VERSIONS` set (unless it is `None`). Defaults to `None`.
* `VERSION_PARAM`. The string that should be used for any versioning parameters, such as in the media type or URL query parameters. Defaults to `'version'`.
* `DEFAULT_VERSION`. The value that should be used for `request.version` when
no versioning information is present. Defaults to `None`.
* `ALLOWED_VERSIONS`. If set, this value will restrict the set of versions that
may be returned by the versioning scheme, and will raise an error if the
provided version is not in this set. Note that the value used for the
`DEFAULT_VERSION` setting is always considered to be part of the
`ALLOWED_VERSIONS` set (unless it is `None`). Defaults to `None`.
* `VERSION_PARAM`. The string that should be used for any versioning
parameters, such as in the media type or URL query parameters. Defaults to
`'version'`.
You can also set your versioning class plus those three values on a per-view or a per-viewset basis by defining your own versioning scheme and using the `default_version`, `allowed_versions` and `version_param` class variables. For example, if you want to use `URLPathVersioning`:
You can also set your versioning class plus those three values on a per-view or
a per-viewset basis by defining your own versioning scheme and using the
`default_version`, `allowed_versions` and `version_param` class variables. For
example, if you want to use `URLPathVersioning`:
from rest_framework.versioning import URLPathVersioning
from rest_framework.views import APIView
@ -93,7 +126,9 @@ You can also set your versioning class plus those three values on a per-view or
## AcceptHeaderVersioning
This scheme requires the client to specify the version as part of the media type in the `Accept` header. The version is included as a media type parameter, that supplements the main media type.
This scheme requires the client to specify the version as part of the media
type in the `Accept` header. The version is included as a media type parameter,
that supplements the main media type.
Here's an example HTTP request using the accept header versioning style.
@ -101,9 +136,12 @@ Here's an example HTTP request using the accept header versioning style.
Host: example.com
Accept: application/json; version=1.0
In the example request above `request.version` attribute would return the string `'1.0'`.
In the example request above `request.version` attribute would return the
string `'1.0'`.
Versioning based on accept headers is [generally considered][klabnik-guidelines] as [best practice][heroku-guidelines], although other styles may be suitable depending on your client requirements.
Versioning based on accept headers is [generally
considered][klabnik-guidelines] as [best practice][heroku-guidelines], although
other styles may be suitable depending on your client requirements.
#### Using accept headers with vendor media types
@ -126,7 +164,9 @@ This scheme requires the client to specify the version as part of the URL path.
Host: example.com
Accept: application/json
Your URL conf must include a pattern that matches the version with a `'version'` keyword argument, so that this information is available to the versioning scheme.
Your URL conf must include a pattern that matches the version with a
`'version'` keyword argument, so that this information is available to the
versioning scheme.
urlpatterns = [
url(
@ -143,15 +183,19 @@ Your URL conf must include a pattern that matches the version with a `'version'`
## NamespaceVersioning
To the client, this scheme is the same as `URLPathVersioning`. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments.
To the client, this scheme is the same as `URLPathVersioning`. The only
difference is how it is configured in your Django application, as it uses URL
namespacing, instead of URL keyword arguments.
GET /v1/something/ HTTP/1.1
Host: example.com
Accept: application/json
With this scheme the `request.version` attribute is determined based on the `namespace` that matches the incoming request path.
With this scheme the `request.version` attribute is determined based on the
`namespace` that matches the incoming request path.
In the following example we're giving a set of views two different possible URL prefixes, each under a different namespace:
In the following example we're giving a set of views two different possible URL
prefixes, each under a different namespace:
# bookings/urls.py
urlpatterns = [
@ -165,13 +209,18 @@ In the following example we're giving a set of views two different possible URL
url(r'^v2/bookings/', include('bookings.urls', namespace='v2'))
]
Both `URLPathVersioning` and `NamespaceVersioning` are reasonable if you just need a simple versioning scheme. The `URLPathVersioning` approach might be better suitable for small ad-hoc projects, and the `NamespaceVersioning` is probably easier to manage for larger projects.
Both `URLPathVersioning` and `NamespaceVersioning` are reasonable if you just
need a simple versioning scheme. The `URLPathVersioning` approach might be
better suitable for small ad-hoc projects, and the `NamespaceVersioning` is
probably easier to manage for larger projects.
## HostNameVersioning
The hostname versioning scheme requires the client to specify the requested version as part of the hostname in the URL.
The hostname versioning scheme requires the client to specify the requested
version as part of the hostname in the URL.
For example the following is an HTTP request to the `http://v1.example.com/bookings/` URL:
For example the following is an HTTP request to the
`http://v1.example.com/bookings/` URL:
GET /bookings/ HTTP/1.1
Host: v1.example.com
@ -181,11 +230,17 @@ By default this implementation expects the hostname to match this simple regular
^([a-zA-Z0-9]+)\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+$
Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname.
Note that the first group is enclosed in brackets, indicating that this is the
matched portion of the hostname.
The `HostNameVersioning` scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as `127.0.0.1`. There are various online services which you to [access localhost with a custom subdomain][lvh] which you may find helpful in this case.
The `HostNameVersioning` scheme can be awkward to use in debug mode as you will
typically be accessing a raw IP address such as `127.0.0.1`. There are various
online services which you to [access localhost with a custom subdomain][lvh]
which you may find helpful in this case.
Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions.
Hostname based versioning can be particularly useful if you have requirements
to route incoming requests to different servers based on the version, as you
can configure different DNS records for different API versions.
## QueryParameterVersioning
@ -199,17 +254,21 @@ This scheme is a simple style that includes the version as a query parameter in
# Custom versioning schemes
To implement a custom versioning scheme, subclass `BaseVersioning` and override the `.determine_version` method.
To implement a custom versioning scheme, subclass `BaseVersioning` and override
the `.determine_version` method.
## Example
The following example uses a custom `X-API-Version` header to determine the requested version.
The following example uses a custom `X-API-Version` header to determine the
requested version.
class XAPIVersionScheme(versioning.BaseVersioning):
def determine_version(self, request, *args, **kwargs):
return request.META.get('HTTP_X_API_VERSION', None)
If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the `.reverse()` method on the class. See the source code for examples.
If your versioning scheme is based on the request URL, you will also want to
alter how versioned URLs are determined. In order to do so you should override
the `.reverse()` method on the class. See the source code for examples.
[cite]: http://www.slideshare.net/evolve_conference/201308-fielding-evolve/31
[roy-fielding-on-versioning]: http://www.infoq.com/articles/roy-fielding-on-versioning

View File

@ -7,16 +7,27 @@ source: decorators.py
>
> &mdash; [Reinout van Rees][cite]
REST framework provides an `APIView` class, which subclasses Django's `View` class.
REST framework provides an `APIView` class, which subclasses Django's `View`
class.
`APIView` classes are different from regular `View` classes in the following ways:
`APIView` classes are different from regular `View` classes in the following
ways:
* Requests passed to the handler methods will be REST framework's `Request` instances, not Django's `HttpRequest` instances.
* Handler methods may return REST framework's `Response`, instead of Django's `HttpResponse`. The view will manage content negotiation and setting the correct renderer on the response.
* Any `APIException` exceptions will be caught and mediated into appropriate responses.
* Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.
* Requests passed to the handler methods will be REST framework's `Request`
instances, not Django's `HttpRequest` instances.
* Handler methods may return REST framework's `Response`, instead of Django's
`HttpResponse`. The view will manage content negotiation and setting the
correct renderer on the response.
* Any `APIException` exceptions will be caught and mediated into appropriate
responses.
* Incoming requests will be authenticated and appropriate permission and/or
throttle checks will be run before dispatching the request to the handler
method.
Using the `APIView` class is pretty much the same as using a regular `View` class, as usual, the incoming request is dispatched to an appropriate handler method such as `.get()` or `.post()`. Additionally, a number of attributes may be set on the class that control various aspects of the API policy.
Using the `APIView` class is pretty much the same as using a regular `View`
class, as usual, the incoming request is dispatched to an appropriate handler
method such as `.get()` or `.post()`. Additionally, a number of attributes may
be set on the class that control various aspects of the API policy.
For example:
@ -59,7 +70,8 @@ The following attributes control the pluggable aspects of API views.
## API policy instantiation methods
The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.
The following methods are used by REST framework to instantiate the various
pluggable API policies. You won't typically need to override these methods.
### .get_renderers(self)
@ -86,32 +98,42 @@ The following methods are called before dispatching to the handler method.
## Dispatch methods
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()`, `patch()` and `.delete()`.
These perform any actions that need to occur before or after calling the
handler methods such as `.get()`, `.post()`, `put()`, `patch()` and
`.delete()`.
### .initial(self, request, \*args, **kwargs)
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.
This method is used to enforce permissions and throttling, and perform content
negotiation.
You won't typically need to override this method.
### .handle_exception(self, exc)
Any exception thrown by the handler method will be passed to this method, which either returns a `Response` instance, or re-raises the exception.
Any 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.
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.
If you need to customize the error responses your API returns you should
subclass this method.
### .initialize_request(self, request, \*args, **kwargs)
Ensures that the request object that is passed to the handler method is an instance of `Request`, rather than the usual Django `HttpRequest`.
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.
### .finalize_response(self, request, response, \*args, **kwargs)
Ensures that any `Response` object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.
Ensures that any `Response` object returned from the handler method will be
rendered into the correct content type, as determined by the content
negotiation.
You won't typically need to override this method.
@ -123,13 +145,19 @@ You won't typically need to override this method.
>
> &mdash; [Nick Coghlan][cite2]
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.
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.
## @api_view()
**Signature:** `@api_view(http_method_names=['GET'])`
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:
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
@ -137,9 +165,12 @@ The core of this functionality is the `api_view` decorator, which takes a list o
def hello_world(request):
return Response({"message": "Hello, world!"})
This view will use the default renderers, parsers, authentication classes etc specified in the [settings].
This view will use the default renderers, parsers, authentication classes etc
specified in the [settings].
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so:
By default only `GET` methods will be accepted. Other methods will respond with
"405 Method Not Allowed". To alter this behavior, specify which methods the
view allows, like so:
@api_view(['GET', 'POST'])
def hello_world(request):
@ -149,7 +180,12 @@ By default only `GET` methods will be accepted. Other methods will respond with
## 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:
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
@ -162,7 +198,8 @@ To override the default settings, REST framework provides a set of additional de
def view(request):
return Response({"message": "Hello for today! See you tomorrow!"})
These decorators correspond to the attributes set on `APIView` subclasses, described above.
These decorators correspond to the attributes set on `APIView` subclasses,
described above.
The available decorators are:
@ -172,7 +209,8 @@ The available decorators are:
* `@throttle_classes(...)`
* `@permission_classes(...)`
Each of these decorators takes a single argument which must be a list or tuple of 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

View File

@ -2,18 +2,28 @@ source: viewsets.py
# ViewSets
> After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.
> After routing has determined which controller to use for a request, your
> controller is responsible for making sense of the request and producing the
> appropriate output.
>
> &mdash; [Ruby on Rails Documentation][cite]
Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
Django REST framework allows you to combine the logic for a set of related
views in a single class, called a `ViewSet`. In other frameworks you may also
find conceptually similar implementations named something like 'Resources' or
'Controllers'.
A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`.
A `ViewSet` class is simply **a type of class-based View, that does not provide
any method handlers** such as `.get()` or `.post()`, and instead provides
actions such as `.list()` and `.create()`.
The method handlers for a `ViewSet` are only bound to the corresponding actions at the point of finalizing the view, using the `.as_view()` method.
The method handlers for a `ViewSet` are only bound to the corresponding actions
at the point of finalizing the view, using the `.as_view()` method.
Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.
Typically, rather than explicitly registering the views in a viewset in the
urlconf, you'll register the viewset with a router class, that automatically
determines the urlconf for you.
## Example
@ -45,7 +55,8 @@ If we need to, we can bind this viewset into two separate views, like so:
user_list = UserViewSet.as_view({'get': 'list'})
user_detail = UserViewSet.as_view({'get': 'retrieve'})
Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated.
Typically we wouldn't do this, but would instead register the viewset with a
router, and allow the urlconf to be automatically generated.
from myapp.views import UserViewSet
from rest_framework.routers import DefaultRouter
@ -54,7 +65,8 @@ Typically we wouldn't do this, but would instead register the viewset with a rou
router.register(r'users', UserViewSet)
urlpatterns = router.urls
Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example:
Rather than writing your own viewsets, you'll often want to use the existing
base classes that provide a default set of behavior. For example:
class UserViewSet(viewsets.ModelViewSet):
"""
@ -63,16 +75,25 @@ Rather than writing your own viewsets, you'll often want to use the existing bas
serializer_class = UserSerializer
queryset = User.objects.all()
There are two main advantages of using a `ViewSet` class over using a `View` class.
There are two main advantages of using a `ViewSet` class over using a `View`
class.
* Repeated logic can be combined into a single class. In the above example, we only need to specify the `queryset` once, and it'll be used across multiple views.
* By using routers, we no longer need to deal with wiring up the URL conf ourselves.
* Repeated logic can be combined into a single class. In the above example, we
only need to specify the `queryset` once, and it'll be used across multiple
views.
* By using routers, we no longer need to deal with wiring up the URL conf
ourselves.
Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.
Both of these come with a trade-off. Using regular views and URL confs is more
explicit and gives you more control. ViewSets are helpful if you want to get
up and running quickly, or when you have a large API and you want to enforce a
consistent URL configuration throughout.
## Marking extra actions for routing
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below:
The default routers included with REST framework will provide routes for a
standard set of create/retrieve/update/destroy style operations, as shown
below:
class UserViewSet(viewsets.ViewSet):
"""
@ -101,9 +122,12 @@ The default routers included with REST framework will provide routes for a stand
def destroy(self, request, pk=None):
pass
If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@detail_route` or `@list_route` decorators.
If you have ad-hoc methods that you need to be routed to, you can mark them as
requiring routing using the `@detail_route` or `@list_route` decorators.
The `@detail_route` decorator contains `pk` in its URL pattern and is intended for methods which require a single instance. The `@list_route` decorator is intended for methods which operate on a list of objects.
The `@detail_route` decorator contains `pk` in its URL pattern and is intended
for methods which require a single instance. The `@list_route` decorator is
intended for methods which operate on a list of objects.
For example:
@ -145,13 +169,15 @@ For example:
serializer = self.get_serializer(recent_users, many=True)
return Response(serializer.data)
The decorators can additionally take extra arguments that will be set for the routed view only. For example...
The decorators can additionally take extra arguments that will be set for the
routed view only. For example...
@detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf])
def set_password(self, request, pk=None):
...
These decorators will route `GET` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example:
These decorators will route `GET` requests by default, but may also accept
other HTTP methods, by using the `methods` argument. For example:
@detail_route(methods=['post', 'delete'])
def unset_password(self, request, pk=None):
@ -165,25 +191,38 @@ The two new actions will then be available at the urls `^users/{pk}/set_password
## ViewSet
The `ViewSet` class inherits from `APIView`. You can use any of the standard attributes such as `permission_classes`, `authentication_classes` in order to control the API policy on the viewset.
The `ViewSet` class inherits from `APIView`. You can use any of the standard
attributes such as `permission_classes`, `authentication_classes` in order to
control the API policy on the viewset.
The `ViewSet` class does not provide any implementations of actions. In order to use a `ViewSet` class you'll override the class and define the action implementations explicitly.
The `ViewSet` class does not provide any implementations of actions. In order
to use a `ViewSet` class you'll override the class and define the action
implementations explicitly.
## GenericViewSet
The `GenericViewSet` class inherits from `GenericAPIView`, and provides the default set of `get_object`, `get_queryset` methods and other generic view base behavior, but does not include any actions by default.
The `GenericViewSet` class inherits from `GenericAPIView`, and provides the
default set of `get_object`, `get_queryset` methods and other generic view base
behavior, but does not include any actions by default.
In order to use a `GenericViewSet` class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.
In order to use a `GenericViewSet` class you'll override the class and either
mixin the required mixin classes, or define the action implementations
explicitly.
## ModelViewSet
The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes.
The `ModelViewSet` class inherits from `GenericAPIView` and includes
implementations for various actions, by mixing in the behavior of the various
mixin classes.
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`,
`.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
#### Example
Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example:
Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to
provide at least the `queryset` and `serializer_class` attributes. For
example:
class AccountViewSet(viewsets.ModelViewSet):
"""
@ -193,7 +232,9 @@ Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide
serializer_class = AccountSerializer
permission_classes = [IsAccountAdminOrReadOnly]
Note that you can use any of the standard attributes or method overrides provided by `GenericAPIView`. For example, to use a `ViewSet` that dynamically determines the queryset it should operate on, you might do something like this:
Note that you can use any of the standard attributes or method overrides
provided by `GenericAPIView`. For example, to use a `ViewSet` that dynamically
determines the queryset it should operate on, you might do something like this:
class AccountViewSet(viewsets.ModelViewSet):
"""
@ -206,17 +247,26 @@ Note that you can use any of the standard attributes or method overrides provide
def get_queryset(self):
return self.request.user.accounts.all()
Note however that upon removal of the `queryset` property from your `ViewSet`, any associated [router][routers] will be unable to derive the base_name of your Model automatically, and so you will have to specify the `base_name` kwarg as part of your [router registration][routers].
Note however that upon removal of the `queryset` property from your `ViewSet`,
any associated [router][routers] will be unable to derive the base_name of your
Model automatically, and so you will have to specify the `base_name` kwarg as
part of your [router registration][routers].
Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.
Also note that although this class provides the complete set of
create/list/retrieve/update/destroy actions by default, you can restrict the
available operations by using the standard permission classes.
## ReadOnlyModelViewSet
The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with `ModelViewSet` it also includes implementations for various actions, but unlike `ModelViewSet` only provides the 'read-only' actions, `.list()` and `.retrieve()`.
The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with
`ModelViewSet` it also includes implementations for various actions, but unlike
`ModelViewSet` only provides the 'read-only' actions, `.list()` and
`.retrieve()`.
#### Example
As with `ModelViewSet`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example:
As with `ModelViewSet`, you'll normally need to provide at least the `queryset`
and `serializer_class` attributes. For example:
class AccountViewSet(viewsets.ReadOnlyModelViewSet):
"""
@ -225,15 +275,18 @@ As with `ModelViewSet`, you'll normally need to provide at least the `queryset`
queryset = Account.objects.all()
serializer_class = AccountSerializer
Again, as with `ModelViewSet`, you can use any of the standard attributes and method overrides available to `GenericAPIView`.
Again, as with `ModelViewSet`, you can use any of the standard attributes and
method overrides available to `GenericAPIView`.
# Custom ViewSet base classes
You may need to provide custom `ViewSet` classes that do not have the full set of `ModelViewSet` actions, or that customize the behavior in some other way.
You may need to provide custom `ViewSet` classes that do not have the full set
of `ModelViewSet` actions, or that customize the behavior in some other way.
## Example
To create a base viewset class that provides `create`, `list` and `retrieve` operations, inherit from `GenericViewSet`, and mixin the required actions:
To create a base viewset class that provides `create`, `list` and `retrieve`
operations, inherit from `GenericViewSet`, and mixin the required actions:
class CreateListRetrieveViewSet(mixins.CreateModelMixin,
mixins.ListModelMixin,
@ -247,7 +300,8 @@ To create a base viewset class that provides `create`, `list` and `retrieve` ope
"""
pass
By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple viewsets across your API.
By creating your own base `ViewSet` classes, you can provide common behavior
that can be reused in multiple viewsets across your API.
[cite]: http://guides.rubyonrails.org/routing.html
[routers]: routers.md

View File

@ -31,7 +31,8 @@
---
**Note**: This is the documentation for the **version 3** of REST framework. Documentation for [version 2](http://tomchristie.github.io/rest-framework-2-docs/) is also available.
**Note**: This is the documentation for the **version 3** of REST framework.
Documentation for [version 2](http://tomchristie.github.io/rest-framework-2-docs/) is also available.
---
@ -116,14 +117,18 @@ Add `'rest_framework'` to your `INSTALLED_APPS` setting.
'rest_framework',
)
If you're intending to use the browsable API you'll probably also 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 browsable API you'll probably also want to add
REST framework's login and logout views. Add the following to your root
`urls.py` file.
urlpatterns = [
...
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
Note that the URL path can be whatever you want, but you must include `'rest_framework.urls'` with the `'rest_framework'` namespace. You may leave out the namespace in Django 1.9+, and REST framework will set it for you.
Note that the URL path can be whatever you want, but you must include
`'rest_framework.urls'` with the `'rest_framework'` namespace. You may leave
out the namespace in Django 1.9+, and REST framework will set it for you.
## Example
@ -131,7 +136,9 @@ Let's take a look at a quick example of using REST framework to build a simple m
We'll create a read-write API for accessing information on the users of our project.
Any global settings for a REST framework API are kept in a single configuration dictionary named `REST_FRAMEWORK`. Start off by adding the following to your `settings.py` module:
Any global settings for a REST framework API are kept in a single configuration
dictionary named `REST_FRAMEWORK`. Start off by adding the following to your
`settings.py` module:
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
@ -172,15 +179,22 @@ Here's our project's root `urls.py` module:
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
You can now open the API in your browser at [http://127.0.0.1:8000/](http://127.0.0.1:8000/), and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.
You can now open the API in your browser at
[http://127.0.0.1:8000/](http://127.0.0.1:8000/), and view your new 'users'
API. If you use the login control in the top right corner you'll also be able
to add, create and delete users from the system.
## Quickstart
Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running, and building APIs with REST framework.
Can't wait to get started? The [quickstart guide][quickstart] is the fastest
way to get up and running, and building APIs with REST framework.
## Tutorial
The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.
The tutorial will walk you through the building blocks that make up REST
framework. It'll take a little while to get through, but it'll give you a
comprehensive understanding of how everything fits together, and is highly
recommended reading.
* [1 - Serialization][tut-1]
* [2 - Requests & Responses][tut-2]
@ -257,20 +271,32 @@ Framework.
## Support
For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.freenode.net`, search [the IRC archives][botbot], or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
For support please see the [REST framework discussion group][group], try the
`#restframework` channel on `irc.freenode.net`, search [the IRC
archives][botbot], or raise a question on [Stack Overflow][stack-overflow],
making sure to include the ['django-rest-framework'][django-rest-framework-tag]
tag.
[Paid support is available][paid-support] from [DabApps][dabapps], and can include work on REST framework core, or support with building your REST framework API. Please [contact DabApps][contact-dabapps] if you'd like to discuss commercial support options.
[Paid support is available][paid-support] from [DabApps][dabapps], and can
include work on REST framework core, or support with building your REST
framework API. Please [contact DabApps][contact-dabapps] if you'd like to
discuss commercial support options.
For updates on REST framework development, you may also want to follow [the author][twitter] on Twitter.
For updates on REST framework development, you may also want to follow [the
author][twitter] on Twitter.
<a style="padding-top: 10px" href="https://twitter.com/_tomchristie" class="twitter-follow-button" data-show-count="false">Follow @_tomchristie</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
## Security
If you believe youve found something in Django REST framework which has security implications, please **do not raise the issue in a public forum**.
If you believe youve found something in Django REST framework which has
security implications, please **do not raise the issue in a public forum**.
Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
Send a description of the issue via email to
[rest-framework-security@googlegroups.com][security-mail]. The project
maintainers will then work with you to resolve any issues where required, prior
to any public disclosure.
## License

View File

@ -1,48 +1,80 @@
# Django REST framework 2.2
The 2.2 release represents an important point for REST framework, with the addition of Python 3 support, and the introduction of an official deprecation policy.
The 2.2 release represents an important point for REST framework, with the
addition of Python 3 support, and the introduction of an official deprecation
policy.
## Python 3 support
Thanks to some fantastic work from [Xavier Ordoquy][xordoquy], Django REST framework 2.2 now supports Python 3. You'll need to be running Django 1.5, and it's worth keeping in mind that Django's Python 3 support is currently [considered experimental][django-python-3].
Thanks to some fantastic work from [Xavier Ordoquy][xordoquy], Django REST
framework 2.2 now supports Python 3. You'll need to be running Django 1.5, and
it's worth keeping in mind that Django's Python 3 support is currently
[considered experimental][django-python-3].
Django 1.6's Python 3 support is expected to be officially labeled as 'production-ready'.
Django 1.6's Python 3 support is expected to be officially labeled as
'production-ready'.
If you want to start ensuring that your own projects are Python 3 ready, we can highly recommend Django's [Porting to Python 3][porting-python-3] documentation.
If you want to start ensuring that your own projects are Python 3 ready, we can
highly recommend Django's [Porting to Python 3][porting-python-3]
documentation.
Django REST framework's Python 2.6 support now requires 2.6.5 or above, in line with [Django 1.5's Python compatibility][python-compat].
Django REST framework's Python 2.6 support now requires 2.6.5 or above, in line
with [Django 1.5's Python compatibility][python-compat].
## Deprecation policy
We've now introduced an official deprecation policy, which is in line with [Django's deprecation policy][django-deprecation-policy]. This policy will make it easy for you to continue to track the latest, greatest version of REST framework.
We've now introduced an official deprecation policy, which is in line with
[Django's deprecation policy][django-deprecation-policy]. This policy will
make it easy for you to continue to track the latest, greatest version of REST
framework.
The timeline for deprecation works as follows:
* Version 2.2 introduces some API changes as detailed in the release notes. It remains fully backwards compatible with 2.1, but will raise `PendingDeprecationWarning` warnings if you use bits of API that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using `python -Wd manage.py test`, you'll be warned of any API changes you need to make.
* Version 2.2 introduces some API changes as detailed in the release notes. It
remains fully backwards compatible with 2.1, but will raise
`PendingDeprecationWarning` warnings if you use bits of API that are due to
be deprecated. These warnings are silent by default, but can be explicitly
enabled when you're ready to start migrating any required changes. For
example if you start running your tests using `python -Wd manage.py test`,
you'll be warned of any API changes you need to make.
* Version 2.3 will escalate these warnings to `DeprecationWarning`, which is loud by default.
* Version 2.3 will escalate these warnings to `DeprecationWarning`, which is
loud by default.
* Version 2.4 will remove the deprecated bits of API entirely.
Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.
Note that in line with Django's policy, any parts of the framework not
mentioned in the documentation should generally be considered private API, and
may be subject to change.
## Community
As of the 2.2 merge, we've also hit an impressive milestone. The number of committers listed in [the credits][credits], is now at over **one hundred individuals**. Each name on that list represents at least one merged pull request, however large or small.
As of the 2.2 merge, we've also hit an impressive milestone. The number of
committers listed in [the credits][credits], is now at over **one hundred
individuals**. Each name on that list represents at least one merged pull
request, however large or small.
Our [mailing list][mailing-list] and #restframework IRC channel are also very active, and we've got a really impressive rate of development both on REST framework itself, and on third party packages such as the great [django-rest-framework-docs][django-rest-framework-docs] package from [Marc Gibbons][marcgibbons].
Our [mailing list][mailing-list] and #restframework IRC channel are also very
active, and we've got a really impressive rate of development both on REST
framework itself, and on third party packages such as the great
[django-rest-framework-docs][django-rest-framework-docs] package from [Marc
Gibbons][marcgibbons].
---
## API changes
The 2.2 release makes a few changes to the API, in order to make it more consistent, simple, and easier to use.
The 2.2 release makes a few changes to the API, in order to make it more
consistent, simple, and easier to use.
### Cleaner to-many related fields
The `ManyRelatedField()` style is being deprecated in favor of a new `RelatedField(many=True)` syntax.
The `ManyRelatedField()` style is being deprecated in favor of a new
`RelatedField(many=True)` syntax.
For example, if a user is associated with multiple questions, which we want to represent using a primary key relationship, we might use something like the following:
For example, if a user is associated with multiple questions, which we want to
represent using a primary key relationship, we might use something like the
following:
class UserSerializer(serializers.HyperlinkedModelSerializer):
questions = serializers.PrimaryKeyRelatedField(many=True)
@ -50,9 +82,14 @@ For example, if a user is associated with multiple questions, which we want to r
class Meta:
fields = ('username', 'questions')
The new syntax is cleaner and more obvious, and the change will also make the documentation cleaner, simplify the internal API, and make writing custom relational fields easier.
The new syntax is cleaner and more obvious, and the change will also make the
documentation cleaner, simplify the internal API, and make writing custom
relational fields easier.
The change also applies to serializers. If you have a nested serializer, you should start using `many=True` for to-many relationships. For example, a serializer representation of an Album that can contain many Tracks might look something like this:
The change also applies to serializers. If you have a nested serializer, you
should start using `many=True` for to-many relationships. For example, a
serializer representation of an Album that can contain many Tracks might look
something like this:
class TrackSerializer(serializer.ModelSerializer):
class Meta:
@ -66,49 +103,80 @@ The change also applies to serializers. If you have a nested serializer, you sh
model = Album
fields = ('album_name', 'artist', 'tracks')
Additionally, the change also applies when serializing or deserializing data. For example to serialize a queryset of models you should now use the `many=True` flag.
Additionally, the change also applies when serializing or deserializing data.
For example to serialize a queryset of models you should now use the
`many=True` flag.
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data
This more explicit behavior on serializing and deserializing data [makes integration with non-ORM backends such as MongoDB easier][564], as instances to be serialized can include the `__iter__` method, without incorrectly triggering list-based serialization, or requiring workarounds.
This more explicit behavior on serializing and deserializing data [makes
integration with non-ORM backends such as MongoDB easier][564], as instances to
be serialized can include the `__iter__` method, without incorrectly triggering
list-based serialization, or requiring workarounds.
The implicit to-many behavior on serializers, and the `ManyRelatedField` style classes will continue to function, but will raise a `PendingDeprecationWarning`, which can be made visible using the `-Wd` flag.
The implicit to-many behavior on serializers, and the `ManyRelatedField` style
classes will continue to function, but will raise a
`PendingDeprecationWarning`, which can be made visible using the `-Wd` flag.
**Note**: If you need to forcibly turn off the implicit "`many=True` for `__iter__` objects" behavior, you can now do so by specifying `many=False`. This will become the default (instead of the current default of `None`) once the deprecation of the implicit behavior is finalised in version 2.4.
**Note**: If you need to forcibly turn off the implicit "`many=True` for
`__iter__` objects" behavior, you can now do so by specifying `many=False`.
This will become the default (instead of the current default of `None`) once
the deprecation of the implicit behavior is finalised in version 2.4.
### Cleaner optional relationships
Serializer relationships for nullable Foreign Keys will change from using the current `null=True` flag, to instead using `required=False`.
Serializer relationships for nullable Foreign Keys will change from using the
current `null=True` flag, to instead using `required=False`.
For example, is a user account has an optional foreign key to a company, that you want to express using a hyperlink, you might use the following field in a `Serializer` class:
For example, is a user account has an optional foreign key to a company, that
you want to express using a hyperlink, you might use the following field in a
`Serializer` class:
current_company = serializers.HyperlinkedRelatedField(required=False)
This is in line both with the rest of the serializer fields API, and with Django's `Form` and `ModelForm` API.
This is in line both with the rest of the serializer fields API, and with
Django's `Form` and `ModelForm` API.
Using `required` throughout the serializers API means you won't need to consider if a particular field should take `blank` or `null` arguments instead of `required`, and also means there will be more consistent behavior for how fields are treated when they are not present in the incoming data.
Using `required` throughout the serializers API means you won't need to
consider if a particular field should take `blank` or `null` arguments instead
of `required`, and also means there will be more consistent behavior for how
fields are treated when they are not present in the incoming data.
The `null=True` argument will continue to function, and will imply `required=False`, but will raise a `PendingDeprecationWarning`.
The `null=True` argument will continue to function, and will imply
`required=False`, but will raise a `PendingDeprecationWarning`.
### Cleaner CharField syntax
The `CharField` API previously took an optional `blank=True` argument, which was intended to differentiate between null CharField input, and blank CharField input.
The `CharField` API previously took an optional `blank=True` argument, which
was intended to differentiate between null CharField input, and blank CharField
input.
In keeping with Django's CharField API, REST framework's `CharField` will only ever return the empty string, for missing or `None` inputs. The `blank` flag will no longer be in use, and you should instead just use the `required=<bool>` flag. For example:
In keeping with Django's CharField API, REST framework's `CharField` will only
ever return the empty string, for missing or `None` inputs. The `blank` flag
will no longer be in use, and you should instead just use the `required=<bool>`
flag. For example:
extra_details = CharField(required=False)
The `blank` keyword argument will continue to function, but will raise a `PendingDeprecationWarning`.
The `blank` keyword argument will continue to function, but will raise a
`PendingDeprecationWarning`.
### Simpler object-level permissions
Custom permissions classes previously used the signature `.has_permission(self, request, view, obj=None)`. This method would be called twice, firstly for the global permissions check, with the `obj` parameter set to `None`, and again for the object-level permissions check when appropriate, with the `obj` parameter set to the relevant model instance.
Custom permissions classes previously used the signature `.has_permission(self,
request, view, obj=None)`. This method would be called twice, firstly for the
global permissions check, with the `obj` parameter set to `None`, and again for
the object-level permissions check when appropriate, with the `obj` parameter
set to the relevant model instance.
The global permissions check and object-level permissions check are now separated into two separate methods, which gives a cleaner, more obvious API.
The global permissions check and object-level permissions check are now
separated into two separate methods, which gives a cleaner, more obvious API.
* Global permission checks now use the `.has_permission(self, request, view)` signature.
* Object-level permission checks use a new method `.has_object_permission(self, request, view, obj)`.
* Global permission checks now use the `.has_permission(self, request, view)`
signature.
* Object-level permission checks use a new method `.has_object_permission(self,
request, view, obj)`.
For example, the following custom permission class:
@ -136,15 +204,27 @@ Now becomes:
def has_object_permission(self, request, view, obj):
return obj.owner == request.user
If you're overriding the `BasePermission` class, the old-style signature will continue to function, and will correctly handle both global and object-level permissions checks, but its use will raise a `PendingDeprecationWarning`.
If you're overriding the `BasePermission` class, the old-style signature will
continue to function, and will correctly handle both global and object-level
permissions checks, but its use will raise a `PendingDeprecationWarning`.
Note also that the usage of the internal APIs for permission checking on the `View` class has been cleaned up slightly, and is now documented and subject to the deprecation policy in all future versions.
Note also that the usage of the internal APIs for permission checking on the
`View` class has been cleaned up slightly, and is now documented and subject to
the deprecation policy in all future versions.
### More explicit hyperlink relations behavior
When using a serializer with a `HyperlinkedRelatedField` or `HyperlinkedIdentityField`, the hyperlinks would previously use absolute URLs if the serializer context included a `'request'` key, and fall back to using relative URLs otherwise. This could lead to non-obvious behavior, as it might not be clear why some serializers generated absolute URLs, and others do not.
When using a serializer with a `HyperlinkedRelatedField` or
`HyperlinkedIdentityField`, the hyperlinks would previously use absolute URLs
if the serializer context included a `'request'` key, and fall back to using
relative URLs otherwise. This could lead to non-obvious behavior, as
it might not be clear why some serializers generated absolute URLs, and
others do not.
From version 2.2 onwards, serializers with hyperlinked relationships *always* require a `'request'` key to be supplied in the context dictionary. The implicit behavior will continue to function, but its use will raise a `PendingDeprecationWarning`.
From version 2.2 onwards, serializers with hyperlinked relationships *always*
require a `'request'` key to be supplied in the context dictionary. The
implicit behavior will continue to function, but its use will raise a
`PendingDeprecationWarning`.
[xordoquy]: https://github.com/xordoquy
[django-python-3]: https://docs.djangoproject.com/en/dev/faq/install/#can-i-use-django-with-python-3

View File

@ -6,11 +6,14 @@ REST framework 2.3 makes it even quicker and easier to build your Web APIs.
The 2.3 release introduces the [ViewSet][viewset] and [Router][router] classes.
A viewset is simply a type of class-based view that allows you to group multiple views into a single common class.
A viewset is simply a type of class-based view that allows you to group
multiple views into a single common class.
Routers allow you to automatically determine the URLconf for your viewset classes.
Routers allow you to automatically determine the URLconf for your viewset
classes.
As an example of just how simple REST framework APIs can now be, here's an API written in a single `urls.py` module:
As an example of just how simple REST framework APIs can now be, here's an API
written in a single `urls.py` module:
"""
A REST framework API for viewing and editing users and groups.
@ -41,21 +44,33 @@ As an example of just how simple REST framework APIs can now be, here's an API w
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
The best place to get started with ViewSets and Routers is to take a look at the [newest section in the tutorial][part-6], which demonstrates their usage.
The best place to get started with ViewSets and Routers is to take a look at
the [newest section in the tutorial][part-6], which demonstrates their usage.
## Simpler views
This release rationalises the API and implementation of the generic views, dropping the dependency on Django's `SingleObjectMixin` and `MultipleObjectMixin` classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with.
This release rationalises the API and implementation of the generic views,
dropping the dependency on Django's `SingleObjectMixin` and
`MultipleObjectMixin` classes, removing a number of unneeded attributes, and
generally making the implementation more obvious and easy to work with.
This improvement is reflected in improved documentation for the `GenericAPIView` base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses.
This improvement is reflected in improved documentation for the
`GenericAPIView` base class, and should make it easier to determine how to
override methods on the base class if you need to write customized subclasses.
## Easier Serializers
REST framework lets you be totally explicit regarding how you want to represent relationships, allowing you to choose between styles such as hyperlinking or primary key relationships.
REST framework lets you be totally explicit regarding how you want to represent
relationships, allowing you to choose between styles such as hyperlinking or
primary key relationships.
The ability to specify exactly how you want to represent relationships is powerful, but it also introduces complexity. In order to keep things more simple, REST framework now allows you to include reverse relationships simply by including the field name in the `fields` metadata of the serializer class.
The ability to specify exactly how you want to represent relationships is
powerful, but it also introduces complexity. In order to keep things more
simple, REST framework now allows you to include reverse relationships simply
by including the field name in the `fields` metadata of the serializer class.
For example, in REST framework 2.2, reverse relationships needed to be included explicitly on a serializer class.
For example, in REST framework 2.2, reverse relationships needed to be included
explicitly on a serializer class.
class BlogSerializer(serializers.ModelSerializer):
comments = serializers.PrimaryKeyRelatedField(many=True)
@ -64,7 +79,8 @@ For example, in REST framework 2.2, reverse relationships needed to be included
model = Blog
fields = ('id', 'title', 'created', 'comments')
As of 2.3, you can simply include the field name, and the appropriate serializer field will automatically be used for the relationship.
As of 2.3, you can simply include the field name, and the appropriate
serializer field will automatically be used for the relationship.
class BlogSerializer(serializers.ModelSerializer):
"""
@ -74,7 +90,8 @@ As of 2.3, you can simply include the field name, and the appropriate serializer
model = Blog
fields = ('id', 'title', 'created', 'comments')
Similarly, you can now easily include the primary key in hyperlinked relationships, simply by adding the field name to the metadata.
Similarly, you can now easily include the primary key in hyperlinked
relationships, simply by adding the field name to the metadata.
class BlogSerializer(serializers.HyperlinkedModelSerializer):
"""
@ -88,11 +105,16 @@ Similarly, you can now easily include the primary key in hyperlinked relationshi
## More flexible filtering
The `FILTER_BACKEND` setting has moved to pending deprecation, in favor of a `DEFAULT_FILTER_BACKENDS` setting that takes a *list* of filter backend classes, instead of a single filter backend class.
The `FILTER_BACKEND` setting has moved to pending deprecation, in favor of a
`DEFAULT_FILTER_BACKENDS` setting that takes a *list* of filter backend
classes, instead of a single filter backend class.
The generic view `filter_backend` attribute has also been moved to pending deprecation in favor of a `filter_backends` setting.
The generic view `filter_backend` attribute has also been moved to pending
deprecation in favor of a `filter_backends` setting.
Being able to specify multiple filters will allow for more flexible, powerful behavior. New filter classes to handle searching and ordering of results are planned to be released shortly.
Being able to specify multiple filters will allow for more flexible, powerful
behavior. New filter classes to handle searching and ordering of results are
planned to be released shortly.
---
@ -100,44 +122,69 @@ Being able to specify multiple filters will allow for more flexible, powerful be
## Simplified generic view classes
The functionality provided by `SingleObjectAPIView` and `MultipleObjectAPIView` base classes has now been moved into the base class `GenericAPIView`. The implementation of this base class is simple enough that providing subclasses for the base classes of detail and list views is somewhat unnecessary.
The functionality provided by `SingleObjectAPIView` and `MultipleObjectAPIView`
base classes has now been moved into the base class `GenericAPIView`. The
implementation of this base class is simple enough that providing subclasses
for the base classes of detail and list views is somewhat unnecessary.
Additionally the base generic view no longer inherits from Django's `SingleObjectMixin` or `MultipleObjectMixin` classes, simplifying the implementation, and meaning you don't need to cross-reference across to Django's codebase.
Additionally the base generic view no longer inherits from Django's
`SingleObjectMixin` or `MultipleObjectMixin` classes, simplifying the
implementation, and meaning you don't need to cross-reference across to
Django's codebase.
Using the `SingleObjectAPIView` and `MultipleObjectAPIView` base classes continues to be supported, but will raise a `PendingDeprecationWarning`. You should instead simply use `GenericAPIView` as the base for any generic view subclasses.
Using the `SingleObjectAPIView` and `MultipleObjectAPIView` base classes
continues to be supported, but will raise a `PendingDeprecationWarning`. You
should instead simply use `GenericAPIView` as the base for any generic view
subclasses.
### Removed attributes
The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unused and have now been entirely removed.
The following attributes and methods, were previously present as part of
Django's generic view implementations, but were unneeded and unused and have
now been entirely removed.
* context_object_name
* get_context_data()
* get_context_object_name()
The following attributes and methods, which were previously present as part of Django's generic view implementations have also been entirely removed.
The following attributes and methods, which were previously present as part of
Django's generic view implementations have also been entirely removed.
* paginator_class
* get_paginator()
* get_allow_empty()
* get_slug_field()
There may be cases when removing these bits of API might mean you need to write a little more code if your view has highly customized behavior, but generally we believe that providing a coarser-grained API will make the views easier to work with, and is the right trade-off to make for the vast majority of cases.
There may be cases when removing these bits of API might mean you need to write
a little more code if your view has highly customized behavior, but generally
we believe that providing a coarser-grained API will make the views easier to
work with, and is the right trade-off to make for the vast majority of cases.
Note that the listed attributes and methods have never been a documented part of the REST framework API, and as such are not covered by the deprecation policy.
Note that the listed attributes and methods have never been a documented part
of the REST framework API, and as such are not covered by the deprecation
policy.
### Simplified methods
The `get_object` and `get_paginate_by` methods no longer take an optional queryset argument. This makes overridden these methods more obvious, and a little more simple.
The `get_object` and `get_paginate_by` methods no longer take an optional
queryset argument. This makes overridden these methods more obvious, and a
little more simple.
Using an optional queryset with these methods continues to be supported, but will raise a `PendingDeprecationWarning`.
Using an optional queryset with these methods continues to be supported, but
will raise a `PendingDeprecationWarning`.
The `paginate_queryset` method no longer takes a `page_size` argument, or returns a four-tuple of pagination information. Instead it simply takes a queryset argument, and either returns a `page` object with an appropriate page size, or returns `None`, if pagination is not configured for the view.
The `paginate_queryset` method no longer takes a `page_size` argument, or
returns a four-tuple of pagination information. Instead it simply takes a
queryset argument, and either returns a `page` object with an appropriate page
size, or returns `None`, if pagination is not configured for the view.
Using the `page_size` argument is still supported and will trigger the old-style return type, but will raise a `PendingDeprecationWarning`.
Using the `page_size` argument is still supported and will trigger the
old-style return type, but will raise a `PendingDeprecationWarning`.
### Deprecated attributes
The following attributes are used to control queryset lookup, and have all been moved into a pending deprecation state.
The following attributes are used to control queryset lookup, and have all been
moved into a pending deprecation state.
* pk_url_kwarg = 'pk'
* slug_url_kwarg = 'slug'
@ -147,7 +194,11 @@ Their usage is replaced with a single attribute:
* lookup_field = 'pk'
This attribute is used both as the regex keyword argument in the URL conf, and as the model field to filter against when looking up a model instance. To use non-pk based lookup, simply set the `lookup_field` argument to an alternative field, and ensure that the keyword argument in the url conf matches the field name.
This attribute is used both as the regex keyword argument in the URL conf, and
as the model field to filter against when looking up a model instance. To use
non-pk based lookup, simply set the `lookup_field` argument to an alternative
field, and ensure that the keyword argument in the url conf matches the field
name.
For example, a view with 'username' based lookup might look like this:
@ -160,9 +211,12 @@ And would have the following entry in the urlconf:
url(r'^users/(?P<username>\w+)/$', UserDetail.as_view()),
Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`.
Usage of the old-style attributes continues to be supported, but will raise a
`PendingDeprecationWarning`.
The `allow_empty` attribute is also deprecated. To use `allow_empty=False` style behavior you should explicitly override `get_queryset` and raise an `Http404` on empty querysets.
The `allow_empty` attribute is also deprecated. To use `allow_empty=False`
style behavior you should explicitly override `get_queryset` and raise an
`Http404` on empty querysets.
For example:
@ -173,45 +227,68 @@ For example:
raise Http404
return queryset
In our opinion removing lesser-used attributes like `allow_empty` helps us move towards simpler generic view implementations, making them more obvious to use and override, and re-enforcing the preferred style of developers writing their own base classes and mixins for custom behavior rather than relying on the configurability of the generic views.
In our opinion removing lesser-used attributes like `allow_empty` helps us move
towards simpler generic view implementations, making them more obvious to use
and override, and re-enforcing the preferred style of developers writing their
own base classes and mixins for custom behavior rather than relying on the
configurability of the generic views.
## Simpler URL lookups
The `HyperlinkedRelatedField` class now takes a single optional `lookup_field` argument, that replaces the `pk_url_kwarg`, `slug_url_kwarg`, and `slug_field` arguments.
The `HyperlinkedRelatedField` class now takes a single optional `lookup_field`
argument, that replaces the `pk_url_kwarg`, `slug_url_kwarg`, and `slug_field`
arguments.
For example, you might have a field that references it's relationship by a hyperlink based on a slug field:
For example, you might have a field that references it's relationship by a
hyperlink based on a slug field:
account = HyperlinkedRelatedField(read_only=True,
lookup_field='slug',
view_name='account-detail')
Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`.
Usage of the old-style attributes continues to be supported, but will raise a
`PendingDeprecationWarning`.
## FileUploadParser
2.3 adds a `FileUploadParser` parser class, that supports raw file uploads, in addition to the existing multipart upload support.
2.3 adds a `FileUploadParser` parser class, that supports raw file uploads, in
addition to the existing multipart upload support.
## DecimalField
2.3 introduces a `DecimalField` serializer field, which returns `Decimal` instances.
2.3 introduces a `DecimalField` serializer field, which returns `Decimal`
instances.
For most cases APIs using model fields will behave as previously, however if you are using a custom renderer, not provided by REST framework, then you may now need to add support for rendering `Decimal` instances to your renderer implementation.
For most cases APIs using model fields will behave as previously, however if
you are using a custom renderer, not provided by REST framework, then you may
now need to add support for rendering `Decimal` instances to your renderer
implementation.
## ModelSerializers and reverse relationships
The support for adding reverse relationships to the `fields` option on a `ModelSerializer` class means that the `get_related_field` and `get_nested_field` method signatures have now changed.
The support for adding reverse relationships to the `fields` option on a
`ModelSerializer` class means that the `get_related_field` and
`get_nested_field` method signatures have now changed.
In the unlikely event that you're providing a custom serializer class, and implementing these methods you should note the new call signature for both methods is now `(self, model_field, related_model, to_many)`. For reverse relationships `model_field` will be `None`.
In the unlikely event that you're providing a custom serializer class, and
implementing these methods you should note the new call signature for both
methods is now `(self, model_field, related_model, to_many)`. For reverse
relationships `model_field` will be `None`.
The old-style signature will continue to function but will raise a `PendingDeprecationWarning`.
The old-style signature will continue to function but will raise a
`PendingDeprecationWarning`.
## View names and descriptions
The mechanics of how the names and descriptions used in the browsable API are generated has been modified and cleaned up somewhat.
The mechanics of how the names and descriptions used in the browsable API are
generated has been modified and cleaned up somewhat.
If you've been customizing this behavior, for example perhaps to use `rst` markup for the browsable API, then you'll need to take a look at the implementation to see what updates you need to make.
If you've been customizing this behavior, for example perhaps to use `rst`
markup for the browsable API, then you'll need to take a look at the
implementation to see what updates you need to make.
Note that the relevant methods have always been private APIs, and the docstrings called them out as intended to be deprecated.
Note that the relevant methods have always been private APIs, and the
docstrings called them out as intended to be deprecated.
---
@ -219,7 +296,9 @@ Note that the relevant methods have always been private APIs, and the docstrings
## More explicit style
The usage of `model` attribute in generic Views is still supported, but it's usage is generally being discouraged throughout the documentation, in favour of the setting the more explicit `queryset` and `serializer_class` attributes.
The usage of `model` attribute in generic Views is still supported, but it's
usage is generally being discouraged throughout the documentation, in favour of
the setting the more explicit `queryset` and `serializer_class` attributes.
For example, the following is now the recommended style for using generic views:
@ -227,9 +306,11 @@ For example, the following is now the recommended style for using generic views:
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
Using an explicit `queryset` and `serializer_class` attributes makes the functioning of the view more clear than using the shortcut `model` attribute.
Using an explicit `queryset` and `serializer_class` attributes makes the
functioning of the view more clear than using the shortcut `model` attribute.
It also makes the usage of the `get_queryset()` or `get_serializer_class()` methods more obvious.
It also makes the usage of the `get_queryset()` or `get_serializer_class()`
methods more obvious.
class AccountListView(generics.RetrieveAPIView):
serializer_class = MyModelSerializer
@ -246,18 +327,23 @@ It also makes the usage of the `get_queryset()` or `get_serializer_class()` meth
## Django 1.3 support
The 2.3.x release series will be the last series to provide compatibility with Django 1.3.
The 2.3.x release series will be the last series to provide compatibility with
Django 1.3.
## Version 2.2 API changes
All API changes in 2.2 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default.
All API changes in 2.2 that previously raised `PendingDeprecationWarning` will
now raise a `DeprecationWarning`, which is loud by default.
## What comes next?
* Support for read-write nested serializers is almost complete, and due to be released in the next few weeks.
* Extra filter backends for searching and ordering of results are planned to be added shortly.
* Support for read-write nested serializers is almost complete, and due to be
released in the next few weeks.
* Extra filter backends for searching and ordering of results are planned to be
added shortly.
The next few months should see a renewed focus on addressing outstanding tickets. The 2.4 release is currently planned for around August-September.
The next few months should see a renewed focus on addressing outstanding
tickets. The 2.4 release is currently planned for around August-September.
[viewset]: ../api-guide/viewsets.md
[router]: ../api-guide/routers.md

View File

@ -1,35 +1,49 @@
# Django REST framework 2.4
The 2.4 release is largely an intermediate step, tying up some outstanding issues prior to the 3.x series.
The 2.4 release is largely an intermediate step, tying up some outstanding
issues prior to the 3.x series.
## Version requirements
Support for Django 1.3 has been dropped.
The lowest supported version of Django is now 1.4.2.
Support for Django 1.3 has been dropped. The lowest supported version of
Django is now 1.4.2.
The current plan is for REST framework to remain in lockstep with [Django's long-term support policy][lts-releases].
The current plan is for REST framework to remain in lockstep with [Django's
long-term support policy][lts-releases].
## Django 1.7 support
The optional authtoken application now includes support for *both* Django 1.7 schema migrations, *and* for old-style `south` migrations.
The optional authtoken application now includes support for *both* Django 1.7
schema migrations, *and* for old-style `south` migrations.
**If you are using authtoken, and you want to continue using `south`, you must upgrade your `south` package to version 1.0.**
**If you are using authtoken, and you want to continue using `south`, you must
upgrade your `south` package to version 1.0.**
## Deprecation of `.model` view attribute
The `.model` attribute on view classes is an optional shortcut for either or both of `.serializer_class` and `.queryset`. Its usage results in more implicit, less obvious behavior.
The `.model` attribute on view classes is an optional shortcut for either or
both of `.serializer_class` and `.queryset`. Its usage results in more
implicit, less obvious behavior.
The documentation has previously stated that usage of the more explicit style is prefered, and we're now taking that one step further and deprecating the usage of the `.model` shortcut.
The documentation has previously stated that usage of the more explicit style
is prefered, and we're now taking that one step further and deprecating the
usage of the `.model` shortcut.
Doing so will mean that there are cases of API code where you'll now need to include a serializer class where you previously were just using the `.model` shortcut. However we firmly believe that it is the right trade-off to make.
Doing so will mean that there are cases of API code where you'll now need to
include a serializer class where you previously were just using the `.model`
shortcut. However we firmly believe that it is the right trade-off to make.
Removing the shortcut takes away an unnecessary layer of abstraction, and makes your codebase more explicit without any significant extra complexity. It also results in better consistency, as there's now only one way to set the serializer class and queryset attributes for the view, instead of two.
Removing the shortcut takes away an unnecessary layer of abstraction, and makes
your codebase more explicit without any significant extra complexity. It also
results in better consistency, as there's now only one way to set the
serializer class and queryset attributes for the view, instead of two.
The `DEFAULT_MODEL_SERIALIZER_CLASS` API setting is now also deprecated.
## Updated test runner
We now have a new test runner for developing against the project,, that uses the excellent [py.test](http://pytest.org) library.
We now have a new test runner for developing against the project,, that uses
the excellent [py.test](http://pytest.org) library.
To use it make sure you have first installed the test requirements.
@ -39,7 +53,8 @@ Then run the `runtests.py` script.
./runtests.py
The new test runner also includes [flake8](https://flake8.readthedocs.io) code linting, which should help keep our coding style consistent.
The new test runner also includes [flake8](https://flake8.readthedocs.io) code
linting, which should help keep our coding style consistent.
#### Test runner flags
@ -71,15 +86,24 @@ Shorter form to run the tests for a given test method.
./runtests test_this_method
Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.
Note: The test case and test method matching is fuzzy and will sometimes run
other tests that contain a partial string match to the given command line
input.
## Improved viewset routing
The `@action` and `@link` decorators were inflexible in that they only allowed additional routes to be added against instance style URLs, not against list style URLs.
The `@action` and `@link` decorators were inflexible in that they only allowed
additional routes to be added against instance style URLs, not against list
style URLs.
The `@action` and `@link` decorators have now been moved to pending deprecation, and the `@list_route` and `@detail_route` decorators have been introduced.
The `@action` and `@link` decorators have now been moved to pending
deprecation, and the `@list_route` and `@detail_route` decorators have been
introduced.
Here's an example of using the new decorators. Firstly we have a detail-type route named "set_password" that acts on a single instance, and takes a `pk` argument in the URL. Secondly we have a list-type route named "recent_users" that acts on a queryset, and does not take any arguments in the URL.
Here's an example of using the new decorators. Firstly we have a detail-type
route named "set_password" that acts on a single instance, and takes a `pk`
argument in the URL. Secondly we have a list-type route named "recent_users"
that acts on a queryset, and does not take any arguments in the URL.
class UserViewSet(viewsets.ModelViewSet):
"""
@ -111,40 +135,58 @@ For more details, see the [viewsets documentation](../api-guide/viewsets.md).
## Throttle behavior
There's one bugfix in 2.4 that's worth calling out, as it will *invalidate existing throttle caches* when you upgrade.
There's one bugfix in 2.4 that's worth calling out, as it will *invalidate
existing throttle caches* when you upgrade.
We've now fixed a typo on the `cache_format` attribute. Previously this was named `"throtte_%(scope)s_%(ident)s"`, it is now `"throttle_%(scope)s_%(ident)s"`.
We've now fixed a typo on the `cache_format` attribute. Previously this was
named `"throtte_%(scope)s_%(ident)s"`, it is now
`"throttle_%(scope)s_%(ident)s"`.
If you're concerned about the invalidation you have two options.
* Manually pre-populate your cache with the fixed version.
* Set the `cache_format` attribute on your throttle class in order to retain the previous incorrect spelling.
* Set the `cache_format` attribute on your throttle class in order to retain
the previous incorrect spelling.
## Other features
There are also a number of other features and bugfixes as [listed in the release notes][2-4-release-notes]. In particular these include:
There are also a number of other features and bugfixes as [listed in the
release notes][2-4-release-notes]. In particular these include:
[Customizable view name and description functions][view-name-and-description-settings] for use with the browsable API, by using the `VIEW_NAME_FUNCTION` and `VIEW_DESCRIPTION_FUNCTION` settings.
[Customizable view name and description
functions][view-name-and-description-settings] for use with the browsable API,
by using the `VIEW_NAME_FUNCTION` and `VIEW_DESCRIPTION_FUNCTION` settings.
Smarter [client IP identification for throttling][client-ip-identification], with the addition of the `NUM_PROXIES` setting.
Smarter [client IP identification for throttling][client-ip-identification],
with the addition of the `NUM_PROXIES` setting.
Added the standardized `Retry-After` header to throttled responses, as per [RFC 6585](http://tools.ietf.org/html/rfc6585). This should now be used in preference to the custom `X-Throttle-Wait-Seconds` header which will be fully deprecated in 3.0.
Added the standardized `Retry-After` header to throttled responses, as per [RFC
6585](http://tools.ietf.org/html/rfc6585). This should now be used in
preference to the custom `X-Throttle-Wait-Seconds` header which will be fully
deprecated in 3.0.
## Deprecations
All API changes in 2.3 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default.
All API changes in 2.3 that previously raised `PendingDeprecationWarning` will
now raise a `DeprecationWarning`, which is loud by default.
All API changes in 2.3 that previously raised `DeprecationWarning` have now been removed entirely.
All API changes in 2.3 that previously raised `DeprecationWarning` have now
been removed entirely.
Furter details on these deprecations is available in the [2.3 announcement][2-3-announcement].
Furter details on these deprecations is available in the [2.3
announcement][2-3-announcement].
## Labels and milestones
Although not strictly part of the 2.4 release it's also worth noting here that we've been working hard towards improving our triage process.
Although not strictly part of the 2.4 release it's also worth noting here that
we've been working hard towards improving our triage process.
The [labels that we use in GitHub][github-labels] have been cleaned up, and all existing tickets triaged. Any given ticket should have one and only one label, indicating its current state.
The [labels that we use in GitHub][github-labels] have been cleaned up, and all
existing tickets triaged. Any given ticket should have one and only one label,
indicating its current state.
We've also [started using milestones][github-milestones] in order to track tickets against particular releases.
We've also [started using milestones][github-milestones] in order to track
tickets against particular releases.
---
@ -154,13 +196,16 @@ We've also [started using milestones][github-milestones] in order to track ticke
---
We hope both of these changes will help make the management process more clear and obvious and help keep tickets well-organised and relevant.
We hope both of these changes will help make the management process more clear
and obvious and help keep tickets well-organised and relevant.
## Next steps
The next planned release will be 3.0, featuring an improved and simplified serializer implementation.
The next planned release will be 3.0, featuring an improved and simplified
serializer implementation.
Once again, many thanks to all the generous [backers and sponsors][kickstarter-sponsors] who've helped make this possible!
Once again, many thanks to all the generous [backers and
sponsors][kickstarter-sponsors] who've helped make this possible!
[lts-releases]: https://docs.djangoproject.com/en/dev/internals/release-process/#long-term-support-lts-releases
[2-4-release-notes]: release-notes#240

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,7 @@
# Django REST framework 3.1
The 3.1 release is an intermediate step in the Kickstarter project releases, and includes a range of new functionality.
The 3.1 release is an intermediate step in the Kickstarter project releases,
and includes a range of new functionality.
Some highlights include:
@ -15,26 +16,52 @@ Some highlights include:
## Pagination
The pagination API has been improved, making it both easier to use, and more powerful.
The pagination API has been improved, making it both easier to use, and more
powerful.
A guide to the headline features follows. For full details, see [the pagination documentation][pagination].
A guide to the headline features follows. For full details, see [the pagination
documentation][pagination].
Note that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes.
Note that as a result of this work a number of settings keys and generic view
attributes are now moved to pending deprecation. Controlling pagination styles
is now largely handled by overriding a pagination class and modifying its
configuration attributes.
* The `PAGINATE_BY` settings key will continue to work but is now pending deprecation. The more obviously named `PAGE_SIZE` settings key should now be used instead.
* The `PAGINATE_BY_PARAM`, `MAX_PAGINATE_BY` settings keys will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.
* The `paginate_by`, `page_query_param`, `paginate_by_param` and `max_paginate_by` generic view attributes will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class.
* The `pagination_serializer_class` view attribute and `DEFAULT_PAGINATION_SERIALIZER_CLASS` settings key **are no longer valid**. The pagination API does not use serializers to determine the output format, and you'll need to instead override the `get_paginated_response` method on a pagination class in order to specify how the output format is controlled.
* The `PAGINATE_BY` settings key will continue to work but is now pending
deprecation. The more obviously named `PAGE_SIZE` settings key should now be
used instead.
* The `PAGINATE_BY_PARAM`, `MAX_PAGINATE_BY` settings keys will continue to
work but are now pending deprecation, in favor of setting configuration
attributes on the configured pagination class.
* The `paginate_by`, `page_query_param`, `paginate_by_param` and
`max_paginate_by` generic view attributes will continue to work but are now
pending deprecation, in favor of setting configuration attributes on the
configured pagination class.
* The `pagination_serializer_class` view attribute and
`DEFAULT_PAGINATION_SERIALIZER_CLASS` settings key **are no longer valid**.
The pagination API does not use serializers to determine the output format,
and you'll need to instead override the `get_paginated_response` method on a
pagination class in order to specify how the output format is controlled.
#### New pagination schemes.
Until now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default.
Until now, there has only been a single built-in pagination style in REST
framework. We now have page, limit/offset and cursor based schemes included by
default.
The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for [this blog post](http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api) on the subject.
The cursor based pagination scheme is particularly smart, and is a better
approach for clients iterating through large or frequently changing result
sets. The scheme supports paging against non-unique indexes, by using both
cursor and limit/offset information. It also allows for both forward and
reverse cursor pagination. Much credit goes to David Cramer for [this blog
post](http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api) on the
subject.
#### Pagination controls in the browsable API.
Paginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API:
Paginated results now include controls that render directly in the browsable
API. If you're using the page or limit/offset style, then you'll see a page
based control displayed in the browsable API:
![page number based pagination](../img/pages-pagination.png )
@ -44,19 +71,26 @@ The cursor based pagination renders a more simple style of control:
#### Support for header-based pagination.
The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the `Link` or `Content-Range` headers.
The pagination API was previously only able to alter the pagination style in
the body of the response. The API now supports being able to write pagination
information in response headers, making it possible to use pagination schemes
that use the `Link` or `Content-Range` headers.
For more information, see the [custom pagination styles](../api-guide/pagination/#custom-pagination-styles) documentation.
For more information, see the [custom pagination
styles](../api-guide/pagination/#custom-pagination-styles) documentation.
---
## Versioning
We've made it [easier to build versioned APIs][versioning]. Built-in schemes for versioning include both URL based and Accept header based variations.
We've made it [easier to build versioned APIs][versioning]. Built-in schemes
for versioning include both URL based and Accept header based variations.
When using a URL based scheme, hyperlinked serializers will resolve relationships to the same API version as used on the incoming request.
When using a URL based scheme, hyperlinked serializers will resolve
relationships to the same API version as used on the incoming request.
For example, when using `NamespaceVersioning`, and the following hyperlinked serializer:
For example, when using `NamespaceVersioning`, and the following hyperlinked
serializer:
class AccountsSerializer(serializer.HyperlinkedModelSerializer):
class Meta:
@ -80,20 +114,27 @@ The output representation would match the version used on the incoming request.
## Internationalization
REST framework now includes a built-in set of translations, and [supports internationalized error responses][internationalization]. This allows you to either change the default language, or to allow clients to specify the language via the `Accept-Language` header.
REST framework now includes a built-in set of translations, and [supports
internationalized error responses][internationalization]. This allows you to
either change the default language, or to allow clients to specify the language
via the `Accept-Language` header.
You can change the default language by using the standard Django `LANGUAGE_CODE` setting:
You can change the default language by using the standard Django
`LANGUAGE_CODE` setting:
LANGUAGE_CODE = "es-es"
You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE_CLASSES` setting:
You can turn on per-request language requests by adding `LocalMiddleware` to
your `MIDDLEWARE_CLASSES` setting:
MIDDLEWARE_CLASSES = [
...
'django.middleware.locale.LocaleMiddleware'
]
When per-request internationalization is enabled, client requests will respect the `Accept-Language` header where possible. For example, let's make a request for an unsupported media type:
When per-request internationalization is enabled, client requests will respect
the `Accept-Language` header where possible. For example, let's make a request
for an unsupported media type:
**Request**
@ -110,13 +151,18 @@ When per-request internationalization is enabled, client requests will respect t
"detail": "No se ha podido satisfacer la solicitud de cabecera de Accept."
}
Note that the structure of the error responses is still the same. We still have a `detail` key in the response. If needed you can modify this behavior too, by using a [custom exception handler][custom-exception-handler].
Note that the structure of the error responses is still the same. We still have
a `detail` key in the response. If needed you can modify this behavior too, by
using a [custom exception handler][custom-exception-handler].
We include built-in translations both for standard exception cases, and for serializer validation errors.
We include built-in translations both for standard exception cases, and for
serializer validation errors.
The full list of supported languages can be found on our [Transifex project page](https://www.transifex.com/projects/p/django-rest-framework/).
The full list of supported languages can be found on our [Transifex project
page](https://www.transifex.com/projects/p/django-rest-framework/).
If you only wish to support a subset of the supported languages, use Django's standard `LANGUAGES` setting:
If you only wish to support a subset of the supported languages, use Django's
standard `LANGUAGES` setting:
LANGUAGES = [
('de', _('German')),
@ -131,11 +177,17 @@ Many thanks to [Craig Blaszczyk](https://github.com/jakul) for helping push this
## New field types
Django 1.8's new `ArrayField`, `HStoreField` and `UUIDField` are now all fully supported.
Django 1.8's new `ArrayField`, `HStoreField` and `UUIDField` are now all fully
supported.
This work also means that we now have both `serializers.DictField()`, and `serializers.ListField()` types, allowing you to express and validate a wider set of representations.
This work also means that we now have both `serializers.DictField()`, and
`serializers.ListField()` types, allowing you to express and validate a wider
set of representations.
If you're building a new 1.8 project, then you should probably consider using `UUIDField` as the primary keys for all your models. This style will work automatically with hyperlinked serializers, returning URLs in the following style:
If you're building a new 1.8 project, then you should probably consider using
`UUIDField` as the primary keys for all your models. This style will work
automatically with hyperlinked serializers, returning URLs in the following
style:
http://example.org/api/purchases/9b1a433f-e90d-4948-848b-300fdc26365d
@ -143,28 +195,43 @@ If you're building a new 1.8 project, then you should probably consider using `U
## ModelSerializer API
The serializer redesign in 3.0 did not include any public API for modifying how ModelSerializer classes automatically generate a set of fields from a given mode class. We've now re-introduced an API for this, allowing you to create new ModelSerializer base classes that behave differently, such as using a different default style for relationships.
The serializer redesign in 3.0 did not include any public API for modifying how
ModelSerializer classes automatically generate a set of fields from a given
mode class. We've now re-introduced an API for this, allowing you to create new
ModelSerializer base classes that behave differently, such as using a different
default style for relationships.
For more information, see the documentation on [customizing field mappings][customizing-field-mappings] for ModelSerializer classes.
For more information, see the documentation on [customizing field
mappings][customizing-field-mappings] for ModelSerializer classes.
---
## Moving packages out of core
We've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to `pip install` the new packages, and change any import paths.
We've now moved a number of packages out of the core of REST framework, and
into separately installable packages. If you're currently using these you don't
need to worry, you simply need to `pip install` the new packages, and change
any import paths.
We're making this change in order to help distribute the maintainance workload, and keep better focus of the core essentials of the framework.
We're making this change in order to help distribute the maintainance workload,
and keep better focus of the core essentials of the framework.
The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained [Django OAuth toolkit](https://github.com/evonove/django-oauth-toolkit) has now been promoted as our recommended option for integrating OAuth support.
The change also means we can be more flexible with which external packages we
recommend. For example, the excellently maintained [Django OAuth
toolkit](https://github.com/evonove/django-oauth-toolkit) has now been promoted
as our recommended option for integrating OAuth support.
The following packages are now moved out of core and should be separately installed:
The following packages are now moved out of core and should be separately
installed:
* OAuth - [djangorestframework-oauth](http://jpadilla.github.io/django-rest-framework-oauth/)
* XML - [djangorestframework-xml](http://jpadilla.github.io/django-rest-framework-xml)
* YAML - [djangorestframework-yaml](http://jpadilla.github.io/django-rest-framework-yaml)
* JSONP - [djangorestframework-jsonp](http://jpadilla.github.io/django-rest-framework-jsonp)
It's worth reiterating that this change in policy shouldn't mean any work in your codebase other than adding a new requirement and modifying some import paths. For example to install XML rendering, you would now do:
It's worth reiterating that this change in policy shouldn't mean any work in
your codebase other than adding a new requirement and modifying some import
paths. For example to install XML rendering, you would now do:
pip install djangorestframework-xml
@ -178,17 +245,24 @@ And modify your settings, like so:
]
}
Thanks go to the latest member of our maintenance team, [José Padilla](https://github.com/jpadilla/), for handling this work and taking on ownership of these packages.
Thanks go to the latest member of our maintenance team, [José
Padilla](https://github.com/jpadilla/), for handling this work and taking on
ownership of these packages.
---
## Deprecations
The `request.DATA`, `request.FILES` and `request.QUERY_PARAMS` attributes move from pending deprecation, to deprecated. Use `request.data` and `request.query_params` instead, as discussed in the 3.0 release notes.
The `request.DATA`, `request.FILES` and `request.QUERY_PARAMS` attributes move
from pending deprecation, to deprecated. Use `request.data` and
`request.query_params` instead, as discussed in the 3.0 release notes.
The ModelSerializer Meta options for `write_only_fields`, `view_name` and `lookup_field` are also moved from pending deprecation, to deprecated. Use `extra_kwargs` instead, as discussed in the 3.0 release notes.
The ModelSerializer Meta options for `write_only_fields`, `view_name` and
`lookup_field` are also moved from pending deprecation, to deprecated. Use
`extra_kwargs` instead, as discussed in the 3.0 release notes.
All these attributes and options will still work in 3.1, but their usage will raise a warning. They will be fully removed in 3.2.
All these attributes and options will still work in 3.1, but their usage will
raise a warning. They will be fully removed in 3.2.
---
@ -200,7 +274,9 @@ The next focus will be on HTML renderings of API output and will include:
* Filtering controls built-in to the browsable API.
* An alternative admin-style interface.
This will either be made as a single 3.2 release, or split across two separate releases, with the HTML forms and filter controls coming in 3.2, and the admin-style interface coming in a 3.3 release.
This will either be made as a single 3.2 release, or split across two separate
releases, with the HTML forms and filter controls coming in 3.2, and the
admin-style interface coming in a 3.3 release.
[custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling
[pagination]: ../api-guide/pagination.md

View File

@ -1,16 +1,28 @@
# Django REST framework 3.2
The 3.2 release is the first version to include an admin interface for the browsable API.
The 3.2 release is the first version to include an admin interface for the
browsable API.
![The AdminRenderer](../img/admin.png)
This interface is intended to act as a more user-friendly interface to the API. It can be used either as a replacement to the existing `BrowsableAPIRenderer`, or used together with it, allowing you to switch between the two styles as required.
This interface is intended to act as a more user-friendly interface to the API.
It can be used either as a replacement to the existing `BrowsableAPIRenderer`,
or used together with it, allowing you to switch between the two styles as
required.
We've also fixed a huge number of issues, and made numerous cleanups and improvements.
We've also fixed a huge number of issues, and made numerous cleanups and
improvements.
Over the course of the 3.1.x series we've [resolved nearly 600 tickets](https://github.com/tomchristie/django-rest-framework/issues?utf8=%E2%9C%93&q=closed%3A%3E2015-03-05) on our GitHub issue tracker. This means we're currently running at a rate of **closing around 100 issues or pull requests per month**.
Over the course of the 3.1.x series we've [resolved nearly 600
tickets](https://github.com/tomchristie/django-rest-framework/issues?utf8=%E2%9C%93&q=closed%3A%3E2015-03-05)
on our GitHub issue tracker. This means we're currently running at a rate of
**closing around 100 issues or pull requests per month**.
None of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking [a look through our sponsors](http://www.django-rest-framework.org/topics/kickstarter-announcement/#sponsors) and finding out who's hiring.
None of this would have been possible without the support of our wonderful
Kickstarter backers. If you're looking for a job in Django development we'd
strongly recommend taking [a look through our
sponsors](http://www.django-rest-framework.org/topics/kickstarter-announcement/#sponsors)
and finding out who's hiring.
## AdminRenderer
@ -26,11 +38,15 @@ To include `AdminRenderer` simply add it to your settings:
'PAGE_SIZE': 100
}
There are some limitations to the `AdminRenderer`, in particular it is not yet able to handle list or dictionary inputs, as we do not have any HTML form fields that support those.
There are some limitations to the `AdminRenderer`, in particular it is not yet
able to handle list or dictionary inputs, as we do not have any HTML form
fields that support those.
Also note that this is an initial release and we do not yet have a public API for modifying the behavior or documentation on overriding the templates.
Also note that this is an initial release and we do not yet have a public API
for modifying the behavior or documentation on overriding the templates.
The idea is to get this released to users early, so we can start getting feedback and release a more fully featured version in 3.3.
The idea is to get this released to users early, so we can start getting
feedback and release a more fully featured version in 3.3.
## Supported versions
@ -40,13 +56,23 @@ Our supported Django versions are now 1.5.6+, 1.6.3+, 1.7 and 1.8.
## Deprecations
There are no new deprecations in 3.2, although a number of existing deprecations have now escalated in line with our deprecation policy.
There are no new deprecations in 3.2, although a number of existing
deprecations have now escalated in line with our deprecation policy.
* `request.DATA` was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of `request.data` instead.
* `request.QUERY_PARAMS` was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of `request.query_params` instead.
* The following `ModelSerializer.Meta` options have now been removed: `write_only_fields`, `view_name`, `lookup_field`. Use the more general `extra_kwargs` option instead.
* `request.DATA` was put on the deprecation path in 3.0. It has now been
removed and its usage will result in an error. Use the more pythonic style of
`request.data` instead.
* `request.QUERY_PARAMS` was put on the deprecation path in 3.0. It has now
been removed and its usage will result in an error. Use the more pythonic
style of `request.query_params` instead.
* The following `ModelSerializer.Meta` options have now been removed:
`write_only_fields`, `view_name`, `lookup_field`. Use the more general
`extra_kwargs` option instead.
The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly in 'pending deprecation', and has now escalated to 'deprecated'. They will continue to function but will raise errors.
The following pagination view attributes and settings have been moved into
attributes on the pagination class since 3.1. Their usage was formerly in
'pending deprecation', and has now escalated to 'deprecated'. They will
continue to function but will raise errors.
* `view.paginate_by` - Use `paginator.page_size` instead.
* `view.page_query_param` - Use `paginator.page_query_param` instead.
@ -58,17 +84,26 @@ The following pagination view attributes and settings have been moved into attri
## Modifications to list behaviors
There are a couple of bug fixes that are worth calling out as they introduce differing behavior.
There are a couple of bug fixes that are worth calling out as they introduce
differing behavior.
These are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project.
These are a little subtle and probably won't affect most users, but are worth
understanding before upgrading your project.
### ManyToMany fields and blank=True
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
We've now added an `allow_empty` argument, which can be used with
`ListSerializer`, or with `many=True` relationships. This is `True` by
default, but can be set to `False` if you want to disallow empty lists as valid
input.
As a follow-up to this we are now able to properly mirror the behavior of Django's `ModelForm` with respect to how many-to-many fields are validated.
As a follow-up to this we are now able to properly mirror the behavior of
Django's `ModelForm` with respect to how many-to-many fields are validated.
Previously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has `blank=True` set.
Previously a many-to-many field on a model would map to a serializer field that
would allow either empty or non-empty list inputs. Now, a many-to-many field
will map to a serializer field that requires at least one input, unless the
model field has `blank=True` set.
Here's what the mapping looks like in practice:
@ -79,7 +114,9 @@ The upshot is this: If you have many to many fields in your models, then make su
### List fields and allow_null
When using `allow_null` with `ListField` or a nested `many=True` serializer the previous behavior was to allow `null` values as items in the list. The behavior is now to allow `null` values instead of the list.
When using `allow_null` with `ListField` or a nested `many=True` serializer the
previous behavior was to allow `null` values as items in the list. The behavior
is now to allow `null` values instead of the list.
For example, take the following field:
@ -95,7 +132,9 @@ Our validation behavior as of 3.2.0 is now:
* `[{…}, null, {…}]` is **invalid**.
* `null` is **valid**.
If you want to allow `null` child items, you'll need to instead specify `allow_null` on the child class, using an explicit `ListField` instead of `many=True`. For example:
If you want to allow `null` child items, you'll need to instead specify
`allow_null` on the child class, using an explicit `ListField` instead of
`many=True`. For example:
ListField(child=NestedSerializer(allow_null=True))
@ -110,4 +149,4 @@ This release is planned to include:
* Improvements and public API for our templated HTML forms and fields.
* Nested object and list support in HTML forms.
Thanks once again to all our sponsors and supporters.
Thanks once again to all our sponsors and supporters.

View File

@ -1,12 +1,23 @@
# Django REST framework 3.3
The 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding **thank you** to all our wonderful sponsors and supporters.
The 3.3 release marks the final work in the Kickstarter funded series. We'd
like to offer a final resounding **thank you** to all our wonderful sponsors
and supporters.
The amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned & refined large parts of the project.
The amount of work that has been achieved as a direct result of the funding is
immense. We've added a huge amounts of new functionality, resolved nearly 2,000
tickets, and redesigned & refined large parts of the project.
In order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow [@_tomchristie](https://twitter.com/_tomchristie) to keep up to date with these announcements, and be among the first set of sign ups.
In order to continue driving REST framework forward, we'll shortly be
announcing a new set of funding plans. Follow
[@_tomchristie](https://twitter.com/_tomchristie) to keep up to date with these
announcements, and be among the first set of sign ups.
We strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished & professional product.
We strongly believe that collaboratively funded software development yields
outstanding results for a relatively low investment-per-head. If you or your
company use REST framework commercially, then we would strongly urge you to
participate in this latest funding drive, and help us continue to build an
increasingly polished & professional product.
---
@ -34,13 +45,27 @@ This brings our supported versions into line with Django's [currently supported
## Deprecations
The AJAX based support for the browsable API means that there are a number of internal cleanups in the `request` class. For the vast majority of developers this should largely remain transparent:
The AJAX based support for the browsable API means that there are a number of
internal cleanups in the `request` class. For the vast majority of developers
this should largely remain transparent:
* To support form based `PUT` and `DELETE`, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-form] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.
* The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class](browser-enhancements.md#url-based-accept-headers).
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware](browser-enhancements.md#http-header-based-method-overriding).
* To support form based `PUT` and `DELETE`, or to support form content types
such as JSON, you should now use the [AJAX forms][ajax-form] javascript
library. This replaces the previous 'method and content type overloading'
that required significant internal complexity to the request class.
The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.
* The `accept` query parameter is no longer supported by the default content
negotiation class. If you require it then you'll need to [use a custom
content negotiation class](browser-enhancements.md#url-based-accept-headers).
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by
default. If you require it then you'll need to [use custom
middleware](browser-enhancements.md#http-header-based-method-overriding).
The following pagination view attributes and settings have been moved into
attributes on the pagination class since 3.1. Their usage was formerly
deprecated, and has now been removed entirely, in line with the deprecation
policy.
* `view.paginate_by` - Use `paginator.page_size` instead.
* `view.page_query_param` - Use `paginator.page_query_param` instead.
@ -50,9 +75,14 @@ The following pagination view attributes and settings have been moved into attri
* `settings.PAGINATE_BY_PARAM` - Use `paginator.page_size_query_param` instead.
* `settings.MAX_PAGINATE_BY` - Use `paginator.max_page_size` instead.
The `ModelSerializer` and `HyperlinkedModelSerializer` classes should now include either a `fields` or `exclude` option, although the `fields = '__all__'` shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings `ModelSerializer` more closely in line with Django's `ModelForm` behavior.
The `ModelSerializer` and `HyperlinkedModelSerializer` classes should now
include either a `fields` or `exclude` option, although the `fields =
'__all__'` shortcut may be used. Failing to include either of these two options
is currently pending deprecation, and will be removed entirely in the 3.5
release. This behavior brings `ModelSerializer` more closely in line with
Django's `ModelForm` behavior.
[forms-api]: html-and-forms.md
[ajax-form]: https://github.com/tomchristie/ajax-form
[jsonfield]: ../../api-guide/fields#jsonfield
[django-supported-versions]: https://www.djangoproject.com/download/#supported-versions
[django-supported-versions]: https://www.djangoproject.com/download/#supported-versions

View File

@ -1,37 +1,62 @@
# Working with AJAX, CSRF & CORS
> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability &mdash; very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."
> "Take a close look at possible CSRF / XSRF vulnerabilities on your own
> websites. They're the worst kind of vulnerability &mdash; very easy to
> exploit by attackers, yet not so intuitively easy to understand for software
> developers, at least until you've been bitten by one."
>
> &mdash; [Jeff Atwood][cite]
## Javascript clients
If youre building a JavaScript client to interface with your Web API, you'll need to consider if the client can use the same authentication policy that is used by the rest of the website, and also determine if you need to use CSRF tokens or CORS headers.
If youre building a JavaScript client to interface with your Web API, you'll
need to consider if the client can use the same authentication policy that is
used by the rest of the website, and also determine if you need to use CSRF
tokens or CORS headers.
AJAX requests that are made within the same context as the API they are interacting with will typically use `SessionAuthentication`. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website.
AJAX requests that are made within the same context as the API they are
interacting with will typically use `SessionAuthentication`. This ensures that
once a user has logged in, any AJAX requests made can be authenticated using
the same session-based authentication that is used for the rest of the website.
AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as `TokenAuthentication`.
AJAX requests that are made on a different site from the API they are
communicating with will typically need to use a non-session-based
authentication scheme, such as `TokenAuthentication`.
## CSRF protection
[Cross Site Request Forgery][csrf] protection is a mechanism of guarding against a particular type of attack, which can occur when a user has not logged out of a web site, and continues to have a valid session. In this circumstance a malicious site may be able to perform actions against the target site, within the context of the logged-in session.
[Cross Site Request Forgery][csrf] protection is a mechanism of guarding
against a particular type of attack, which can occur when a user has not logged
out of a web site, and continues to have a valid session. In this
circumstance a malicious site may be able to perform actions against the target
site, within the context of the logged-in session.
To guard against these type of attacks, you need to do two things:
1. Ensure that the 'safe' HTTP operations, such as `GET`, `HEAD` and `OPTIONS` cannot be used to alter any server-side state.
2. Ensure that any 'unsafe' HTTP operations, such as `POST`, `PUT`, `PATCH` and `DELETE`, always require a valid CSRF token.
1. Ensure that the 'safe' HTTP operations, such as `GET`, `HEAD` and `OPTIONS`
cannot be used to alter any server-side state.
2. Ensure that any 'unsafe' HTTP operations, such as `POST`, `PUT`, `PATCH` and
`DELETE`, always require a valid CSRF token.
If you're using `SessionAuthentication` you'll need to include valid CSRF tokens for any `POST`, `PUT`, `PATCH` or `DELETE` operations.
If you're using `SessionAuthentication` you'll need to include valid CSRF
tokens for any `POST`, `PUT`, `PATCH` or `DELETE` operations.
In order to make AJAX requests, you need to include CSRF token in the HTTP header, as [described in the Django documentation][csrf-ajax].
In order to make AJAX requests, you need to include CSRF token in the HTTP
header, as [described in the Django documentation][csrf-ajax].
## CORS
[Cross-Origin Resource Sharing][cors] is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed.
[Cross-Origin Resource Sharing][cors] is a mechanism for allowing clients to
interact with APIs that are hosted on a different domain. CORS works by
requiring the server to include a specific set of headers that allow a browser
to determine if and when cross-domain requests should be allowed.
The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.
The best way to deal with CORS in REST framework is to add the required
response headers in middleware. This ensures that CORS is supported
transparently, without having to change any behavior in your views.
[Otto Yiu][ottoyiu] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs.
[Otto Yiu][ottoyiu] maintains the [django-cors-headers] package, which is known
to work correctly with REST framework APIs.
[cite]: http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html
[csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)

View File

@ -1,25 +1,42 @@
# The Browsable API
> It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them.
> It is a profoundly erroneous truism... that we should cultivate the habit of
> thinking of what we are doing. The precise opposite is the case.
> Civilization advances by extending the number of important operations which
> we can perform without thinking about them.
>
> &mdash; [Alfred North Whitehead][cite], An Introduction to Mathematics (1911)
API may stand for Application *Programming* Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the `HTML` format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using `POST`, `PUT`, and `DELETE`.
API may stand for Application *Programming* Interface, but humans have to be
able to read the APIs, too; someone has to do the programming. Django REST
Framework supports generating human-friendly HTML output for each resource when
the `HTML` format is requested. These pages allow for easy browsing of
resources, as well as forms for submitting data to the resources using `POST`,
`PUT`, and `DELETE`.
## URLs
If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The `rest_framework` package includes a [`reverse`][drfreverse] helper for this purpose.
If you include fully-qualified URLs in your resource output, they will be
'urlized' and made clickable for easy browsing by humans. The `rest_framework`
package includes a [`reverse`][drfreverse] helper for this purpose.
## Formats
By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox][ffjsonview] and [Chrome][chromejsonview].
By default, the API will return the format specified by the headers, which in
the case of the browser is HTML. The format can be specified using `?format=`
in the request, so you can look at the raw JSON response in a browser by adding
`?format=json` to the URL. There are helpful extensions for viewing JSON in
[Firefox][ffjsonview] and [Chrome][chromejsonview].
## Customizing
The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.3.5), making it easy to customize the look-and-feel.
The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.3.5),
making it easy to customize the look-and-feel.
To customize the default style, create a template called `rest_framework/api.html` that extends from `rest_framework/base.html`. For example:
To customize the default style, create a template called
`rest_framework/api.html` that extends from `rest_framework/base.html`. For
example:
**templates/rest_framework/api.html**
@ -29,15 +46,23 @@ To customize the default style, create a template called `rest_framework/api.htm
### Overriding the default theme
To replace the default theme, add a `bootstrap_theme` block to your `api.html` and insert a `link` to the desired Bootstrap theme css file. This will completely replace the included theme.
To replace the default theme, add a `bootstrap_theme` block to your `api.html`
and insert a `link` to the desired Bootstrap theme css file. This will
completely replace the included theme.
{% block bootstrap_theme %}
<link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css">
{% endblock %}
Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above.
Suitable pre-made replacement themes are available at [Bootswatch][bswatch].
To use any of the Bootswatch themes, simply download the theme's
`bootstrap.min.css` file, add it to your project, and replace the default one
as described above.
You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style.
You can also change the navbar variant, which by default is `navbar-inverse`,
using the `bootstrap_navbar_variant` block. The empty `{% block
bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap
navbar style.
Full example:
@ -86,11 +111,16 @@ All of the standard [Bootstrap components][bcomponents] are available.
#### Tooltips
The browsable API makes use of the Bootstrap tooltips component. Any element with the `js-tooltip` class and a `title` attribute has that title content will display a tooltip on hover events.
The browsable API makes use of the Bootstrap tooltips component. Any element
with the `js-tooltip` class and a `title` attribute has that title content will
display a tooltip on hover events.
### Login Template
To add branding and customize the look-and-feel of the login template, create a template called `login.html` and add it to your project, eg: `templates/rest_framework/login.html`. The template should extend from `rest_framework/login_base.html`.
To add branding and customize the look-and-feel of the login template, create a
template called `login.html` and add it to your project, eg:
`templates/rest_framework/login.html`. The template should extend from
`rest_framework/login_base.html`.
You can add your site name or branding by including the branding block:
@ -127,13 +157,19 @@ You can override the `BrowsableAPIRenderer.get_context()` method to customise th
#### Not using base.html
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.
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.
#### Handling `ChoiceField` with large numbers of items.
When a relationship or `ChoiceField` has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly.
When a relationship or `ChoiceField` has too many items, rendering the widget
containing all the options can become very slow, and cause the browsable API
rendering to perform poorly.
The simplest option in this case is to replace the select input with a standard text input. For example:
The simplest option in this case is to replace the select input with a standard
text input. For example:
author = serializers.HyperlinkedRelatedField(
queryset=User.objects.all(),
@ -142,9 +178,18 @@ The simplest option in this case is to replace the select input with a standard
#### Autocomplete
An alternative, but more complex option would be to replace the input with an autocomplete widget, that only loads and renders a subset of the available options as needed. If you need to do this you'll need to do some work to build a custom autocomplete HTML template yourself.
An alternative, but more complex option would be to replace the input with an
autocomplete widget, that only loads and renders a subset of the available
options as needed. If you need to do this you'll need to do some work to build
a custom autocomplete HTML template yourself.
There are [a variety of packages for autocomplete widgets][autocomplete-packages], such as [django-autocomplete-light][django-autocomplete-light], that you may want to refer to. Note that you will not be able to simply include these components as standard widgets, but will need to write the HTML template explicitly. This is because REST framework 3.0 no longer supports the `widget` keyword argument since it now uses templated HTML generation.
There are [a variety of packages for autocomplete
widgets][autocomplete-packages], such as
[django-autocomplete-light][django-autocomplete-light], that you may want to
refer to. Note that you will not be able to simply include these components as
standard widgets, but will need to write the HTML template explicitly. This is
because REST framework 3.0 no longer supports the `widget` keyword argument
since it now uses templated HTML generation.
Better support for autocomplete inputs is planned in future versions.

View File

@ -1,12 +1,16 @@
# Browser enhancements
> "There are two noncontroversial uses for overloaded POST. The first is to *simulate* HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE"
> "There are two noncontroversial uses for overloaded POST. The first is to
> *simulate* HTTP's uniform interface for clients like web browsers that don't
> support PUT or DELETE"
>
> &mdash; [RESTful Web Services][cite], Leonard Richardson & Sam Ruby.
In order to allow the browsable API to function, there are a couple of browser enhancements that REST framework needs to provide.
In order to allow the browsable API to function, there are a couple of browser
enhancements that REST framework needs to provide.
As of version 3.3.0 onwards these are enabled with javascript, using the [ajax-form][ajax-form] library.
As of version 3.3.0 onwards these are enabled with javascript, using the
[ajax-form][ajax-form] library.
## Browser based PUT, DELETE, etc...
@ -19,11 +23,15 @@ After including the library, use the `data-method` attribute on the form, like s
...
</form>
Note that prior to 3.3.0, this support was server-side rather than javascript based. The method overloading style (as used in [Ruby on Rails][rails]) is no longer supported due to subtle issues that it introduces in request parsing.
Note that prior to 3.3.0, this support was server-side rather than javascript
based. The method overloading style (as used in [Ruby on Rails][rails]) is no
longer supported due to subtle issues that it introduces in request parsing.
## Browser based submission of non-form content
Browser-based submission of content types such as JSON are supported by the [AJAX form library][ajax-form], using form fields with `data-override='content-type'` and `data-override='content'` attributes.
Browser-based submission of content types such as JSON are supported by the
[AJAX form library][ajax-form], using form fields with
`data-override='content-type'` and `data-override='content'` attributes.
For example:
@ -45,12 +53,14 @@ This behavior is controlled using the `URL_FORMAT_OVERRIDE` setting.
## HTTP header based method overriding
Prior to version 3.3.0 the semi extension header `X-HTTP-Method-Override` was supported for overriding the request method. This behavior is no longer in core, but can be adding if needed using middleware.
Prior to version 3.3.0 the semi extension header `X-HTTP-Method-Override` was
supported for overriding the request method. This behavior is no longer in
core, but can be adding if needed using middleware.
For example:
METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE'
class MethodOverrideMiddleware(object):
def process_view(self, request, callback, callback_args, callback_kwargs):
if request.method != 'POST':
@ -61,9 +71,13 @@ For example:
## URL based accept headers
Until version 3.3.0 REST framework included built-in support for `?accept=application/json` style URL parameters, which would allow the `Accept` header to be overridden.
Until version 3.3.0 REST framework included built-in support for
`?accept=application/json` style URL parameters, which would allow the `Accept`
header to be overridden.
Since the introduction of the content negotiation API this behavior is no longer included in core, but may be added using a custom content negotiation class, if needed.
Since the introduction of the content negotiation API this behavior is no
longer included in core, but may be added using a custom content negotiation
class, if needed.
For example:

View File

@ -1,200 +1,280 @@
# Contributing to REST framework
> The world can only really be changed one piece at a time. The art is picking that piece.
> The world can only really be changed one piece at a time. The art is picking
> that piece.
>
> &mdash; [Tim Berners-Lee][cite]
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
There are many ways you can contribute to Django REST framework. We'd like it
to be a community-led project, so please get involved and help shape the future
of the project.
## Community
The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
The most important thing you can do to help push the REST framework project
forward is to be actively involved wherever possible. Code contributions are
often overvalued as being the primary way to get involved in a project, we
don't believe that needs to be the case.
If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with.
If you use REST framework, we'd love you to be vocal about your experiences
with it - you might consider writing a blog post about using REST framework, or
publishing a tutorial about building a project with a particular JavaScript
framework. Experiences from beginners can be particularly helpful because
you'll be in the best position to assess which bits of REST framework are more
difficult to understand and work with.
Other really great ways you can help move the community forward include helping to answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag.
Other really great ways you can help move the community forward include helping
to answer questions on the [discussion group][google-group], or setting up an
[email alert on StackOverflow][so-filter] so that you get notified of any new
questions with the `django-rest-framework` tag.
When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.
When answering questions make sure to help future contributors find their way
around by hyperlinking wherever possible to related threads and tickets, and
include backlinks from those items if relevant.
## Code of conduct
Please keep the tone polite & professional. For some users a discussion on the REST framework mailing list or ticket tracker may be their first engagement with the open source community. First impressions count, so let's try to make everyone feel welcome.
Please keep the tone polite & professional. For some users a discussion on the
REST framework mailing list or ticket tracker may be their first engagement
with the open source community. First impressions count, so let's try to make
everyone feel welcome.
Be mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations.
Be mindful in the language you choose. As an example, in an environment that
is heavily male-dominated, posts that start 'Hey guys,' can come across as
unintentionally exclusive. It's just as easy, and more inclusive to use gender
neutral language in those situations.
The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines for participating in community forums.
The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines
for participating in community forums.
# Issues
It's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the [discussion group][google-group]. Feature requests, bug reports and other issues should be raised on the GitHub [issue tracker][issues].
It's really helpful if you can make sure to address issues on the correct
channel. Usage questions should be directed to the [discussion
group][google-group]. Feature requests, bug reports and other issues should be
raised on the GitHub [issue tracker][issues].
Some tips on good issue reporting:
* When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
* Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation.
* Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.
* When describing issues try to phrase your ticket in terms of the *behavior*
you think needs changing rather than the *code* you think need changing.
* Search the issue list first for related items, and make sure you're running
the latest version of REST framework before reporting an issue.
* If reporting a bug, then try to include a pull request with a failing test
case. This will help us quickly identify if there is a valid issue, and make
sure that it gets fixed more quickly if there is one.
* Feature requests will often be closed with a recommendation that they be
implemented outside of the core REST framework library. Keeping new feature
requests implemented as third party libraries allows us to keep down the
maintenance overhead of REST framework, so that the focus can be on continued
stability, bug fixes, and great documentation.
* Closing an issue doesn't necessarily mean the end of a discussion. If you
believe your issue has been closed incorrectly, explain why and we'll
consider if it needs to be reopened.
## Triaging issues
Getting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to
Getting involved in triaging incoming issues is a good way to start
contributing. Every single ticket that comes into the ticket tracker needs to
be reviewed in order to determine what the next steps should be. Anyone can
help out with this, you just need to be willing to:
* Read through the ticket - does it make sense, is it missing any context that would help explain it better?
* Is the ticket reported in the correct place, would it be better suited as a discussion on the discussion group?
* If the ticket is a bug report, can you reproduce it? Are you able to write a failing test case that demonstrates the issue and that can be submitted as a pull request?
* If the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package?
* If a ticket hasn't had much activity and it addresses something you need, then comment on the ticket and try to find out what's needed to get it moving again.
* Read through the ticket - does it make sense, is it missing any context that
would help explain it better?
* Is the ticket reported in the correct place, would it be better suited as a
discussion on the discussion group?
* If the ticket is a bug report, can you reproduce it? Are you able to write a
failing test case that demonstrates the issue and that can be submitted as a
pull request?
* If the ticket is a feature request, do you agree with it, and could the
feature request instead be implemented as a third party package?
* If a ticket hasn't had much activity and it addresses something you need,
then comment on the ticket and try to find out what's needed to get it moving
again.
# Development
To start developing on Django REST framework, clone the repo:
git clone git@github.com:tomchristie/django-rest-framework.git
git clone git@github.com:tomchristie/django-rest-framework.git
Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.
Changes should broadly follow the [PEP 8][pep-8] style conventions, and we
recommend you set up your editor to automatically indicate non-conforming
styles.
## Testing
To run the tests, clone the repository, and then:
# Setup the virtual environment
virtualenv env
source env/bin/activate
pip install -r requirements.txt
# Setup the virtual environment virtualenv env source env/bin/activate pip
install -r requirements.txt
# Run the tests
./runtests.py
# Run the tests ./runtests.py
### Test options
Run using a more concise output style.
./runtests.py -q
./runtests.py -q
Run the tests using a more concise output style, no coverage, no flake8.
./runtests.py --fast
./runtests.py --fast
Don't run the flake8 code linting.
./runtests.py --nolint
./runtests.py --nolint
Only run the flake8 code linting, don't run the tests.
./runtests.py --lintonly
./runtests.py --lintonly
Run the tests for a given test case.
./runtests.py MyTestCase
./runtests.py MyTestCase
Run the tests for a given test method.
./runtests.py MyTestCase.test_this_method
./runtests.py MyTestCase.test_this_method
Shorter form to run the tests for a given test method.
./runtests.py test_this_method
./runtests.py test_this_method
Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.
Note: The test case and test method matching is fuzzy and will sometimes run
other tests that contain a partial string match to the given command line
input.
### Running against multiple environments
You can also use the excellent [tox][tox] testing tool to run the tests against all supported versions of Python and Django. Install `tox` globally, and then simply run:
You can also use the excellent [tox][tox] testing tool to run the tests against
all supported versions of Python and Django. Install `tox` globally, and then
simply run:
tox
tox
## Pull requests
It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.
It's a good idea to make pull requests early on. A pull request represents the
start of a discussion, and doesn't necessarily need to be the final, finished
submission.
It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests.
It's also always best to make a new branch before starting work on a pull
request. This means that you'll be able to later switch back to working on
another separate issue without interfering with an ongoing pull requests.
It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests.
It's also useful to remember that if you have an outstanding pull request then
pushing new commits to your GitHub repo will also automatically update the pull
requests.
GitHub's documentation for working on pull requests is [available here][pull-requests].
GitHub's documentation for working on pull requests is [available
here][pull-requests].
Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django.
Always run the tests before submitting pull requests, and ideally run `tox` in
order to check that your modifications are compatible with both Python 2 and
Python 3, and that they run properly on all supported versions of Django.
Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect.
![Travis status][travis-status]
*Above: Travis build notifications*
Once you've made a pull request take a look at the Travis build status in the
GitHub interface and make sure the tests are running as you'd expect.
## Managing compatibility issues
Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the `compat.py` module, and should provide a single common interface that the rest of the codebase can use.
Sometimes, in order to ensure your code works on various different versions of
Django, Python or third party libraries, you'll need to run slightly different
code depending on the environment. Any code that branches in this way should
be isolated into the `compat.py` module, and should provide a single common
interface that the rest of the codebase can use.
# Documentation
The documentation for REST framework is built from the [Markdown][markdown] source files in [the docs directory][docs].
The documentation for REST framework is built from the [Markdown][markdown]
source files in [the docs directory][docs].
There are many great Markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended.
There are many great Markdown editors that make working with the documentation
really easy. The [Mou editor for Mac][mou] is one such editor that comes
highly recommended.
## Building the documentation
To build the documentation, install MkDocs with `pip install mkdocs` and then run the following command.
To build the documentation, install MkDocs with `pip install mkdocs` and then
run the following command.
mkdocs build
mkdocs build
This will build the documentation into the `site` directory.
You can build the documentation and open a preview in a browser window by using the `serve` command.
You can build the documentation and open a preview in a browser window by using
the `serve` command.
mkdocs serve
mkdocs serve
## Language style
Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible.
Documentation should be in American English. The tone of the documentation is
very important - try to stick to a simple, plain, objective and well-balanced
style where possible.
Some other tips:
* Keep paragraphs reasonably short.
* Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.
* Don't use abbreviations such as 'e.g.' but instead use
the long form, such as 'For example'.
## Markdown style
There are a couple of conventions you should follow when working on the documentation.
There are a couple of conventions you should follow when working on the
documentation.
##### 1. Headers
Headers should use the hash style. For example:
Headers should use the hash style. For example:
### Some important topic
### Some important topic
The underline style should not be used. **Don't do this:**
The underline style should not be used. **Don't do this:**
Some important topic
====================
Some important topic ====================
##### 2. Links
Links should always use the reference style, with the referenced hyperlinks kept at the end of the document.
Links should always use the reference style, with the referenced hyperlinks
kept at the end of the document.
Here is a link to [some other thing][other-thing].
Here is a link to [some other thing][other-thing].
More text...
More text...
[other-thing]: http://example.com/other/thing
[other-thing]: http://example.com/other/thing
This style helps keep the documentation source consistent and readable.
If you are hyperlinking to another REST framework document, you should use a relative link, and link to the `.md` suffix. For example:
If you are hyperlinking to another REST framework document, you should use a
relative link, and link to the `.md` suffix. For example:
[authentication]: ../api-guide/authentication.md
[authentication]: ../api-guide/authentication.md
Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.
Linking in this style means you'll be able to click the hyperlink in your
Markdown editor to open the referenced document. When the documentation is
built, these links will be converted into regular links to HTML pages.
##### 3. Notes
If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:
If you want to draw attention to a note or warning, use a pair of enclosing
lines, like so:
---
---
**Note:** A useful documentation note.
**Note:** A useful documentation note.
---
---
[cite]: http://www.w3.org/People/Berners-Lee/FAQ.html
@ -203,7 +283,6 @@ If you want to draw attention to a note or warning, use a pair of enclosing line
[so-filter]: http://stackexchange.com/filters/66475/rest-framework
[issues]: https://github.com/tomchristie/django-rest-framework/issues?state=open
[pep-8]: http://www.python.org/dev/peps/pep-0008/
[travis-status]: ../img/travis-status.png
[pull-requests]: https://help.github.com/articles/using-pull-requests
[tox]: https://tox.readthedocs.io/en/latest/
[markdown]: http://daringfireball.net/projects/markdown/basics

View File

@ -1,24 +1,40 @@
# Documenting your API
> 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.
> 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.
>
> &mdash; Roy Fielding, [REST APIs must be hypertext driven][cite]
There are a variety of approaches to API documentation. This document introduces a few of the various tools and options you might choose from. The approaches should not be considered exclusive - you may want to provide more than one documentation style for you API, such as a self describing API that also includes static documentation of the various API endpoints.
There are a variety of approaches to API documentation. This document
introduces a few of the various tools and options you might choose from. The
approaches should not be considered exclusive - you may want to provide more
than one documentation style for you API, such as a self describing API that
also includes static documentation of the various API endpoints.
## Endpoint documentation
The most common way to document Web APIs today is to produce documentation that lists the API endpoints verbatim, and describes the allowable operations on each. There are various tools that allow you to do this in an automated or semi-automated way.
The most common way to document Web APIs today is to produce documentation that
lists the API endpoints verbatim, and describes the allowable operations on
each. There are various tools that allow you to do this in an automated or
semi-automated way.
---
#### DRF Docs
[DRF Docs][drfdocs-repo] allows you to document Web APIs made with Django REST Framework and it is authored by Emmanouil Konstantinidis. It's made to work out of the box and its setup should not take more than a couple of minutes. Complete documentation can be found on the [website][drfdocs-website] while there is also a [demo][drfdocs-demo] available for people to see what it looks like. **Live API Endpoints** allow you to utilize the endpoints from within the documentation in a neat way.
[DRF Docs][drfdocs-repo] allows you to document Web APIs made with Django REST
Framework and it is authored by Emmanouil Konstantinidis. It's made to work out
of the box and its setup should not take more than a couple of minutes.
Complete documentation can be found on the [website][drfdocs-website] while
there is also a [demo][drfdocs-demo] available for people to see what it looks
like. **Live API Endpoints** allow you to utilize the endpoints from within the
documentation in a neat way.
Features include customizing the template with your branding, settings for hiding the docs depending on the environment and more.
Features include customizing the template with your branding, settings for
hiding the docs depending on the environment and more.
Both this package and Django REST Swagger are fully documented, well supported, and come highly recommended.
Both this package and Django REST Swagger are fully documented, well supported,
and come highly recommended.
![Screenshot - DRF docs][image-drf-docs]
@ -26,13 +42,19 @@ Both this package and Django REST Swagger are fully documented, well supported,
#### Django REST Swagger
Marc Gibbons' [Django REST Swagger][django-rest-swagger] integrates REST framework with the [Swagger][swagger] API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints.
Marc Gibbons' [Django REST Swagger][django-rest-swagger] integrates REST
framework with the [Swagger][swagger] API documentation tool. The package
produces well presented API documentation, and includes interactive tools for
testing API endpoints.
Django REST Swagger supports REST framework versions 2.3 and above.
Mark is also the author of the [REST Framework Docs][rest-framework-docs] package which offers clean, simple autogenerated documentation for your API but is deprecated and has moved to Django REST Swagger.
Mark is also the author of the [REST Framework Docs][rest-framework-docs]
package which offers clean, simple autogenerated documentation for your API but
is deprecated and has moved to Django REST Swagger.
Both this package and DRF docs are fully documented, well supported, and come highly recommended.
Both this package and DRF docs are fully documented, well supported, and come
highly recommended.
![Screenshot - Django REST Swagger][image-django-rest-swagger]
@ -40,7 +62,11 @@ Both this package and DRF docs are fully documented, well supported, and come hi
#### Apiary
There are various other online tools and services for providing API documentation. One notable service is [Apiary][apiary]. With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing & prototyping, and various other tools.
There are various other online tools and services for providing API
documentation. One notable service is [Apiary][apiary]. With Apiary, you
describe your API using a simple markdown-like syntax. The generated
documentation includes API interaction, a mock server for testing &
prototyping, and various other tools.
![Screenshot - Apiary][image-apiary]
@ -48,7 +74,9 @@ There are various other online tools and services for providing API documentatio
## Self describing APIs
The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.
The browsable API that REST framework provides makes it possible for your API
to be entirely self describing. The documentation for each API endpoint can be
provided simply by visiting the URL in your browser.
![Screenshot - Self describing API][image-self-describing-api]
@ -56,17 +84,26 @@ The browsable API that REST framework provides makes it possible for your API to
#### Setting the title
The title that is used in the browsable API is generated from the view class name or function name. Any trailing `View` or `ViewSet` suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.
The title that is used in the browsable API is generated from the view class
name or function name. Any trailing `View` or `ViewSet` suffix is stripped,
and the string is whitespace separated on uppercase/lowercase boundaries or
underscores.
For example, the view `UserListView`, will be named `User List` when presented in the browsable API.
For example, the view `UserListView`, will be named `User List` when presented
in the browsable API.
When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set `UserViewSet` will generate views named `User List` and `User Instance`.
When working with viewsets, an appropriate suffix is appended to each generated
view. For example, the view set `UserViewSet` will generate views named `User
List` and `User Instance`.
#### Setting the description
The description in the browsable API is generated from the docstring of the view or viewset.
The description in the browsable API is generated from the docstring of the
view or viewset.
If the python `markdown` library is installed, then [markdown syntax][markdown] may be used in the docstring, and will be converted to HTML in the browsable API. For example:
If the python `markdown` library is installed, then [markdown syntax][markdown]
may be used in the docstring, and will be converted to HTML in the browsable
API. For example:
class AccountListView(views.APIView):
"""
@ -77,15 +114,23 @@ If the python `markdown` library is installed, then [markdown syntax][markdown]
[ref]: http://example.com/activating-accounts
"""
Note that one constraint of using viewsets is that any documentation be used for all generated views, so for example, you cannot have differing documentation for the generated list view and detail view.
Note that one constraint of using viewsets is that any documentation be used
for all generated views, so for example, you cannot have differing
documentation for the generated list view and detail view.
#### The `OPTIONS` method
REST framework APIs also support programmatically accessible descriptions, using the `OPTIONS` HTTP method. A view will respond to an `OPTIONS` request with metadata including the name, description, and the various media types it accepts and responds with.
REST framework APIs also support programmatically accessible descriptions,
using the `OPTIONS` HTTP method. A view will respond to an `OPTIONS` request
with metadata including the name, description, and the various media types it
accepts and responds with.
When using the generic views, any `OPTIONS` requests will additionally respond with metadata regarding any `POST` or `PUT` actions available, describing which fields are on the serializer.
When using the generic views, any `OPTIONS` requests will additionally respond
with metadata regarding any `POST` or `PUT` actions available, describing which
fields are on the serializer.
You can modify the response behavior to `OPTIONS` requests by overriding the `metadata` view method. For example:
You can modify the response behavior to `OPTIONS` requests by overriding the
`metadata` view method. For example:
def metadata(self, request):
"""
@ -99,11 +144,20 @@ You can modify the response behavior to `OPTIONS` requests by overriding the `me
## The hypermedia approach
To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.
To be fully RESTful an API should present its available actions as hypermedia
controls in the responses that it sends.
In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the *media types* that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.
In this approach, rather than documenting the available API endpoints up front,
the description instead concentrates on the *media types* that are used. The
available actions that may be taken on any given URL are not strictly fixed,
but are instead made available by the presence of link and form controls in the
returned document.
To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The [REST, Hypermedia & HATEOAS][hypermedia-docs] section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.
To implement a hypermedia API you'll need to decide on an appropriate media
type for the API, and implement a custom renderer and parser for that media
type. The [REST, Hypermedia & HATEOAS][hypermedia-docs] section of the
documentation includes pointers to background reading, as well as links to
various hypermedia formats.
[cite]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
[drfdocs-repo]: https://github.com/ekonstantinidis/django-rest-framework-docs

View File

@ -97,21 +97,32 @@ form.signup {
# Funding
> As a direct result of [a successful Mozilla grant application](mozilla-grant.md), I will be leaving my current role at [DabApps](http://www.dabapps.com), and attempting to secure a sustainable business model for REST framework development. I need your help in order to make this work.
> As a direct result of [a successful Mozilla grant
> application](mozilla-grant.md), I will be leaving my current role at
> [DabApps](http://www.dabapps.com), and attempting to secure a sustainable
> business model for REST framework development. I need your help in order to
> make this work.
>
> &mdash; Tom Christie
If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan.
If you use REST framework commercially we strongly encourage you to invest in
its continued development by signing up for a paid plan.
**We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development.**
**We believe that collaboratively funded software can offer outstanding returns
on investment, by encouraging our users to collectively share the cost of
development.**
Signing up for a paid plan will:
* Directly contribute to faster releases, more features, and higher quality software.
* Allow more time to be invested in documentation, issue triage, and community support.
* Directly contribute to faster releases, more features, and higher quality
software.
* Allow more time to be invested in documentation, issue triage, and community
support.
* Safeguard the future development of REST framework.
REST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development.
REST framework continues to be open-source and permissively licensed, but we
firmly believe it is in the commercial best-interest for users of the project
to invest in its ongoing development.
---
@ -134,17 +145,22 @@ With *typical corporate fundings of just £100-£1000 per organization* we succe
* The metadata APIs for handling `OPTIONS` requests and schema endpoints.
* Numerous minor improvements and better quality throughout the codebase.
This incredible level of return on investment is *only possible through collaboratively funded models*, which is why we believe that supporting our paid plans is in everyone's best interest.
This incredible level of return on investment is *only possible through
collaboratively funded models*, which is why we believe that supporting our
paid plans is in everyone's best interest.
Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project.
Sign up for a paid plan today, and help ensure that REST framework becomes a
sustainable, full-time funded project.
---
## Freelancer plan
This subscription is recommended for freelancers and other individuals with an interest in seeing REST framework continue to&nbsp;improve.
This subscription is recommended for freelancers and other individuals with an
interest in seeing REST framework continue to&nbsp;improve.
If you are using REST framework as an full-time employee, consider recommending that your company takes out a [corporate&nbsp;plan](#corporate-plans).
If you are using REST framework as an full-time employee, consider recommending
that your company takes out a [corporate&nbsp;plan](#corporate-plans).
<div class="pricing">
<div class="span4">
@ -188,11 +204,16 @@ If you are using REST framework as an full-time employee, consider recommending
## Corporate plans
These subscriptions are recommended for companies and organizations using REST framework either publicly or privately.
These subscriptions are recommended for companies and organizations using REST
framework either publicly or privately.
In exchange for funding you'll also receive advertising space on our site, allowing you to **promote your company or product to many tens of thousands of developers worldwide**.
In exchange for funding you'll also receive advertising space on our site,
allowing you to **promote your company or product to many tens of thousands of
developers worldwide**.
Our professional and premium plans also include **priority support**. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day.
Our professional and premium plans also include **priority support**. At any
time your engineers can escalate an issue or discussion group thread, and we'll
ensure it gets a guaranteed response within the next working day.
<div class="pricing">
<div class="span4">

View File

@ -1,18 +1,27 @@
# HTML & Forms
REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.
REST framework is suitable for returning both API style responses, and regular
HTML pages. Additionally, serializers can used as HTML forms and rendered in
templates.
## Rendering HTML
In order to return HTML responses you'll need to either `TemplateHTMLRenderer`, or `StaticHTMLRenderer`.
In order to return HTML responses you'll need to either `TemplateHTMLRenderer`,
or `StaticHTMLRenderer`.
The `TemplateHTMLRenderer` class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.
The `TemplateHTMLRenderer` class expects the response to contain a dictionary
of context data, and renders an HTML page based on a template that must be
specified either in the view or on the response.
The `StaticHTMLRender` class expects the response to contain a string of the pre-rendered HTML content.
The `StaticHTMLRender` class expects the response to contain a string of the
pre-rendered HTML content.
Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.
Because static HTML pages typically have different behavior from API responses
you'll probably need to write any HTML views explicitly, rather than relying on
the built-in generic views.
Here's an example of a view that returns a list of "Profile" instances, rendered in an HTML template:
Here's an example of a view that returns a list of "Profile" instances,
rendered in an HTML template:
**views.py**:
@ -40,12 +49,14 @@ Here's an example of a view that returns a list of "Profile" instances, rendered
{% endfor %}
</ul>
</body></html>
## Rendering Forms
Serializers may be rendered as forms by using the `render_form` template tag, and including the serializer instance as context to the template.
Serializers may be rendered as forms by using the `render_form` template tag,
and including the serializer instance as context to the template.
The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:
The following view demonstrates an example of using a serializer in a template
for viewing and updating a model instance:
**views.py**:
@ -77,7 +88,7 @@ The following view demonstrates an example of using a serializer in a template f
{% load rest_framework %}
<html><body>
<h1>Profile - {{ profile.name }}</h1>
<form action="{% url 'profile-detail' pk=profile.pk %}" method="POST">
@ -90,9 +101,14 @@ The following view demonstrates an example of using a serializer in a template f
### Using template packs
The `render_form` tag takes an optional `template_pack` argument, that specifies which template directory should be used for rendering the form and form fields.
The `render_form` tag takes an optional `template_pack` argument, that
specifies which template directory should be used for rendering the form and
form fields.
REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are `horizontal`, `vertical`, and `inline`. The default style is `horizontal`. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.
REST framework includes three built-in template packs, all based on Bootstrap
3. The built-in styles are `horizontal`, `vertical`, and `inline`. The default
style is `horizontal`. To use any of these template packs you'll want to also
include the Bootstrap 3 CSS.
The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:
@ -101,9 +117,12 @@ The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.
Third party packages may include alternate template packs, by bundling a
template directory containing the necessary form and field templates.
Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a "Login" form.
Let's take a look at how to render each of the three available template packs.
For these examples we'll use a single serializer class to present a "Login"
form.
class LoginSerializer(serializers.Serializer):
email = serializers.EmailField(
@ -120,7 +139,8 @@ Let's take a look at how to render each of the three available template packs. F
#### `rest_framework/vertical`
Presents form labels above their corresponding control inputs, using the standard Bootstrap layout.
Presents form labels above their corresponding control inputs, using the
standard Bootstrap layout.
*This is the default template pack.*
@ -180,25 +200,34 @@ A compact form style that presents all the controls inline.
## Field styles
Serializer fields can have their rendering style customized by using the `style` keyword argument. This argument is a dictionary of options that control the template and layout used.
Serializer fields can have their rendering style customized by using the
`style` keyword argument. This argument is a dictionary of options that control
the template and layout used.
The most common way to customize the field style is to use the `base_template` style keyword argument to select which template in the template pack should be use.
The most common way to customize the field style is to use the `base_template`
style keyword argument to select which template in the template pack should be
use.
For example, to render a `CharField` as an HTML textarea rather than the default HTML input, you would use something like this:
For example, to render a `CharField` as an HTML textarea rather than the
default HTML input, you would use something like this:
details = serializers.CharField(
max_length=1000,
style={'base_template': 'textarea.html'}
)
If you instead want a field to be rendered using a custom template that is *not part of an included template pack*, you can instead use the `template` style option, to fully specify a template name:
If you instead want a field to be rendered using a custom template that is *not
part of an included template pack*, you can instead use the `template` style
option, to fully specify a template name:
details = serializers.CharField(
max_length=1000,
style={'template': 'my-field-templates/custom-input.html'}
)
Field templates can also use additional style properties, depending on their type. For example, the `textarea.html` template also accepts a `rows` property that can be used to affect the sizing of the control.
Field templates can also use additional style properties, depending on their
type. For example, the `textarea.html` template also accepts a `rows` property
that can be used to affect the sizing of the control.
details = serializers.CharField(
max_length=1000,
@ -207,7 +236,7 @@ Field templates can also use additional style properties, depending on their typ
The complete list of `base_template` options and their associated style options is listed below.
base_template | Valid field types | Additional style options
base_template | Valid field types | Additional style options
----|----|----
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label
textarea.html | `CharField` | rows, placeholder, hide_label

View File

@ -4,27 +4,36 @@
>
> &mdash; [Jannis Leidel, speaking at Django Under the Hood, 2015][cite].
REST framework ships with translatable error messages. You can make these appear in your language enabling [Django's standard translation mechanisms][django-translation].
REST framework ships with translatable error messages. You can make these
appear in your language enabling [Django's standard translation
mechanisms][django-translation].
Doing so will allow you to:
* Select a language other than English as the default, using the standard `LANGUAGE_CODE` Django setting.
* Allow clients to choose a language themselves, using the `LocaleMiddleware` included with Django. A typical usage for API clients would be to include an `Accept-Language` request header.
* Select a language other than English as the default, using the standard
`LANGUAGE_CODE` Django setting.
* Allow clients to choose a language themselves, using the `LocaleMiddleware`
included with Django. A typical usage for API clients would be to include an
`Accept-Language` request header.
## Enabling internationalized APIs
You can change the default language by using the standard Django `LANGUAGE_CODE` setting:
You can change the default language by using the standard Django
`LANGUAGE_CODE` setting:
LANGUAGE_CODE = "es-es"
You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE_CLASSES` setting:
You can turn on per-request language requests by adding `LocalMiddleware` to
your `MIDDLEWARE_CLASSES` setting:
MIDDLEWARE_CLASSES = [
...
'django.middleware.locale.LocaleMiddleware'
]
When per-request internationalization is enabled, client requests will respect the `Accept-Language` header where possible. For example, let's make a request for an unsupported media type:
When per-request internationalization is enabled, client requests will respect
the `Accept-Language` header where possible. For example, let's make a request
for an unsupported media type:
**Request**
@ -39,19 +48,25 @@ When per-request internationalization is enabled, client requests will respect t
{"detail": "No se ha podido satisfacer la solicitud de cabecera de Accept."}
REST framework includes these built-in translations both for standard exception cases, and for serializer validation errors.
REST framework includes these built-in translations both for standard exception
cases, and for serializer validation errors.
Note that the translations only apply to the error strings themselves. The format of error messages, and the keys of field names will remain the same. An example `400 Bad Request` response body might look like this:
Note that the translations only apply to the error strings themselves. The
format of error messages, and the keys of field names will remain the same. An
example `400 Bad Request` response body might look like this:
{"detail": {"username": ["Esse campo deve ser unico."]}}
If you want to use different string for parts of the response such as `detail` and `non_field_errors` then you can modify this behavior by using a [custom exception handler][custom-exception-handler].
If you want to use different string for parts of the response such as `detail`
and `non_field_errors` then you can modify this behavior by using a [custom
exception handler][custom-exception-handler].
#### Specifying the set of supported languages.
By default all available languages will be supported.
If you only wish to support a subset of the available languages, use Django's standard `LANGUAGES` setting:
If you only wish to support a subset of the available languages, use Django's
standard `LANGUAGES` setting:
LANGUAGES = [
('de', _('German')),
@ -60,53 +75,80 @@ If you only wish to support a subset of the available languages, use Django's st
## Adding new translations
REST framework translations are managed online using [Transifex][transifex-project]. You can use the Transifex service to add new translation languages. The maintenance team will then ensure that these translation strings are included in the REST framework package.
REST framework translations are managed online using
[Transifex][transifex-project]. You can use the Transifex service to add new
translation languages. The maintenance team will then ensure that these
translation strings are included in the REST framework package.
Sometimes you may need to add translation strings to your project locally. You may need to do this if:
Sometimes you may need to add translation strings to your project locally. You
may need to do this if:
* You want to use REST Framework in a language which has not been translated yet on Transifex.
* Your project includes custom error messages, which are not part of REST framework's default translation strings.
* You want to use REST Framework in a language which has not been translated
yet on Transifex.
* Your project includes custom error messages, which are not part of REST
framework's default translation strings.
#### Translating a new language locally
This guide assumes you are already familiar with how to translate a Django app. If you're not, start by reading [Django's translation docs][django-translation].
This guide assumes you are already familiar with how to translate a Django app.
If you're not, start by reading [Django's translation
docs][django-translation].
If you're translating a new language you'll need to translate the existing REST framework error messages:
If you're translating a new language you'll need to translate the existing REST
framework error messages:
1. Make a new folder where you want to store the internationalization resources. Add this path to your [`LOCALE_PATHS`][django-locale-paths] setting.
1. Make a new folder where you want to store the internationalization
resources. Add this path to your [`LOCALE_PATHS`][django-locale-paths] setting.
2. Now create a subfolder for the language you want to translate. The folder should be named using [locale name][django-locale-name] notation. For example: `de`, `pt_BR`, `es_AR`.
2. Now create a subfolder for the language you want to translate. The folder
should be named using [locale name][django-locale-name] notation. For example:
`de`, `pt_BR`, `es_AR`.
3. Now copy the [base translations file][django-po-source] from the REST framework source code into your translations folder.
3. Now copy the [base translations file][django-po-source] from the REST
framework source code into your translations folder.
4. Edit the `django.po` file you've just copied, translating all the error messages.
4. Edit the `django.po` file you've just copied, translating all the error
messages.
5. Run `manage.py compilemessages -l pt_BR` to make the translations
available for Django to use. You should see a message like `processing file django.po in <...>/locale/pt_BR/LC_MESSAGES`.
5. Run `manage.py compilemessages -l pt_BR` to make the translations available
for Django to use. You should see a message like `processing file django.po in
<...>/locale/pt_BR/LC_MESSAGES`.
6. Restart your development server to see the changes take effect.
If you're only translating custom error messages that exist inside your project codebase you don't need to copy the REST framework source `django.po` file into a `LOCALE_PATHS` folder, and can instead simply run Django's standard `makemessages` process.
If you're only translating custom error messages that exist inside your project
codebase you don't need to copy the REST framework source `django.po` file into
a `LOCALE_PATHS` folder, and can instead simply run Django's standard
`makemessages` process.
## How the language is determined
If you want to allow per-request language preferences you'll need to include `django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE_CLASSES` setting.
If you want to allow per-request language preferences you'll need to include
`django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE_CLASSES`
setting.
You can find more information on how the language preference is determined in the [Django documentation][django-language-preference]. For reference, the method is:
You can find more information on how the language preference is determined in
the [Django documentation][django-language-preference]. For reference, the
method is:
1. First, it looks for the language prefix in the requested URL.
2. Failing that, it looks for the `LANGUAGE_SESSION_KEY` key in the current users session.
2. Failing that, it looks for the `LANGUAGE_SESSION_KEY` key in the current
users session.
3. Failing that, it looks for a cookie.
4. Failing that, it looks at the `Accept-Language` HTTP header.
5. Failing that, it uses the global `LANGUAGE_CODE` setting.
For API clients the most appropriate of these will typically be to use the `Accept-Language` header; Sessions and cookies will not be available unless using session authentication, and generally better practice to prefer an `Accept-Language` header for API clients rather than using language URL prefixes.
For API clients the most appropriate of these will typically be to use the
`Accept-Language` header; Sessions and cookies will not be available unless
using session authentication, and generally better practice to prefer an
`Accept-Language` header for API clients rather than using language URL
prefixes.
[cite]: http://youtu.be/Wa0VfS2q94Y
[django-translation]: https://docs.djangoproject.com/en/1.7/topics/i18n/translation
[custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling
[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/
[django-po-source]: https://raw.githubusercontent.com/tomchristie/django-rest-framework/master/rest_framework/locale/en_US/LC_MESSAGES/django.po
[django-po-source]: https://raw.githubusercontent.com/tomchristie/django-rest-framework/master/rest_framework/locale/en_US/LC_MESSAGES/django.po
[django-language-preference]: https://docs.djangoproject.com/en/1.7/topics/i18n/translation/#how-django-discovers-language-preference
[django-locale-paths]: https://docs.djangoproject.com/en/1.7/ref/settings/#std:setting-LOCALE_PATHS
[django-locale-name]: https://docs.djangoproject.com/en/1.7/topics/i18n/#term-locale-name

View File

@ -6,11 +6,14 @@
---
In order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3.
In order to continue to drive the project forward, I'm launching a Kickstarter
campaign to help fund the development of a major new release - Django REST
framework 3.
## Project details
This new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following:
This new release will allow us to comprehensively address some of the
shortcomings of the framework, and will aim to include the following:
* Faster, simpler and easier-to-use serializers.
* An alternative admin-style interface for the browsable API.
@ -20,9 +23,13 @@ This new release will allow us to comprehensively address some of the shortcomin
* Triage of outstanding tickets.
* Improving the ongoing quality and maintainability of the project.
Full details are available now on the [project page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3).
Full details are available now on the [project
page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3).
If you're interested in helping make sustainable open source development a reality please [visit the Kickstarter page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) and consider funding the project.
If you're interested in helping make sustainable open source development a
reality please [visit the Kickstarter
page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3)
and consider funding the project.
I can't wait to see where this takes us!
@ -34,13 +41,19 @@ Many thanks to everyone for your support so far,
## Sponsors
We've now blazed way past all our goals, with a staggering £30,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible.
We've now blazed way past all our goals, with a staggering £30,000 (~$50,000),
meaning I'll be in a position to work on the project significantly beyond what
we'd originally planned for. I owe a huge debt of gratitude to all the
wonderful companies and individuals who have been backing the project so
generously, and making this possible.
---
### Platinum sponsors
Our platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough.
Our platinum sponsors have each made a hugely substantial contribution to the
future development of Django REST framework, and I simply can't thank them
enough.
<ul class="sponsor diamond">
<li><a href="https://www.eventbrite.com/" rel="nofollow" style="background-image:url(../../img/sponsors/0-eventbrite.png);">Eventbrite</a></li>
@ -65,7 +78,9 @@ Our platinum sponsors have each made a hugely substantial contribution to the fu
### Gold sponsors
Our gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development.
Our gold sponsors include companies large and small. Many thanks for their
significant funding of the project and their commitment to sustainable
open-source development.
<ul class="sponsor gold">
<li><a href="https://laterpay.net/" rel="nofollow" style="background-image:url(../../img/sponsors/2-laterpay.png);">LaterPay</a></li>
@ -102,7 +117,9 @@ Our gold sponsors include companies large and small. Many thanks for their signi
### Silver sponsors
The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank&nbsp;you to individuals who have choosen to privately support the project at this level.
The serious financial contribution that our silver sponsors have made is very
much appreciated. I'd like to say a particular thank&nbsp;you to individuals
who have choosen to privately support the project at this level.
<ul class="sponsor silver">
<li><a href="http://www.imtapps.com/" rel="nofollow" style="background-image:url(../../img/sponsors/3-imt_computer_services.png);">IMT Computer Services</a></li>
@ -150,14 +167,31 @@ The serious financial contribution that our silver sponsors have made is very mu
### Advocates
The following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you!
The following individuals made a significant financial contribution to the
development of Django REST framework 3, for which I can only offer a huge, warm
and sincere thank you!
**Individual backers**: Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, Décébal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkkä, Charalampos Papaloizou, Nikolai Røed Kristiansen, Antoni Aloy López, Celia Oakley, Michał Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel.
**Individual backers**: Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal
Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross
Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton,
Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan
Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio
Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman,
Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C.
Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke
Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, Décébal Hormuz, James
Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkkä,
Charalampos Papaloizou, Nikolai Røed Kristiansen, Antoni Aloy López, Celia
Oakley, Michał Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan,
Ryan Kaskel.
**Corporate backers**: Savannah Informatics, Prism Skylabs, Musical Operating Devices.
**Corporate backers**: Savannah Informatics, Prism Skylabs, Musical Operating
Devices.
---
### Supporters
There were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!
There were also almost 300 further individuals choosing to help fund the
project at other levels or choosing to give anonymously. Again, thank you,
thank you, thank you!

View File

@ -1,16 +1,33 @@
# Mozilla Grant
We have recently been [awarded a Mozilla grant](https://blog.mozilla.org/blog/2016/04/13/mozilla-open-source-support-moss-update-q1-2016/), in order to fund the next major releases of REST framework. This work will focus on seamless client-side integration by introducing supporting client libraries that are able to dynamically interact with REST framework APIs. The framework will provide for either hypermedia or schema endpoints, which will expose the available interface for the client libraries to interact with.
We have recently been [awarded a Mozilla
grant](https://blog.mozilla.org/blog/2016/04/13/mozilla-open-source-support-moss-update-q1-2016/),
in order to fund the next major releases of REST framework. This work will
focus on seamless client-side integration by introducing supporting client
libraries that are able to dynamically interact with REST framework APIs. The
framework will provide for either hypermedia or schema endpoints, which will
expose the available interface for the client libraries to interact with.
Additionally, we will be building on the realtime support that Django Channels provides, supporting and documenting how to build realtime APIs with REST framework. Again, this will include supporting work in the associated client libraries, making it easier to build richly interactive applications.
Additionally, we will be building on the realtime support that Django Channels
provides, supporting and documenting how to build realtime APIs with REST
framework. Again, this will include supporting work in the associated client
libraries, making it easier to build richly interactive applications.
The [Core API](http://www.coreapi.org) project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with *any* API that exposes a supported schema or hypermedia format.
The [Core API](http://www.coreapi.org) project will provide the foundations for
our client library support, and will allow us to support interaction using a
wide range of schemas and hypermedia formats. It's worth noting that these
client libraries won't be tightly coupled to solely REST framework APIs either,
and will be able to interact with *any* API that exposes a supported schema or
hypermedia format.
Specifically, the work includes:
## Client libraries
This work will include built-in schema and hypermedia support, allowing dynamic client libraries to interact with the API. I'll also be releasing both Python and Javascript client libraries, plus a command-line client, a new tutorial section, and further documentation.
This work will include built-in schema and hypermedia support, allowing dynamic
client libraries to interact with the API. I'll also be releasing both Python
and Javascript client libraries, plus a command-line client, a new tutorial
section, and further documentation.
* Client library support in REST framework.
* Schema & hypermedia support for REST framework APIs.
@ -22,7 +39,8 @@ This work will include built-in schema and hypermedia support, allowing dynamic
## Realtime APIs
The next goal is to build on the realtime support offered by Django Channels, adding support & documentation for building realtime API endpoints.
The next goal is to build on the realtime support offered by Django Channels,
adding support & documentation for building realtime API endpoints.
* Support for API subscription endpoints, using REST framework and Django Channels.
* New tutorial section on building realtime API endpoints with REST framework.

View File

@ -6,14 +6,18 @@
This document outlines our project management processes for REST framework.
The aim is to ensure that the project has a high
["bus factor"][bus-factor], and can continue to remain well supported for the foreseeable future. Suggestions for improvements to our process are welcome.
The aim is to ensure that the project has a high ["bus factor"][bus-factor],
and can continue to remain well supported for the foreseeable future.
Suggestions for improvements to our process are welcome.
---
## Maintenance team
We have a quarterly maintenance cycle where new members may join the maintenance team. We currently cap the size of the team at 5 members, and may encourage folks to step out of the team for a cycle to allow new members to participate.
We have a quarterly maintenance cycle where new members may join the
maintenance team. We currently cap the size of the team at 5 members, and may
encourage folks to step out of the team for a cycle to allow new members to
participate.
#### Current team
@ -27,38 +31,42 @@ The [maintenance team for Q4 2015](https://github.com/tomchristie/django-rest-fr
#### Maintenance cycles
Each maintenance cycle is initiated by an issue being opened with the `Process` label.
Each maintenance cycle is initiated by an issue being opened with the `Process`
label.
* To be considered for a maintainer role simply comment against the issue.
* Existing members must explicitly opt-in to the next cycle by check-marking their name.
* Existing members must explicitly opt-in to the next cycle by check-marking
their name.
* The final decision on the incoming team will be made by `@tomchristie`.
Members of the maintenance team will be added as collaborators to the repository.
Members of the maintenance team will be added as collaborators to the
repository.
The following template should be used for the description of the issue, and serves as the formal process for selecting the team.
The following template should be used for the description of the issue, and
serves as the formal process for selecting the team.
This issue is for determining the maintenance team for the *** period.
Please see the [Project management](http://www.django-rest-framework.org/topics/project-management/) section of our documentation for more details.
---
#### Renewing existing members.
The following people are the current maintenance team. Please checkmark your name if you wish to continue to have write permission on the repository for the *** period.
- [ ] @***
- [ ] @***
- [ ] @***
- [ ] @***
- [ ] @***
---
#### New members.
If you wish to be considered for this or a future date, please comment against this or subsequent issues.
To modify this process for future maintenance cycles make a pull request to the [project management](http://www.django-rest-framework.org/topics/project-management/) documentation.
#### Responsibilities of team members
@ -116,24 +124,31 @@ The following template should be used for the description of the issue, and serv
- [ ] Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework).
- [ ] Make a release announcement on twitter.
- [ ] Close the milestone on GitHub.
To modify this process for future releases make a pull request to the [project management](http://www.django-rest-framework.org/topics/project-management/) documentation.
When pushing the release to PyPI ensure that your environment has been installed from our development `requirement.txt`, so that documentation and PyPI installs are consistently being built against a pinned set of packages.
When pushing the release to PyPI ensure that your environment has been
installed from our development `requirement.txt`, so that documentation and
PyPI installs are consistently being built against a pinned set of packages.
---
## Translations
The maintenance team are responsible for managing the translation packs include in REST framework. Translating the source strings into multiple languages is managed through the [transifex service][transifex-project].
The maintenance team are responsible for managing the translation packs include
in REST framework. Translating the source strings into multiple languages is
managed through the [transifex service][transifex-project].
### Managing Transifex
The [official Transifex client][transifex-client] is used to upload and download translations to Transifex. The client is installed using pip:
The [official Transifex client][transifex-client] is used to upload and
download translations to Transifex. The client is installed using pip:
pip install transifex-client
To use it you'll need a login to Transifex which has a password, and you'll need to have administrative access to the Transifex project. You'll need to create a `~/.transifexrc` file which contains your credentials.
To use it you'll need a login to Transifex which has a password, and you'll
need to have administrative access to the Transifex project. You'll need to
create a `~/.transifexrc` file which contains your credentials.
[https://www.transifex.com]
username = ***
@ -143,7 +158,8 @@ To use it you'll need a login to Transifex which has a password, and you'll need
### Upload new source files
When any user visible strings are changed, they should be uploaded to Transifex so that the translators can start to translate them. To do this, just run:
When any user visible strings are changed, they should be uploaded to Transifex
so that the translators can start to translate them. To do this, just run:
# 1. Update the source django.po file, which is the US English version.
cd rest_framework
@ -152,13 +168,17 @@ When any user visible strings are changed, they should be uploaded to Transifex
cd ..
tx push -s
When pushing source files, Transifex will update the source strings of a resource to match those from the new source file.
When pushing source files, Transifex will update the source strings of a
resource to match those from the new source file.
Here's how differences between the old and new source files will be handled:
* New strings will be added.
* Modified strings will be added as well.
* Strings which do not exist in the new source file will be removed from the database, along with their translations. If that source strings gets re-added later then [Transifex Translation Memory][translation-memory] will automatically include the translation string.
* Strings which do not exist in the new source file will be removed from the
database, along with their translations. If that source strings gets re-added
later then [Transifex Translation Memory][translation-memory] will
automatically include the translation string.
### Download translations
@ -174,17 +194,25 @@ When a translator has finished translating their work needs to be downloaded fro
## Project requirements
All our test requirements are pinned to exact versions, in order to ensure that our test runs are reproducible. We maintain the requirements in the `requirements` directory. The requirements files are referenced from the `tox.ini` configuration file, ensuring we have a single source of truth for package versions used in testing.
All our test requirements are pinned to exact versions, in order to ensure that
our test runs are reproducible. We maintain the requirements in the
`requirements` directory. The requirements files are referenced from the
`tox.ini` configuration file, ensuring we have a single source of truth for
package versions used in testing.
Package upgrades should generally be treated as isolated pull requests. You can check if there are any packages available at a newer version, by using the `pip list --outdated`.
Package upgrades should generally be treated as isolated pull requests. You can
check if there are any packages available at a newer version, by using the `pip
list --outdated`.
---
## Project ownership
The PyPI package is owned by `@tomchristie`. As a backup `@j4mie` also has ownership of the package.
The PyPI package is owned by `@tomchristie`. As a backup `@j4mie` also has
ownership of the package.
If `@tomchristie` ceases to participate in the project then `@j4mie` has responsibility for handing over ownership duties.
If `@tomchristie` ceases to participate in the project then `@j4mie` has
responsibility for handing over ownership duties.
#### Outstanding management & ownership issues

View File

@ -6,9 +6,13 @@
## Versioning
Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.
Minor version numbers (0.0.x) are used for changes that are API compatible.
You should be able to upgrade between minor point releases without any other
code changes.
Medium version numbers (0.x.0) may include API changes, in line with the [deprecation policy][deprecation-policy]. You should read the release notes carefully before upgrading between medium point releases.
Medium version numbers (0.x.0) may include API changes, in line with the
[deprecation policy][deprecation-policy]. You should read the release notes
carefully before upgrading between medium point releases.
Major version numbers (x.0.0) are reserved for substantial project milestones.

View File

@ -1,6 +1,8 @@
# Django REST framework 2.0
> Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result.
> Most people just make the mistake that it should be simple to design simple
> things. In reality, the effort required to design something is inversely
> proportional to the simplicity of the result.
>
> &mdash; [Roy Fielding][cite]
@ -10,65 +12,109 @@
---
REST framework 2 is an almost complete reworking of the original framework, which comprehensively addresses some of the original design issues.
REST framework 2 is an almost complete reworking of the original framework,
which comprehensively addresses some of the original design issues.
Because the latest version should be considered a re-release, rather than an incremental improvement, we've skipped a version, and called this release Django REST framework 2.0.
Because the latest version should be considered a re-release, rather than an
incremental improvement, we've skipped a version, and called this release
Django REST framework 2.0.
This article is intended to give you a flavor of what REST framework 2 is, and why you might want to give it a try.
This article is intended to give you a flavor of what REST framework 2 is, and
why you might want to give it a try.
## User feedback
Before we get cracking, let's start with the hard sell, with a few bits of feedback from some early adopters…
Before we get cracking, let's start with the hard sell, with a few bits of
feedback from some early adopters…
"Django REST framework 2 is beautiful. Some of the API design is worthy of @kennethreitz." - [Kit La Touche][quote1]
"Django REST framework 2 is beautiful. Some of the API design is worthy of
@kennethreitz." - [Kit La Touche][quote1]
"Since it's pretty much just Django, controlling things like URLs has been a breeze... I think [REST framework 2] has definitely got the right approach here; even simple things like being able to override a function called post to do custom work during rather than having to intimately know what happens during a post make a huge difference to your productivity." - [Ian Strachan][quote2]
"Since it's pretty much just Django, controlling things like URLs has been a
breeze... I think [REST framework 2] has definitely got the right approach
here; even simple things like being able to override a function called post to
do custom work during rather than having to intimately know what happens during
a post make a huge difference to your productivity." - [Ian
Strachan][quote2]
"I switched to the 2.0 branch and I don't regret it - fully refactored my code in another &half; day and it's *much* more to my tastes" - [Bruno Desthuilliers][quote3]
"I switched to the 2.0 branch and I don't regret it - fully refactored my code
in another &half; day and it's *much* more to my tastes" - [Bruno
Desthuilliers][quote3]
Sounds good, right? Let's get into some details...
## Serialization
REST framework 2 includes a totally re-worked serialization engine, that was initially intended as a replacement for Django's existing inflexible fixture serialization, and which meets the following design goals:
REST framework 2 includes a totally re-worked serialization engine, that was
initially intended as a replacement for Django's existing inflexible fixture
serialization, and which meets the following design goals:
* A declarative serialization API, that mirrors Django's `Forms`/`ModelForms` API.
* A declarative serialization API, that mirrors Django's `Forms`/`ModelForms`
API.
* Structural concerns are decoupled from encoding concerns.
* Able to support rendering and parsing to many formats, including both machine-readable representations and HTML forms.
* Able to support rendering and parsing to many formats, including both
machine-readable representations and HTML forms.
* Validation that can be mapped to obvious and comprehensive error responses.
* Serializers that support both nested, flat, and partially-nested representations.
* Relationships that can be expressed as primary keys, hyperlinks, slug fields, and other custom representations.
* Serializers that support both nested, flat, and partially-nested
representations.
* Relationships that can be expressed as primary keys, hyperlinks, slug fields,
and other custom representations.
Mapping between the internal state of the system and external representations of that state is the core concern of building Web APIs. Designing serializers that allow the developer to do so in a flexible and obvious way is a deceptively difficult design task, and with the new serialization API we think we've pretty much nailed it.
Mapping between the internal state of the system and external representations
of that state is the core concern of building Web APIs. Designing serializers
that allow the developer to do so in a flexible and obvious way is a
deceptively difficult design task, and with the new serialization API we think
we've pretty much nailed it.
## Generic views
When REST framework was initially released at the start of 2011, the current Django release was version 1.2. REST framework included a backport of Django 1.3's upcoming `View` class, but it didn't take full advantage of the generic view implementations.
When REST framework was initially released at the start of 2011, the current
Django release was version 1.2. REST framework included a backport of Django
1.3's upcoming `View` class, but it didn't take full advantage of the generic
view implementations.
With the new release the generic views in REST framework now tie in with Django's generic views. The end result is that framework is clean, lightweight and easy to use.
With the new release the generic views in REST framework now tie in with
Django's generic views. The end result is that framework is clean, lightweight
and easy to use.
## Requests, Responses & Views
REST framework 2 includes `Request` and `Response` classes, than are used in place of Django's existing `HttpRequest` and `HttpResponse` classes. Doing so allows logic such as parsing the incoming request or rendering the outgoing response to be supported transparently by the framework.
REST framework 2 includes `Request` and `Response` classes, than are used in
place of Django's existing `HttpRequest` and `HttpResponse` classes. Doing so
allows logic such as parsing the incoming request or rendering the outgoing
response to be supported transparently by the framework.
The `Request`/`Response` approach leads to a much cleaner API, less logic in the view itself, and a simple, obvious request-response cycle.
The `Request`/`Response` approach leads to a much cleaner API, less logic in
the view itself, and a simple, obvious request-response cycle.
REST framework 2 also allows you to work with both function-based and class-based views. For simple API views all you need is a single `@api_view` decorator, and you're good to go.
REST framework 2 also allows you to work with both function-based and
class-based views. For simple API views all you need is a single `@api_view`
decorator, and you're good to go.
## API Design
Pretty much every aspect of REST framework has been reworked, with the aim of ironing out some of the design flaws of the previous versions. Each of the components of REST framework are cleanly decoupled, and can be used independently of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions.
Pretty much every aspect of REST framework has been reworked, with the aim of
ironing out some of the design flaws of the previous versions. Each of the
components of REST framework are cleanly decoupled, and can be used
independently of each-other, and there are no monolithic resource classes,
overcomplicated mixin combinations, or opinionated serialization or URL routing
decisions.
## The Browsable API
Django REST framework's most unique feature is the way it is able to serve up both machine-readable representations, and a fully browsable HTML representation to the same endpoints.
Django REST framework's most unique feature is the way it is able to serve up
both machine-readable representations, and a fully browsable HTML
representation to the same endpoints.
Browsable Web APIs are easier to work with, visualize and debug, and generally makes it easier and more frictionless to inspect and work with.
Browsable Web APIs are easier to work with, visualize and debug, and generally
makes it easier and more frictionless to inspect and work with.
With REST framework 2, the browsable API gets a snazzy new bootstrap-based theme that looks great and is even nicer to work with.
With REST framework 2, the browsable API gets a snazzy new bootstrap-based
theme that looks great and is even nicer to work with.
There are also some functionality improvements - actions such as as `POST` and `DELETE` will only display if the user has the appropriate permissions.
There are also some functionality improvements - actions such as as `POST` and
`DELETE` will only display if the user has the appropriate permissions.
![Browsable API][image]
@ -76,17 +122,23 @@ There are also some functionality improvements - actions such as as `POST` and `
## Documentation
As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling.
As you can see the documentation for REST framework has been radically
improved. It gets a completely new style, using markdown for the documentation
source, and a bootstrap-based theme for the styling.
We're really pleased with how the docs style looks - it's simple and clean, is easy to navigate around, and we think it reads great.
We're really pleased with how the docs style looks - it's simple and clean, is
easy to navigate around, and we think it reads great.
## Summary
In short, we've engineered the hell outta this thing, and we're incredibly proud of the result.
In short, we've engineered the hell outta this thing, and we're incredibly
proud of the result.
If you're interested please take a browse around the documentation. [The tutorial][tut] is a great place to get started.
If you're interested please take a browse around the documentation. [The
tutorial][tut] is a great place to get started.
There's also a [live sandbox version of the tutorial API][sandbox] available for testing.
There's also a [live sandbox version of the tutorial API][sandbox] available
for testing.
[cite]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven#comment-724
[quote1]: https://twitter.com/kobutsu/status/261689665952833536

View File

@ -4,35 +4,55 @@
>
> &mdash; Mike Amundsen, [REST fest 2012 keynote][cite].
First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
First off, the disclaimer. The name "Django REST framework" was decided back
in early 2011 and was chosen simply to sure the project would be easily found
by developers. Throughout the documentation we try to use the more simple and
technically correct terminology of "Web APIs".
If you are serious about designing a Hypermedia API, you should look to resources outside of this documentation to help inform your design choices.
If you are serious about designing a Hypermedia API, you should look to
resources outside of this documentation to help inform your design choices.
The following fall into the "required reading" category.
* Roy Fielding's dissertation - [Architectural Styles and
the Design of Network-based Software Architectures][dissertation].
* Roy Fielding's "[REST APIs must be hypertext-driven][hypertext-driven]" blog post.
* Roy Fielding's dissertation - [Architectural Styles and the Design of
Network-based Software Architectures][dissertation].
* Roy Fielding's "[REST APIs must be hypertext-driven][hypertext-driven]" blog
post.
* Leonard Richardson & Mike Amundsen's [RESTful Web APIs][restful-web-apis].
* Mike Amundsen's [Building Hypermedia APIs with HTML5 and Node][building-hypermedia-apis].
* Mike Amundsen's [Building Hypermedia APIs with HTML5 and
Node][building-hypermedia-apis].
* Steve Klabnik's [Designing Hypermedia APIs][designing-hypermedia-apis].
* The [Richardson Maturity Model][maturitymodel].
For a more thorough background, check out Klabnik's [Hypermedia API reading list][readinglist].
For a more thorough background, check out Klabnik's [Hypermedia API reading
list][readinglist].
## Building Hypermedia APIs with REST framework
REST framework is an agnostic Web API toolkit. It does help guide you towards building well-connected APIs, and makes it easy to design appropriate media types, but it does not strictly enforce any particular design style.
REST framework is an agnostic Web API toolkit. It does help guide you towards
building well-connected APIs, and makes it easy to design appropriate media
types, but it does not strictly enforce any particular design style.
## What REST framework provides.
It is self evident that REST framework makes it possible to build Hypermedia APIs. The browsable API that it offers is built on HTML - the hypermedia language of the web.
It is self evident that REST framework makes it possible to build Hypermedia
APIs. The browsable API that it offers is built on HTML - the hypermedia
language of the web.
REST framework also includes [serialization] and [parser]/[renderer] components that make it easy to build appropriate media types, [hyperlinked relations][fields] for building well-connected systems, and great support for [content negotiation][conneg].
REST framework also includes [serialization] and [parser]/[renderer] components
that make it easy to build appropriate media types, [hyperlinked
relations][fields] for building well-connected systems, and great support for
[content negotiation][conneg].
## What REST framework doesn't provide.
What REST framework doesn't do is give you machine readable hypermedia formats such as [HAL][hal], [Collection+JSON][collection], [JSON API][json-api] or HTML [microformats] by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.
What REST framework doesn't do is give you machine readable hypermedia formats
such as [HAL][hal], [Collection+JSON][collection], [JSON API][json-api] or HTML
[microformats] by default, or the ability to auto-magically create fully
HATEOAS style APIs that include hypermedia-based form descriptions and
semantically labelled hyperlinks. Doing so would involve making opinionated
choices about API design that should really remain outside of the framework's
scope.
[cite]: http://vimeo.com/channels/restfest/page:2
[dissertation]: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

View File

@ -6,33 +6,52 @@
## About Third Party Packages
Third Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.
Third Party Packages allow developers to share code that extends the
functionality of Django REST framework, in order to support additional
use-cases.
We **support**, **encourage** and **strongly favor** the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.
We **support**, **encourage** and **strongly favor** the creation of Third
Party Packages to encapsulate new behavior rather than adding additional
functionality directly to Django REST Framework.
We aim to make creating third party packages as easy as possible, whilst keeping a **simple** and **well maintained** core API. By promoting third party packages we ensure that the responsibility for a package remains with its author. If a package proves suitably popular it can always be considered for inclusion into the core REST framework.
We aim to make creating third party packages as easy as possible, whilst
keeping a **simple** and **well maintained** core API. By promoting third party
packages we ensure that the responsibility for a package remains with its
author. If a package proves suitably popular it can always be considered for
inclusion into the core REST framework.
If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the [Mailing List][discussion-group].
If you have an idea for a new feature please consider how it may be packaged as
a Third Party Package. We're always happy to discuss ideas on the [Mailing
List][discussion-group].
## How to create a Third Party Package
### Creating your package
You can use [this cookiecutter template][cookiecutter] for creating reusable Django REST Framework packages quickly. Cookiecutter creates projects from project templates. While optional, this cookiecutter template includes best practices from Django REST framework and other packages, as well as a Travis CI configuration, Tox configuration, and a sane setup.py for easy PyPI registration/distribution.
You can use [this cookiecutter template][cookiecutter] for creating reusable
Django REST Framework packages quickly. Cookiecutter creates projects from
project templates. While optional, this cookiecutter template includes best
practices from Django REST framework and other packages, as well as a Travis CI
configuration, Tox configuration, and a sane setup.py for easy PyPI
registration/distribution.
Note: Let us know if you have an alternate cookiecuter package so we can also link to it.
Note: Let us know if you have an alternate cookiecuter package so we can also
link to it.
#### Running the initial cookiecutter command
To run the initial cookiecutter command, you'll first need to install the Python `cookiecutter` package.
To run the initial cookiecutter command, you'll first need to install the
Python `cookiecutter` package.
$ pip install cookiecutter
Once `cookiecutter` is installed just run the following to create a new project.
Once `cookiecutter` is installed just run the following to create a new
project.
$ cookiecutter gh:jpadilla/cookiecutter-django-rest-framework
You'll be prompted for some questions, answer them, then it'll create your Python package in the current working directory based on those values.
You'll be prompted for some questions, answer them, then it'll create your
Python package in the current working directory based on those values.
full_name (default is "Your full name here")? Johnny Appleseed
email (default is "you@example.com")? jappleseed@example.com
@ -46,20 +65,29 @@ You'll be prompted for some questions, answer them, then it'll create your Pytho
#### Getting it onto GitHub
To put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository [here][new-repo]. If you need help, check out the [Create A Repo][create-a-repo] article on GitHub.
To put your project up on GitHub, you'll need a repository for it to live in.
You can create a new repository [here][new-repo]. If you need help, check out
the [Create A Repo][create-a-repo] article on GitHub.
#### Adding to Travis CI
We recommend using [Travis CI][travis-ci], a hosted continuous integration service which integrates well with GitHub and is free for public repositories.
We recommend using [Travis CI][travis-ci], a hosted continuous integration
service which integrates well with GitHub and is free for public repositories.
To get started with Travis CI, [sign in][travis-ci] with your GitHub account. Once you're signed in, go to your [profile page][travis-profile] and enable the service hook for the repository you want.
To get started with Travis CI, [sign in][travis-ci] with your GitHub account.
Once you're signed in, go to your [profile page][travis-profile] and enable the
service hook for the repository you want.
If you use the cookiecutter template, your project will already contain a `.travis.yml` file which Travis CI will use to build your project and run tests. By default, builds are triggered everytime you push to your repository or create Pull Request.
If you use the cookiecutter template, your project will already contain a
`.travis.yml` file which Travis CI will use to build your project and run
tests. By default, builds are triggered everytime you push to your repository
or create Pull Request.
#### Uploading to PyPI
Once you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via `pip`.
Once you've got at least a prototype working and tests running, you should
publish it on PyPI to allow others to install it via `pip`.
You must [register][pypi-register] an account before publishing to PyPI.
@ -69,7 +97,8 @@ To register your package on PyPI run the following command.
If this is the first time publishing to PyPI, you'll be prompted to login.
Note: Before publishing you'll need to make sure you have the latest pip that supports `wheel` as well as install the `wheel` package.
Note: Before publishing you'll need to make sure you have the latest pip that
supports `wheel` as well as install the `wheel` package.
$ pip install --upgrade pip
$ pip install wheel
@ -81,7 +110,8 @@ After this, every time you want to release a new version on PyPI just run the fo
git tag -a {0} -m 'version 0.1.0'
git push --tags
After releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release.
After releasing a new version to PyPI, it's always a good idea to tag the
version and make available as a GitHub Release.
We recommend to follow [Semantic Versioning][semver] for your package's versions.
@ -89,7 +119,10 @@ We recommend to follow [Semantic Versioning][semver] for your package's versions
#### Version requirements
The cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, `tox.ini`, `.travis.yml`, and `setup.py` to match the set of versions you wish to support.
The cookiecutter template assumes a set of supported versions will be provided
for Python and Django. Make sure you correctly update your requirements, docs,
`tox.ini`, `.travis.yml`, and `setup.py` to match the set of versions
you wish to support.
#### Tests
@ -131,7 +164,9 @@ Shorter form to run the tests for a given test method.
$ ./runtests.py test_this_method
To run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using `tox`. [Tox][tox-docs] is a generic virtualenv management and test command line tool.
To run your tests against multiple versions of Python as different versions of
requirements such as Django we recommend using `tox`. [Tox][tox-docs] is a
generic virtualenv management and test command line tool.
First, install `tox` globally.
@ -145,13 +180,18 @@ To run a particular `tox` environment:
$ tox -e envlist
`envlist` is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run:
`envlist` is a comma-separated value to that specifies the environments to run
tests against. To view a list of all possible test environments, run:
$ tox -l
#### Version compatibility
Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a `compat.py` module, and should provide a single common interface that the rest of the codebase can use.
Sometimes, in order to ensure your code works on various different versions of
Django, Python or third party libraries, you'll need to run slightly different
code depending on the environment. Any code that branches in this way should be
isolated into a `compat.py` module, and should provide a single common
interface that the rest of the codebase can use.
Check out Django REST framework's [compat.py][drf-compat] for an example.
@ -165,7 +205,12 @@ We suggest adding your package to the [REST Framework][rest-framework-grid] grid
#### Adding to the Django REST framework docs
Create a [Pull Request][drf-create-pr] or [Issue][drf-create-issue] on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under **Third party packages** of the API Guide section that best applies, like [Authentication][authentication] or [Permissions][permissions]. You can also link your package under the [Third Party Resources][third-party-resources] section.
Create a [Pull Request][drf-create-pr] or [Issue][drf-create-issue] on GitHub,
and we'll add a link to it from the main REST framework documentation. You can
add your package under **Third party packages** of the API Guide section that
best applies, like [Authentication][authentication] or
[Permissions][permissions]. You can also link your package under the [Third
Party Resources][third-party-resources] section.
#### Announce on the discussion group.
@ -173,11 +218,14 @@ You can also let others know about your package through the [discussion group][d
## Existing Third Party Packages
Django REST Framework has a growing community of developers, packages, and resources.
Django REST Framework has a growing community of developers, packages, and
resources.
Check out a grid detailing all the packages and ecosystem around Django REST Framework at [Django Packages][rest-framework-grid].
Check out a grid detailing all the packages and ecosystem around Django REST
Framework at [Django Packages][rest-framework-grid].
To submit new content, [open an issue][drf-create-issue] or [create a pull request][drf-create-pr].
To submit new content, [open an issue][drf-create-issue] or [create a pull
request][drf-create-pr].
### Authentication

View File

@ -4,9 +4,15 @@
# Writable nested serializers
Although flat data structures serve to properly delineate between the individual entities in your service, there are cases where it may be more appropriate or convenient to use nested data structures.
Although flat data structures serve to properly delineate between the
individual entities in your service, there are cases where it may be more
appropriate or convenient to use nested data structures.
Nested data structures are easy enough to work with if they're read-only - simply nest your serializer classes and you're good to go. However, there are a few more subtleties to using writable nested serializers, due to the dependencies between the various model instances, and the need to save or delete multiple instances in a single action.
Nested data structures are easy enough to work with if they're read-only -
simply nest your serializer classes and you're good to go. However, there are
a few more subtleties to using writable nested serializers, due to the
dependencies between the various model instances, and the need to save or
delete multiple instances in a single action.
## One-to-many data structures

View File

@ -2,19 +2,29 @@
## Introduction
This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.
This tutorial will cover creating a simple pastebin code highlighting Web API.
Along the way it will introduce the various components that make up REST
framework, and give you a comprehensive understanding of how everything fits
together.
The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the [quickstart] documentation instead.
The tutorial is fairly in-depth, so you should probably get a cookie and a cup
of your favorite brew before getting started. If you just want a quick
overview, you should head over to the [quickstart] documentation instead.
---
**Note**: The code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. The completed implementation is also online as a sandbox version for testing, [available here][sandbox].
**Note**: The code for this tutorial is available in the
[tomchristie/rest-framework-tutorial][repo] repository on GitHub. The
completed implementation is also online as a sandbox version for testing,
[available here][sandbox].
---
## Setting up a new environment
Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.
Before we do anything else we'll create a new virtual environment, using
[virtualenv]. This will make sure our package configuration is kept nicely
isolated from any other projects we're working on.
virtualenv env
source env/bin/activate
@ -25,7 +35,9 @@ Now that we're inside a virtualenv environment, we can install our package requi
pip install djangorestframework
pip install pygments # We'll be using this for the code highlighting
**Note:** To exit the virtualenv environment at any time, just type `deactivate`. For more information see the [virtualenv documentation][virtualenv].
**Note:** To exit the virtualenv environment at any time, just type
`deactivate`. For more information see the [virtualenv
documentation][virtualenv].
## Getting started
@ -40,7 +52,8 @@ Once that's done we can create an app that we'll use to create a simple Web API.
python manage.py startapp snippets
We'll need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. Let's edit the `tutorial/settings.py` file:
We'll need to add our new `snippets` app and the `rest_framework` app to
`INSTALLED_APPS`. Let's edit the `tutorial/settings.py` file:
INSTALLED_APPS = (
...
@ -52,7 +65,11 @@ Okay, we're ready to roll.
## Creating a model to work with
For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets/models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
For the purposes of this tutorial we're going to start by creating a simple
`Snippet` model that is used to store code snippets. Go ahead and edit the
`snippets/models.py` file. Note: Good programming practices include comments.
Although you will find them in our repository version of this tutorial code, we
have omitted them here to focus on the code itself.
from django.db import models
from pygments.lexers import get_all_lexers
@ -81,7 +98,11 @@ We'll also need to create an initial migration for our snippet model, and sync t
## Creating a Serializer class
The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as `json`. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the `snippets` directory named `serializers.py` and add the following.
The first thing we need to get started on our Web API is to provide a way of
serializing and deserializing the snippet instances into representations such
as `json`. We can do this by declaring serializers that work very similar to
Django's forms. Create a file in the `snippets` directory named
`serializers.py` and add the following.
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
@ -113,21 +134,34 @@ The first thing we need to get started on our Web API is to provide a way of ser
instance.save()
return instance
The first part of the serializer class defines the fields that get serialized/deserialized. The `create()` and `update()` methods define how fully fledged instances are created or modified when calling `serializer.save()`
The first part of the serializer class defines the fields that get
serialized/deserialized. The `create()` and `update()` methods define how
fully fledged instances are created or modified when calling
`serializer.save()`
A serializer class is very similar to a Django `Form` class, and includes similar validation flags on the various fields, such as `required`, `max_length` and `default`.
A serializer class is very similar to a Django `Form` class, and includes
similar validation flags on the various fields, such as `required`,
`max_length` and `default`.
The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The `{'base_template': 'textarea.html'}` flag above is equivalent to using `widget=widgets.Textarea` on a Django `Form` class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.
The field flags can also control how the serializer should be displayed in
certain circumstances, such as when rendering to HTML. The `{'base_template':
'textarea.html'}` flag above is equivalent to using `widget=widgets.Textarea`
on a Django `Form` class. This is particularly useful for controlling how the
browsable API should be displayed, as we'll see later in the tutorial.
We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit.
We can actually also save ourselves some time by using the `ModelSerializer`
class, as we'll see later, but for now we'll keep our serializer definition
explicit.
## Working with Serializers
Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.
Before we go any further we'll familiarize ourselves with using our new
Serializer class. Let's drop into the Django shell.
python manage.py shell
Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.
Okay, once we've got a few imports out of the way, let's create a couple of
code snippets to work with.
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
@ -140,19 +174,22 @@ Okay, once we've got a few imports out of the way, let's create a couple of code
snippet = Snippet(code='print "hello, world"\n')
snippet.save()
We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.
We've now got a few snippet instances to play with. Let's take a look at
serializing one of those instances.
serializer = SnippetSerializer(snippet)
serializer.data
# {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`.
At this point we've translated the model instance into Python native datatypes.
To finalize the serialization process we render the data into `json`.
content = JSONRenderer().render(serializer.data)
content
# '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
Deserialization is similar. First we parse a stream into Python native datatypes...
Deserialization is similar. First we parse a stream into Python native
datatypes...
from django.utils.six import BytesIO
@ -169,9 +206,11 @@ Deserialization is similar. First we parse a stream into Python native datatype
serializer.save()
# <Snippet: Snippet object>
Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.
Notice how similar the API is to working with forms. The similarity should
become even more apparent when we start writing views that use our serializer.
We can also serialize querysets instead of model instances. To do so we simply add a `many=True` flag to the serializer arguments.
We can also serialize querysets instead of model instances. To do so we simply
add a `many=True` flag to the serializer arguments.
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data
@ -179,9 +218,13 @@ We can also serialize querysets instead of model instances. To do so we simply
## Using ModelSerializers
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise.
Our `SnippetSerializer` class is replicating a lot of information that's also
contained in the `Snippet` model. It would be nice if we could keep our code a
bit more concise.
In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes.
In the same way that Django provides both `Form` classes and `ModelForm`
classes, REST framework includes both `Serializer` classes, and
`ModelSerializer` classes.
Let's look at refactoring our serializer using the `ModelSerializer` class.
Open the file `snippets/serializers.py` again, and replace the `SnippetSerializer` class with the following.
@ -191,7 +234,9 @@ Open the file `snippets/serializers.py` again, and replace the `SnippetSerialize
model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with `python manage.py shell`, then try the following:
One nice property that serializers have is that you can inspect all the fields
in a serializer instance, by printing its representation. Open the Django shell
with `python manage.py shell`, then try the following:
from snippets.serializers import SnippetSerializer
serializer = SnippetSerializer()
@ -204,7 +249,9 @@ One nice property that serializers have is that you can inspect all the fields i
# language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...
# style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...
It's important to remember that `ModelSerializer` classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes:
It's important to remember that `ModelSerializer` classes don't do anything
particularly magical, they are simply a shortcut for creating serializer
classes:
* An automatically determined set of fields.
* Simple default implementations for the `create()` and `update()` methods.
@ -254,9 +301,13 @@ The root of our API is going to be a view that supports listing all the existing
return JSONResponse(serializer.data, status=201)
return JSONResponse(serializer.errors, status=400)
Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as `csrf_exempt`. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.
Note that because we want to be able to POST to this view from clients that
won't have a CSRF token we need to mark the view as `csrf_exempt`. This isn't
something that you'd normally want to do, and REST framework views actually use
more sensible behavior than this, but it'll do for our purposes right now.
We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.
We'll also need a view which corresponds to an individual snippet, and can be
used to retrieve, update or delete the snippet.
@csrf_exempt
def snippet_detail(request, pk):
@ -302,7 +353,10 @@ We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to inc
url(r'^', include('snippets.urls')),
]
It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.
It's worth noting that there are a couple of edge cases we're not dealing with
properly at the moment. If we send malformed `json`, or if a request is made
with a method that the view doesn't handle, then we'll end up with a 500
"server error" response. Still, this'll do for now.
## Testing our first attempt at a Web API
@ -325,7 +379,8 @@ Quit out of the shell...
In another terminal window, we can test the server.
We can test our API using [curl][curl] or [httpie][httpie]. Httpie is a user friendly http client that's written in Python. Let's install that.
We can test our API using [curl][curl] or [httpie][httpie]. Httpie is a user
friendly http client that's written in Python. Let's install that.
You can install httpie using pip:
@ -375,11 +430,15 @@ Similarly, you can have the same json displayed by visiting these URLs in a web
## Where are we now
We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views.
We're doing okay so far, we've got a serialization API that feels pretty
similar to Django's Forms API, and some regular Django views.
Our API views don't do anything particularly special at the moment, beyond serving `json` responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.
Our API views don't do anything particularly special at the moment, beyond
serving `json` responses, and there are some error handling edge cases we'd
still like to clean up, but it's a functioning Web API.
We'll see how we can start to improve things in [part 2 of the tutorial][tut-2].
We'll see how we can start to improve things in [part 2 of the
tutorial][tut-2].
[quickstart]: quickstart.md
[repo]: https://github.com/tomchristie/rest-framework-tutorial

View File

@ -5,20 +5,29 @@ Let's introduce a couple of essential building blocks.
## Request objects
REST framework introduces a `Request` object that extends the regular `HttpRequest`, and provides more flexible request parsing. The core functionality of the `Request` object is the `request.data` attribute, which is similar to `request.POST`, but more useful for working with Web APIs.
REST framework introduces a `Request` object that extends the regular
`HttpRequest`, and provides more flexible request parsing. The core
functionality of the `Request` object is the `request.data` attribute, which is
similar to `request.POST`, but more useful for working with Web APIs.
request.POST # Only handles form data. Only works for 'POST' method.
request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
## Response objects
REST framework also introduces a `Response` object, which is a type of `TemplateResponse` that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.
REST framework also introduces a `Response` object, which is a type of
`TemplateResponse` that takes unrendered content and uses content negotiation
to determine the correct content type to return to the client.
return Response(data) # Renders to content type as requested by the client.
## Status codes
Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as `HTTP_400_BAD_REQUEST` in the `status` module. It's a good idea to use these throughout rather than using numeric identifiers.
Using numeric HTTP status codes in your views doesn't always make for obvious
reading, and it's easy to not notice if you get an error code wrong. REST
framework provides more explicit identifiers for each status code, such as
`HTTP_400_BAD_REQUEST` in the `status` module. It's a good idea to use these
throughout rather than using numeric identifiers.
## Wrapping API views
@ -27,15 +36,20 @@ REST framework provides two wrappers you can use to write API views.
1. The `@api_view` decorator for working with function based views.
2. The `APIView` class for working with class-based views.
These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
These wrappers provide a few bits of functionality such as making sure you
receive `Request` instances in your view, and adding context to `Response`
objects so that content negotiation can be performed.
The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.data` with malformed input.
The wrappers also provide behaviour such as returning `405 Method Not Allowed`
responses when appropriate, and handling any `ParseError` exception that occurs
when accessing `request.data` with malformed input.
## Pulling it all together
Okay, let's go ahead and start using these new components to write a few views.
We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly.
We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and
delete that. Once that's done we can start refactoring our views slightly.
from rest_framework import status
from rest_framework.decorators import api_view
@ -61,7 +75,10 @@ We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and de
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.
Our instance view is an improvement over the previous example. It's a little
more concise, and the code now feels very similar to if we were working with
the Forms API. We're also using named status codes, which makes the response
meanings more obvious.
Here is the view for an individual snippet, in the `views.py` module.
@ -90,13 +107,22 @@ Here is the view for an individual snippet, in the `views.py` module.
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
This should all feel very familiar - it is not a lot different from working with regular Django views.
This should all feel very familiar - it is not a lot different from working
with regular Django views.
Notice that we're no longer explicitly tying our requests or responses to a given content type. `request.data` can handle incoming `json` requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.
Notice that we're no longer explicitly tying our requests or responses to a
given content type. `request.data` can handle incoming `json` requests, but it
can also handle other formats. Similarly we're returning response objects with
data, but allowing REST framework to render the response into the correct
content type for us.
## Adding optional format suffixes to our URLs
To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [http://example.com/api/items/4.json][json-url].
To take advantage of the fact that our responses are no longer hardwired to a
single content type let's add support for format suffixes to our API endpoints.
Using format suffixes gives us URLs that explicitly refer to a given format,
and means our API will be able to handle URLs such as
[http://example.com/api/items/4.json][json-url].
Start by adding a `format` keyword argument to both of the views, like so.
@ -106,7 +132,8 @@ and
def snippet_detail(request, pk, format=None):
Now update the `urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs.
Now update the `urls.py` file slightly, to append a set of
`format_suffix_patterns` in addition to the existing URLs.
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
@ -119,11 +146,14 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter
urlpatterns = format_suffix_patterns(urlpatterns)
We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.
We don't necessarily need to add these extra url patterns in, but it gives us a
simple, clean way of referring to a specific format.
## How's it looking?
Go ahead and test the API from the command line, as we did in [tutorial part 1][tut-1]. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.
Go ahead and test the API from the command line, as we did in [tutorial part
1][tut-1]. Everything is working pretty similarly, although we've got some
nicer error handling if we send invalid requests.
We can get a list of all of the snippets, as before.
@ -186,21 +216,29 @@ Similarly, we can control the format of the request that we send, using the `Con
"style": "friendly"
}
If you add a `--debug` switch to the `http` requests above, you will be able to see the request type in request headers.
If you add a `--debug` switch to the `http` requests above, you will be able to
see the request type in request headers.
Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver].
### Browsability
Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.
Because the API chooses the content type of the response based on the client
request, it will, by default, return an HTML-formatted representation of the
resource when that resource is requested by a web browser. This allows for the
API to return a fully web-browsable HTML representation.
Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.
Having a web-browsable API is a huge usability win, and makes developing and
using your API much easier. It also dramatically lowers the barrier-to-entry
for other developers wanting to inspect and work with your API.
See the [browsable api][browsable-api] topic for more information about the browsable API feature and how to customize it.
See the [browsable api][browsable-api] topic for more information about the
browsable API feature and how to customize it.
## What's next?
In [tutorial part 3][tut-3], we'll start using class-based views, and see how generic views reduce the amount of code we need to write.
In [tutorial part 3][tut-3], we'll start using class-based views, and see how
generic views reduce the amount of code we need to write.
[json-url]: http://example.com/api/items/4.json
[devserver]: http://127.0.0.1:8000/snippets/

View File

@ -1,10 +1,13 @@
# Tutorial 3: Class-based Views
We can also write our API views using class-based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code [DRY][dry].
We can also write our API views using class-based views, rather than function
based views. As we'll see this is a powerful pattern that allows us to reuse
common functionality, and helps us keep our code [DRY][dry].
## Rewriting our API using class-based views
We'll start by rewriting the root view as a class-based view. All this involves is a little bit of refactoring of `views.py`.
We'll start by rewriting the root view as a class-based view. All this
involves is a little bit of refactoring of `views.py`.
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
@ -30,7 +33,9 @@ We'll start by rewriting the root view as a class-based view. All this involves
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view in `views.py`.
So far, so good. It looks pretty similar to the previous case, but we've got
better separation between the different HTTP methods. We'll also need to
update the instance view in `views.py`.
class SnippetDetail(APIView):
"""
@ -79,11 +84,15 @@ Okay, we're done. If you run the development server everything should be workin
## Using mixins
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behaviour.
One of the big wins of using class-based views is that it allows us to easily
compose reusable bits of behaviour.
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.
The create/retrieve/update/delete operations that we've been using so far are
going to be pretty similar for any model-backed API views we create. Those
bits of common behaviour are implemented in REST framework's mixin classes.
Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again.
Let's take a look at how we can compose the views by using the mixin classes.
Here's our `views.py` module again.
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
@ -102,9 +111,13 @@ Let's take a look at how we can compose the views by using the mixin classes. H
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
We'll take a moment to examine exactly what's happening here. We're building our view using `GenericAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`.
We'll take a moment to examine exactly what's happening here. We're building
our view using `GenericAPIView`, and adding in `ListModelMixin` and
`CreateModelMixin`.
The base class provides the core functionality, and the mixin classes provide the `.list()` and `.create()` actions. We're then explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far.
The base class provides the core functionality, and the mixin classes provide
the `.list()` and `.create()` actions. We're then explicitly binding the `get`
and `post` methods to the appropriate actions. Simple enough stuff so far.
class SnippetDetail(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
@ -122,11 +135,16 @@ The base class provides the core functionality, and the mixin classes provide th
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
Pretty similar. Again we're using the `GenericAPIView` class to provide the core functionality, and adding in mixins to provide the `.retrieve()`, `.update()` and `.destroy()` actions.
Pretty similar. Again we're using the `GenericAPIView` class to provide the
core functionality, and adding in mixins to provide the `.retrieve()`,
`.update()` and `.destroy()` actions.
## Using generic class-based views
Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our `views.py` module even more.
Using the mixin classes we've rewritten the views to use slightly less code
than before, but we can go one step further. REST framework provides a set of
already mixed-in generic views that we can use to trim down our `views.py`
module even more.
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
@ -142,9 +160,11 @@ Using the mixin classes we've rewritten the views to use slightly less code than
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.
Wow, that's pretty concise. We've gotten a huge amount for free, and our code
looks like good, clean, idiomatic Django.
Next we'll move onto [part 4 of the tutorial][tut-4], where we'll take a look at how we can deal with authentication and permissions for our API.
Next we'll move onto [part 4 of the tutorial][tut-4], where we'll take a look
at how we can deal with authentication and permissions for our API.
[dry]: http://en.wikipedia.org/wiki/Don't_repeat_yourself
[tut-4]: 4-authentication-and-permissions.md

View File

@ -1,6 +1,8 @@
# Tutorial 4: Authentication & Permissions
Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:
Currently our API doesn't have any restrictions on who can edit or delete code
snippets. We'd like to have some more advanced behavior in order to make sure
that:
* Code snippets are always associated with a creator.
* Only authenticated users may create snippets.
@ -9,15 +11,18 @@ Currently our API doesn't have any restrictions on who can edit or delete code s
## Adding information to our model
We're going to make a couple of changes to our `Snippet` model class.
First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.
We're going to make a couple of changes to our `Snippet` model class. First,
let's add a couple of fields. One of those fields will be used to represent
the user who created the code snippet. The other field will be used to store
the highlighted HTML representation of the code.
Add the following two fields to the `Snippet` model in `models.py`.
owner = models.ForeignKey('auth.User', related_name='snippets')
highlighted = models.TextField()
We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the `pygments` code highlighting library.
We'd also need to make sure that when the model is saved, that we populate the
highlighted field, using the `pygments` code highlighting library.
We'll need some extra imports:
@ -40,21 +45,25 @@ And now we can add a `.save()` method to our model class:
self.highlighted = highlight(self.code, lexer, formatter)
super(Snippet, self).save(*args, **kwargs)
When that's all done we'll need to update our database tables.
Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.
When that's all done we'll need to update our database tables. Normally we'd
create a database migration in order to do that, but for the purposes of this
tutorial, let's just delete the database and start again.
rm -f tmp.db db.sqlite3
rm -r snippets/migrations
python manage.py makemigrations snippets
python manage.py migrate
You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the `createsuperuser` command.
You might also want to create a few different users, to use for testing the
API. The quickest way to do this will be with the `createsuperuser` command.
python manage.py createsuperuser
## Adding endpoints for our User models
Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In `serializers.py` add:
Now that we've got some users to work with, we'd better add representations of
those users to our API. Creating a new serializer is easy. In `serializers.py`
add:
from django.contrib.auth.models import User
@ -65,9 +74,13 @@ Now that we've got some users to work with, we'd better add representations of t
model = User
fields = ('id', 'username', 'snippets')
Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we needed to add an explicit field for it.
Because `'snippets'` is a *reverse* relationship on the User model, it will not
be included by default when using the `ModelSerializer` class, so we needed to
add an explicit field for it.
We'll also add a couple of views to `views.py`. We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class-based views.
We'll also add a couple of views to `views.py`. We'd like to just use
read-only views for the user representations, so we'll use the `ListAPIView`
and `RetrieveAPIView` generic class-based views.
from django.contrib.auth.models import User
@ -85,41 +98,64 @@ Make sure to also import the `UserSerializer` class
from snippets.serializers import UserSerializer
Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `urls.py`.
Finally we need to add those views into the API, by referencing them from the
URL conf. Add the following to the patterns in `urls.py`.
url(r'^users/$', views.UserList.as_view()),
url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
## Associating Snippets with Users
Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.
Right now, if we created a code snippet, there'd be no way of associating the
user that created the snippet, with the snippet instance. The user isn't sent
as part of the serialized representation, but is instead a property of the
incoming request.
The way we deal with that is by overriding a `.perform_create()` method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL.
The way we deal with that is by overriding a `.perform_create()` method on our
snippet views, that allows us to modify how the instance save is managed, and
handle any information that is implicit in the incoming request or requested
URL.
On the `SnippetList` view class, add the following method:
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
The `create()` method of our serializer will now be passed an additional `'owner'` field, along with the validated data from the request.
The `create()` method of our serializer will now be passed an additional
`'owner'` field, along with the validated data from the request.
## Updating our serializer
Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition in `serializers.py`:
Now that snippets are associated with the user that created them, let's update
our `SnippetSerializer` to reflect that. Add the following field to the
serializer definition in `serializers.py`:
owner = serializers.ReadOnlyField(source='owner.username')
**Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class.
**Note**: Make sure you also add `'owner',` to the list of fields in the inner
`Meta` class.
This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.
This field is doing something quite interesting. The `source` argument
controls which attribute is used to populate a field, and can point at any
attribute on the serialized instance. It can also take the dotted notation
shown above, in which case it will traverse the given attributes, in a similar
way as it is used with Django's template language.
The field we've added is the untyped `ReadOnlyField` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `ReadOnlyField` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also used `CharField(read_only=True)` here.
The field we've added is the untyped `ReadOnlyField` class, in contrast to the
other typed fields, such as `CharField`, `BooleanField` etc... The untyped
`ReadOnlyField` is always read-only, and will be used for serialized
representations, but will not be used for updating model instances when they
are deserialized. We could have also used `CharField(read_only=True)` here.
## Adding required permissions to views
Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.
Now that code snippets are associated with users, we want to make sure that
only authenticated users are able to create, update and delete code snippets.
REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is `IsAuthenticatedOrReadOnly`, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.
REST framework includes a number of permission classes that we can use to
restrict who can access a given view. In this case the one we're looking for
is `IsAuthenticatedOrReadOnly`, which will ensure that authenticated requests
get read-write access, and unauthenticated requests get read-only access.
First add the following import in the views module
@ -131,30 +167,42 @@ Then, add the following property to **both** the `SnippetList` and `SnippetDetai
## Adding login to the Browsable API
If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
If you open a browser and navigate to the browsable API at the moment, you'll
find that you're no longer able to create new code snippets. In order to do so
we'd need to be able to login as a user.
We can add a login view for use with the browsable API, by editing the URLconf in our project-level `urls.py` file.
We can add a login view for use with the browsable API, by editing the URLconf
in our project-level `urls.py` file.
Add the following import at the top of the file:
from django.conf.urls import include
And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
And, at the end of the file, add a pattern to include the login and logout
views for the browsable API.
urlpatterns += [
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
]
The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the `'rest_framework'` namespace. In Django 1.9+, REST framework will set the namespace, so you may leave it out.
The `r'^api-auth/'` part of pattern can actually be whatever URL you want to
use. The only restriction is that the included urls must use the
`'rest_framework'` namespace. In Django 1.9+, REST framework will set the
namespace, so you may leave it out.
Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.
Now if you open up the browser again and refresh the page you'll see a 'Login'
link in the top right of the page. If you log in as one of the users you
created earlier, you'll be able to create code snippets again.
Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet pks that are associated with each user, in each user's 'snippets' field.
Once you've created a few code snippets, navigate to the '/users/' endpoint,
and notice that the representation includes a list of the snippet pks that are
associated with each user, in each user's 'snippets' field.
## Object level permissions
Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.
Really we'd like all code snippets to be visible to anyone, but also make sure
that only the user that created a code snippet is able to update or delete it.
To do that we're going to need to create a custom permission.
@ -177,7 +225,8 @@ In the snippets app, create a new file, `permissions.py`
# Write permissions are only allowed to the owner of the snippet.
return obj.owner == request.user
Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` view class:
Now we can add that custom permission to our snippet instance endpoint, by
editing the `permission_classes` property on the `SnippetDetail` view class:
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
@ -186,15 +235,22 @@ Make sure to also import the `IsOwnerOrReadOnly` class.
from snippets.permissions import IsOwnerOrReadOnly
Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.
Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions
only appear on a snippet instance endpoint if you're logged in as the same user
that created the code snippet.
## Authenticating with the API
Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any [authentication classes][authentication], so the defaults are currently applied, which are `SessionAuthentication` and `BasicAuthentication`.
Because we now have a set of permissions on the API, we need to authenticate
our requests to it if we want to edit any snippets. We haven't set up any
[authentication classes][authentication], so the defaults are currently
applied, which are `SessionAuthentication` and `BasicAuthentication`.
When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.
When we interact with the API through the web browser, we can login, and the
browser session will then provide the required authentication for the requests.
If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.
If we're interacting with the API programmatically we need to explicitly
provide the authentication credentials on each request.
If we try to create a snippet without authenticating, we'll get an error:
@ -204,7 +260,8 @@ If we try to create a snippet without authenticating, we'll get an error:
"detail": "Authentication credentials were not provided."
}
We can make a successful request by including the username and password of one of the users we created earlier.
We can make a successful request by including the username and password of one
of the users we created earlier.
http -a tom:password123 POST http://127.0.0.1:8000/snippets/ code="print 789"
@ -220,9 +277,14 @@ We can make a successful request by including the username and password of one o
## Summary
We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.
We've now got a fairly fine-grained set of permissions on our Web API, and end
points for users of the system and for the code snippets that they have
created.
In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
In [part 5][tut-5] of the tutorial we'll look at how we can tie everything
together by creating an HTML endpoint for our highlighted snippets, and improve
the cohesion of our API by using hyperlinking for the relationships within the
system.
[authentication]: ../api-guide/authentication.md
[tut-5]: 5-relationships-and-hyperlinked-apis.md

View File

@ -1,10 +1,15 @@
# Tutorial 5: Relationships & Hyperlinked APIs
At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.
At the moment relationships within our API are represented by using primary
keys. In this part of the tutorial we'll improve the cohesion and
discoverability of our API, by instead using hyperlinking for relationships.
## Creating an endpoint for the root of our API
Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. In your `snippets/views.py` add:
Right now we have endpoints for 'snippets' and 'users', but we don't have a
single entry point to our API. To create one, we'll use a regular
function-based view and the `@api_view` decorator we introduced earlier. In
your `snippets/views.py` add:
from rest_framework.decorators import api_view
from rest_framework.response import Response
@ -18,17 +23,29 @@ Right now we have endpoints for 'snippets' and 'users', but we don't have a sing
'snippets': reverse('snippet-list', request=request, format=format)
})
Two things should be noticed here. First, we're using REST framework's `reverse` function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our `snippets/urls.py`.
Two things should be noticed here. First, we're using REST framework's
`reverse` function in order to return fully-qualified URLs; second, URL
patterns are identified by convenience names that we will declare later on in
our `snippets/urls.py`.
## Creating an endpoint for the highlighted snippets
The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.
The other obvious thing that's still missing from our pastebin API is the code
highlighting endpoints.
Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two styles of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint.
Unlike all our other API endpoints, we don't want to use JSON, but instead just
present an HTML representation. There are two styles of HTML renderer provided
by REST framework, one for dealing with HTML rendered using templates, the
other for dealing with pre-rendered HTML. The second renderer is the one we'd
like to use for this endpoint.
The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.
The other thing we need to consider when creating the code highlight view is
that there's no existing concrete generic view that we can use. We're not
returning an object instance, but instead a property of an object instance.
Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets/views.py` add:
Instead of using a concrete generic view, we'll use the base class for
representing instances, and create our own `.get()` method. In your
`snippets/views.py` add:
from rest_framework import renderers
from rest_framework.response import Response
@ -52,7 +69,9 @@ And then add a url pattern for the snippet highlights:
## Hyperlinking our API
Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:
Dealing with relationships between entities is one of the more challenging
aspects of Web API design. There are a number of different ways that we might
choose to represent a relationship:
* Using primary keys.
* Using hyperlinking between entities.
@ -61,11 +80,16 @@ Dealing with relationships between entities is one of the more challenging aspec
* Nesting the related entity inside the parent representation.
* Some other custom representation.
REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.
REST framework supports all of these styles, and can apply them across forward
or reverse relationships, or apply them across custom managers such as generic
foreign keys.
In this case we'd like to use a hyperlinked style between entities. In order to do so, we'll modify our serializers to extend `HyperlinkedModelSerializer` instead of the existing `ModelSerializer`.
In this case we'd like to use a hyperlinked style between entities. In order
to do so, we'll modify our serializers to extend `HyperlinkedModelSerializer`
instead of the existing `ModelSerializer`.
The `HyperlinkedModelSerializer` has the following differences from `ModelSerializer`:
The `HyperlinkedModelSerializer` has the following differences from
`ModelSerializer`:
* It does not include the `pk` field by default.
* It includes a `url` field, using `HyperlinkedIdentityField`.
@ -91,18 +115,26 @@ We can easily re-write our existing serializers to use hyperlinking. In your `sn
model = User
fields = ('url', 'pk', 'username', 'snippets')
Notice that we've also added a new `'highlight'` field. This field is of the same type as the `url` field, except that it points to the `'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url pattern.
Notice that we've also added a new `'highlight'` field. This field is of the
same type as the `url` field, except that it points to the
`'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url
pattern.
Because we've included format suffixed URLs such as `'.json'`, we also need to indicate on the `highlight` field that any format suffixed hyperlinks it returns should use the `'.html'` suffix.
Because we've included format suffixed URLs such as `'.json'`, we also need to
indicate on the `highlight` field that any format suffixed hyperlinks it
returns should use the `'.html'` suffix.
## Making sure our URL patterns are named
If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name.
If we're going to have a hyperlinked API, we need to make sure we name our URL
patterns. Let's take a look at which URL patterns we need to name.
* The root of our API refers to `'user-list'` and `'snippet-list'`.
* Our snippet serializer includes a field that refers to `'snippet-highlight'`.
* Our user serializer includes a field that refers to `'snippet-detail'`.
* Our snippet and user serializers include `'url'` fields that by default will refer to `'{model_name}-detail'`, which in this case will be `'snippet-detail'` and `'user-detail'`.
* Our snippet and user serializers include `'url'` fields that by default will
refer to `'{model_name}-detail'`, which in this case will be
`'snippet-detail'` and `'user-detail'`.
After adding all those names into our URLconf, our final `snippets/urls.py` file should look like this:
@ -138,24 +170,33 @@ After adding all those names into our URLconf, our final `snippets/urls.py` file
## Adding pagination
The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.
The list views for users and code snippets could end up returning quite a lot
of instances, so really we'd like to make sure we paginate the results, and
allow the API client to step through each of the individual pages.
We can change the default list style to use pagination, by modifying our `tutorial/settings.py` file slightly. Add the following setting:
We can change the default list style to use pagination, by modifying our
`tutorial/settings.py` file slightly. Add the following setting:
REST_FRAMEWORK = {
'PAGE_SIZE': 10
}
Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well separated from your other project settings.
Note that settings in REST framework are all namespaced into a single
dictionary setting, named 'REST_FRAMEWORK', which helps keep them well
separated from your other project settings.
We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.
We could also customize the pagination style if we needed too, but in this case
we'll just stick with the default.
## Browsing the API
If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.
If we open a browser and navigate to the browsable API, you'll find that you
can now work your way around the API simply by following links.
You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.
You'll also be able to see the 'highlight' links on the snippet instances, that
will take you to the highlighted code HTML representations.
In [part 6][tut-6] of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.
In [part 6][tut-6] of the tutorial we'll look at how we can use ViewSets and
Routers to reduce the amount of code we need to build our API.
[tut-6]: 6-viewsets-and-routers.md

View File

@ -1,16 +1,25 @@
# Tutorial 6: ViewSets & Routers
REST framework includes an abstraction for dealing with `ViewSets`, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.
REST framework includes an abstraction for dealing with `ViewSets`, that allows
the developer to concentrate on modeling the state and interactions of the API,
and leave the URL construction to be handled automatically, based on common
conventions.
`ViewSet` classes are almost the same thing as `View` classes, except that they provide operations such as `read`, or `update`, and not method handlers such as `get` or `put`.
`ViewSet` classes are almost the same thing as `View` classes, except that they
provide operations such as `read`, or `update`, and not method handlers such as
`get` or `put`.
A `ViewSet` class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a `Router` class which handles the complexities of defining the URL conf for you.
A `ViewSet` class is only bound to a set of method handlers at the last moment,
when it is instantiated into a set of views, typically by using a `Router`
class which handles the complexities of defining the URL conf for you.
## Refactoring to use ViewSets
Let's take our current set of views, and refactor them into view sets.
First of all let's refactor our `UserList` and `UserDetail` views into a single `UserViewSet`. We can remove the two views, and replace them with a single class:
First of all let's refactor our `UserList` and `UserDetail` views into a single
`UserViewSet`. We can remove the two views, and replace them with a single
class:
from rest_framework import viewsets
@ -21,9 +30,15 @@ First of all let's refactor our `UserList` and `UserDetail` views into a single
queryset = User.objects.all()
serializer_class = UserSerializer
Here we've used the `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations. We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.
Here we've used the `ReadOnlyModelViewSet` class to automatically provide the
default 'read-only' operations. We're still setting the `queryset` and
`serializer_class` attributes exactly as we did when we were using regular
views, but we no longer need to provide the same information to two separate
classes.
Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes. We can remove the three views, and again replace them with a single class.
Next we're going to replace the `SnippetList`, `SnippetDetail` and
`SnippetHighlight` view classes. We can remove the three views, and again
replace them with a single class.
from rest_framework.decorators import detail_route
@ -47,13 +62,20 @@ Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations.
This time we've used the `ModelViewSet` class in order to get the complete set
of default read and write operations.
Notice that we've also used the `@detail_route` decorator to create a custom action, named `highlight`. This decorator can be used to add any custom endpoints that don't fit into the standard `create`/`update`/`delete` style.
Notice that we've also used the `@detail_route` decorator to create a custom
action, named `highlight`. This decorator can be used to add any custom
endpoints that don't fit into the standard `create`/`update`/`delete` style.
Custom actions which use the `@detail_route` decorator will respond to `GET` requests. We can use the `methods` argument if we wanted an action that responded to `POST` requests.
Custom actions which use the `@detail_route` decorator will respond to `GET`
requests. We can use the `methods` argument if we wanted an action that
responded to `POST` requests.
The URLs for custom actions by default depend on the method name itself. If you want to change the way url should be constructed, you can include url_path as a decorator keyword argument.
The URLs for custom actions by default depend on the method name itself. If you
want to change the way url should be constructed, you can include url_path as a
decorator keyword argument.
## Binding ViewSets to URLs explicitly
@ -85,9 +107,11 @@ In the `urls.py` file we bind our `ViewSet` classes into a set of concrete views
'get': 'retrieve'
})
Notice how we're creating multiple views from each `ViewSet` class, by binding the http methods to the required action for each view.
Notice how we're creating multiple views from each `ViewSet` class, by binding
the http methods to the required action for each view.
Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.
Now that we've bound our resources into concrete views, we can register the
views with the URL conf as usual.
urlpatterns = format_suffix_patterns([
url(r'^$', api_root),
@ -100,7 +124,11 @@ Now that we've bound our resources into concrete views, we can register the view
## Using Routers
Because we're using `ViewSet` classes rather than `View` classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a `Router` class. All we need to do is register the appropriate view sets with a router, and let it do the rest.
Because we're using `ViewSet` classes rather than `View` classes, we actually
don't need to design the URL conf ourselves. The conventions for wiring up
resources into views and urls can be handled automatically, using a `Router`
class. All we need to do is register the appropriate view sets with a router,
and let it do the rest.
Here's our re-wired `urls.py` file.
@ -120,15 +148,25 @@ Here's our re-wired `urls.py` file.
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself.
Registering the viewsets with the router is similar to providing a urlpattern.
We include two arguments - the URL prefix for the views, and the viewset
itself.
The `DefaultRouter` class we're using also automatically creates the API root view for us, so we can now delete the `api_root` method from our `views` module.
The `DefaultRouter` class we're using also automatically creates the API root
view for us, so we can now delete the `api_root` method from our `views`
module.
## Trade-offs between views vs viewsets
Using viewsets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.
Using viewsets can be a really useful abstraction. It helps ensure that URL
conventions will be consistent across your API, minimizes the amount of code
you need to write, and allows you to concentrate on the interactions and
representations your API provides rather than the specifics of the URL conf.
That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function based views. Using viewsets is less explicit than building your views individually.
That doesn't mean it's always the right approach to take. There's a similar
set of trade-offs to consider as when using class-based views instead of
function based views. Using viewsets is less explicit than building your views
individually.
In [part 7][tut-7] of the tutorial we'll look at how we can add an API schema,
and interact with our API using a client library or command line tool.

View File

@ -195,15 +195,22 @@ client libraries you'll need to refer to the full documentation.
## Reviewing our work
With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browsable, includes a schema-driven client library, and comes complete with authentication, per-object permissions, and multiple renderer formats.
With an incredibly small amount of code, we've now got a complete pastebin Web
API, which is fully web browsable, includes a schema-driven client library, and
comes complete with authentication, per-object permissions, and multiple
renderer formats.
We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.
We've walked through each step of the design process, and seen how if we need
to customize anything we can gradually work our way down to simply using
regular Django views.
You can review the final [tutorial code][repo] on GitHub, or try out a live example in [the sandbox][sandbox].
You can review the final [tutorial code][repo] on GitHub, or try out a live
example in [the sandbox][sandbox].
## Onwards and upwards
We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here are a few places you can start:
We've reached the end of our tutorial. If you want to get more involved in the
REST framework project, here are a few places you can start:
* Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests.
* Join the [REST framework discussion group][group], and help build the community.

View File

@ -1,6 +1,7 @@
# Quickstart
We're going to create a simple API to allow admin users to view and edit the users and groups in the system.
We're going to create a simple API to allow admin users to view and edit the
users and groups in the system.
## Project setup
@ -28,15 +29,19 @@ Now sync your database for the first time:
python manage.py migrate
We'll also create an initial user named `admin` with a password of `password123`. We'll authenticate as that user later in our example.
We'll also create an initial user named `admin` with a password of
`password123`. We'll authenticate as that user later in our example.
python manage.py createsuperuser
Once you've set up a database and initial user created and ready to go, open up the app's directory and we'll get coding...
Once you've set up a database and initial user created and ready to go, open up
the app's directory and we'll get coding...
## Serializers
First up we're going to define some serializers. Let's create a new module named `tutorial/quickstart/serializers.py` that we'll use for our data representations.
First up we're going to define some serializers. Let's create a new module
named `tutorial/quickstart/serializers.py` that we'll use for our data
representations.
from django.contrib.auth.models import User, Group
from rest_framework import serializers
@ -53,7 +58,9 @@ First up we're going to define some serializers. Let's create a new module named
model = Group
fields = ('url', 'name')
Notice that we're using hyperlinked relations in this case, with `HyperlinkedModelSerializer`. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.
Notice that we're using hyperlinked relations in this case, with
`HyperlinkedModelSerializer`. You can also use primary key and various other
relationships, but hyperlinking is good RESTful design.
## Views
@ -79,9 +86,11 @@ Right, we'd better write some views then. Open `tutorial/quickstart/views.py` a
queryset = Group.objects.all()
serializer_class = GroupSerializer
Rather than write multiple views we're grouping together all the common behavior into classes called `ViewSets`.
Rather than write multiple views we're grouping together all the common
behavior into classes called `ViewSets`.
We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.
We can easily break these down into individual views if we need to, but using
viewsets keeps the view logic nicely organized as well as being very concise.
## URLs
@ -102,15 +111,22 @@ Okay, now let's wire up the API URLs. On to `tutorial/urls.py`...
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.
Because we're using viewsets instead of views, we can automatically generate
the URL conf for our API, by simply registering the viewsets with a router
class.
Again, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly.
Again, if we need more control over the API URLs we can simply drop down to
using regular class-based views, and writing the URL conf explicitly.
Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.
Finally, we're including default login and logout views for use with the
browsable API. That's optional, but useful if your API requires authentication
and you want to use the browsable API.
## Settings
We'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. The settings module will be in `tutorial/settings.py`
We'd also like to set a few global settings. We'd like to turn on pagination,
and we want our API to only be accessible to admin users. The settings module
will be in `tutorial/settings.py`
INSTALLED_APPS = (
...
@ -128,7 +144,8 @@ Okay, we're done.
## Testing our API
We're now ready to test the API we've built. Let's fire up the server from the command line.
We're now ready to test the API we've built. Let's fire up the server from the
command line.
python manage.py runserver
@ -186,11 +203,14 @@ Or directly through the browser, by going to the URL `http://127.0.0.1:8000/user
![Quick start image][image]
If you're working through the browser, make sure to login using the control in the top right corner.
If you're working through the browser, make sure to login using the control in
the top right corner.
Great, that was easy!
If you want to get a more in depth understanding of how REST framework fits together head on over to [the tutorial][tutorial], or start browsing the [API guide][guide].
If you want to get a more in depth understanding of how REST framework fits
together head on over to [the tutorial][tutorial], or start browsing the [API
guide][guide].
[readme-example-api]: ../#example
[image]: ../img/quickstart.png