Merge master

This commit is contained in:
Tom Christie 2013-05-05 18:12:35 +01:00
commit b70c9cc107
12 changed files with 38 additions and 33 deletions

View File

@ -57,7 +57,7 @@ Or, if you're using the `@api_view` decorator with function based views.
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 browseable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header. 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].
@ -167,7 +167,7 @@ See also: `TemplateHTMLRenderer`
## BrowsableAPIRenderer ## BrowsableAPIRenderer
Renders data into HTML for the Browseable API. This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page. Renders data into HTML for the Browsable API. This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.
**.media_type**: `text/html` **.media_type**: `text/html`

5
docs/api-guide/serializers.md Executable file → Normal file
View File

@ -59,14 +59,15 @@ We can now use `CommentSerializer` to serialize a comment, or list of comments.
At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`. At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`.
stream = JSONRenderer().render(data) json = JSONRenderer().render(serializer.data)
stream json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}' # '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
## Deserializing objects ## Deserializing objects
Deserialization is similar. First we parse a stream into python native datatypes... Deserialization is similar. First we parse a stream into python native datatypes...
stream = StringIO(json)
data = JSONParser().parse(stream) data = JSONParser().parse(stream)
...then we restore those native datatypes into a fully populated object instance. ...then we restore those native datatypes into a fully populated object instance.

View File

@ -9,7 +9,7 @@
# Django REST framework # Django REST framework
**Awesome web-browseable Web APIs.** **Awesome web-browsable Web APIs.**
Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs. Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs.
@ -23,7 +23,7 @@ Some reasons you might want to use REST framework:
There is a live example API for testing purposes, [available here][sandbox]. There is a live example API for testing purposes, [available here][sandbox].
**Below**: *Screenshot from the browseable API* **Below**: *Screenshot from the browsable API*
![Screenshot][image] ![Screenshot][image]
@ -36,7 +36,7 @@ REST framework requires the following:
The following packages are optional: The following packages are optional:
* [Markdown][markdown] (2.1.0+) - Markdown support for the browseable API. * [Markdown][markdown] (2.1.0+) - Markdown support for the browsable API.
* [PyYAML][yaml] (3.10+) - YAML content-type support. * [PyYAML][yaml] (3.10+) - YAML content-type support.
* [defusedxml][defusedxml] (0.3+) - XML content-type support. * [defusedxml][defusedxml] (0.3+) - XML content-type support.
* [django-filter][django-filter] (0.5.4+) - Filtering support. * [django-filter][django-filter] (0.5.4+) - Filtering support.
@ -50,7 +50,7 @@ The following packages are optional:
Install using `pip`, including any optional packages you want... Install using `pip`, including any optional packages you want...
pip install djangorestframework pip install djangorestframework
pip install markdown # Markdown support for the browseable API. pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support pip install django-filter # Filtering support
...or clone the project from github. ...or clone the project from github.
@ -64,7 +64,7 @@ Add `'rest_framework'` to your `INSTALLED_APPS` setting.
'rest_framework', 'rest_framework',
) )
If you're intending to use the browseable 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 = patterns('', urlpatterns = patterns('',
... ...

View File

@ -72,7 +72,7 @@ You can determine your currently installed version using `pip freeze`:
**Date**: 4th April 2013 **Date**: 4th April 2013
* OAuth2 authentication no longer requires unneccessary URL parameters in addition to the token. * OAuth2 authentication no longer requires unneccessary URL parameters in addition to the token.
* URL hyperlinking in browseable API now handles more cases correctly. * URL hyperlinking in browsable API now handles more cases correctly.
* Long HTTP headers in browsable API are broken in multiple lines when possible. * Long HTTP headers in browsable API are broken in multiple lines when possible.
* Bugfix: Fix regression with DjangoFilterBackend not worthing correctly with single object views. * Bugfix: Fix regression with DjangoFilterBackend not worthing correctly with single object views.
* Bugfix: OAuth should fail hard when invalid token used. * Bugfix: OAuth should fail hard when invalid token used.
@ -122,10 +122,10 @@ You can determine your currently installed version using `pip freeze`:
**Date**: 22nd Feb 2013 **Date**: 22nd Feb 2013
* Security fix: Use `defusedxml` package to address XML parsing vulnerabilities. * Security fix: Use `defusedxml` package to address XML parsing vulnerabilities.
* Raw data tab added to browseable API. (Eg. Allow for JSON input.) * Raw data tab added to browsable API. (Eg. Allow for JSON input.)
* Added TimeField. * Added TimeField.
* Serializer fields can be mapped to any method that takes no args, or only takes kwargs which have defaults. * Serializer fields can be mapped to any method that takes no args, or only takes kwargs which have defaults.
* Unicode support for view names/descriptions in browseable API. * Unicode support for view names/descriptions in browsable API.
* Bugfix: request.DATA should return an empty `QueryDict` with no data, not `None`. * Bugfix: request.DATA should return an empty `QueryDict` with no data, not `None`.
* Bugfix: Remove unneeded field validation, which caused extra queries. * Bugfix: Remove unneeded field validation, which caused extra queries.
@ -222,14 +222,14 @@ This change will not affect user code, so long as it's following the recommended
**Date**: 21st Dec 2012 **Date**: 21st Dec 2012
* Bugfix: Fix bug that could occur using ChoiceField. * Bugfix: Fix bug that could occur using ChoiceField.
* Bugfix: Fix exception in browseable API on DELETE. * Bugfix: Fix exception in browsable API on DELETE.
* Bugfix: Fix issue where pk was was being set to a string if set by URL kwarg. * Bugfix: Fix issue where pk was was being set to a string if set by URL kwarg.
### 2.1.11 ### 2.1.11
**Date**: 17th Dec 2012 **Date**: 17th Dec 2012
* Bugfix: Fix issue with M2M fields in browseable API. * Bugfix: Fix issue with M2M fields in browsable API.
### 2.1.10 ### 2.1.10
@ -325,7 +325,7 @@ This change will not affect user code, so long as it's following the recommended
* Hyperlinked related fields optionally take `slug_field` and `slug_url_kwarg` arguments. * Hyperlinked related fields optionally take `slug_field` and `slug_url_kwarg` arguments.
* Support Django's cache framework. * Support Django's cache framework.
* Minor field improvements. (Don't stringify dicts, more robust many-pk fields.) * Minor field improvements. (Don't stringify dicts, more robust many-pk fields.)
* Bugfix: Support choice field in Browseable API. * Bugfix: Support choice field in Browsable API.
* Bugfix: Related fields with `read_only=True` do not require a `queryset` argument. * Bugfix: Related fields with `read_only=True` do not require a `queryset` argument.
**API-incompatible changes**: Please read [this thread][2.1.0-notes] regarding the `instance` and `data` keyword args before updating to 2.1.0. **API-incompatible changes**: Please read [this thread][2.1.0-notes] regarding the `instance` and `data` keyword args before updating to 2.1.0.

View File

@ -62,19 +62,19 @@ REST framework 2 also allows you to work with both function-based and class-base
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 independantly 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 independantly of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions.
## The Browseable API ## 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.
Browseable 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 browseable 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 improvments - actions such as as `POST` and `DELETE` will only display if the user has the appropriate permissions. There are also some functionality improvments - actions such as as `POST` and `DELETE` will only display if the user has the appropriate permissions.
![Browseable API][image] ![Browsable API][image]
**Image above**: An example of the browseable API in REST framework 2 **Image above**: An example of the browsable API in REST framework 2
## Documentation ## Documentation

View File

@ -26,7 +26,7 @@ REST framework is an agnostic Web API toolkit. It does help guide you towards b
## What REST framework provides. ## What REST framework provides.
It is self evident that REST framework makes it possible to build Hypermedia APIs. The browseable 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].

View File

@ -140,7 +140,7 @@ We can control the format of the response that we get back, either by using the
Or by appending a format suffix: Or by appending a format suffix:
curl http://127.0.0.1:8000/snippets/.json # JSON suffix curl http://127.0.0.1:8000/snippets/.json # JSON suffix
curl http://127.0.0.1:8000/snippets/.api # Browseable API suffix curl http://127.0.0.1:8000/snippets/.api # Browsable API suffix
Similarly, we can control the format of the request that we send, using the `Content-Type` header. Similarly, we can control the format of the request that we send, using the `Content-Type` header.
@ -160,9 +160,9 @@ Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/sni
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-browseable 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][browseable-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? ## What's next?
@ -170,6 +170,6 @@ In [tutorial part 3][tut-3], we'll start using class based views, and see how ge
[json-url]: http://example.com/api/items/4.json [json-url]: http://example.com/api/items/4.json
[devserver]: http://127.0.0.1:8000/snippets/ [devserver]: http://127.0.0.1:8000/snippets/
[browseable-api]: ../topics/browsable-api.md [browsable-api]: ../topics/browsable-api.md
[tut-1]: 1-serialization.md [tut-1]: 1-serialization.md
[tut-3]: 3-class-based-views.md [tut-3]: 3-class-based-views.md

View File

@ -118,17 +118,17 @@ Then, add the following property to **both** the `SnippetList` and `SnippetDetai
permission_classes = (permissions.IsAuthenticatedOrReadOnly,) permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
## Adding login to the Browseable API ## Adding login to the Browsable API
If you open a browser and navigate to the browseable 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 browseable API, by editing our URLconf once more. We can add a login view for use with the browsable API, by editing our URLconf once more.
Add the following import at the top of the file: Add the following import at the top of the file:
from django.conf.urls import include 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 browseable API. And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
urlpatterns += patterns('', urlpatterns += patterns('',
url(r'^api-auth/', include('rest_framework.urls', url(r'^api-auth/', include('rest_framework.urls',

View File

@ -149,7 +149,7 @@ We could also customize the pagination style if we needed too, but in this case
## Browsing the API ## Browsing the API
If we open a browser and navigate to the browseable API, you'll find that you can now work your way around the API simply by following links. 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.

View File

@ -76,7 +76,11 @@ Because we're using viewsets instead of views, we can automatically generate the
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.
<<<<<<< HEAD
Note that we're also 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 browseable API. Note that we're also 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 browseable 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.
>>>>>>> master
## Settings ## Settings

View File

@ -58,7 +58,7 @@ class JSONRenderer(BaseRenderer):
return '' return ''
# If 'indent' is provided in the context, then pretty print the result. # If 'indent' is provided in the context, then pretty print the result.
# E.g. If we're being called by the BrowseableAPIRenderer. # E.g. If we're being called by the BrowsableAPIRenderer.
renderer_context = renderer_context or {} renderer_context = renderer_context or {}
indent = renderer_context.get('indent', None) indent = renderer_context.get('indent', None)

View File

@ -377,7 +377,7 @@ class TestCreateModelWithAutoNowAddField(TestCase):
self.assertEqual(created.content, 'foobar') self.assertEqual(created.content, 'foobar')
# Test for particularly ugly regression with m2m in browseable API # Test for particularly ugly regression with m2m in browsable API
class ClassB(models.Model): class ClassB(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255)
@ -402,7 +402,7 @@ class ExampleView(generics.ListCreateAPIView):
class TestM2MBrowseableAPI(TestCase): class TestM2MBrowseableAPI(TestCase):
def test_m2m_in_browseable_api(self): def test_m2m_in_browseable_api(self):
""" """
Test for particularly ugly regression with m2m in browseable API Test for particularly ugly regression with m2m in browsable API
""" """
request = factory.get('/', HTTP_ACCEPT='text/html') request = factory.get('/', HTTP_ACCEPT='text/html')
view = ExampleView().as_view() view = ExampleView().as_view()