mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-07-25 23:50:01 +03:00
docs: lint
This commit is contained in:
parent
79604a895e
commit
7ff1facd53
|
@ -58,7 +58,6 @@ Instead of passing the files argument separately:
|
|||
# Don't do this...
|
||||
ExampleSerializer(data=request.DATA, files=request.FILES)
|
||||
|
||||
|
||||
The usage of `request.QUERY_PARAMS` is now pending deprecation in favor of the lowercased `request.query_params`.
|
||||
|
||||
---
|
||||
|
@ -791,7 +790,7 @@ Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circu
|
|||
|
||||
If you need to restore the previous behavior you may want to include [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views.
|
||||
|
||||
#### Customizing error responses.
|
||||
#### Customizing error responses.
|
||||
|
||||
The generic views now raise `ValidationFailed` exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a `400 Bad Request` response directly.
|
||||
|
||||
|
@ -807,7 +806,7 @@ This makes it far easier to use a different style for `OPTIONS` responses throug
|
|||
|
||||
---
|
||||
|
||||
## Serializers as HTML forms
|
||||
## Serializers as HTML forms
|
||||
|
||||
REST framework 3.0 includes templated HTML form rendering for serializers.
|
||||
|
||||
|
|
|
@ -129,7 +129,7 @@ Many thanks to [Craig Blaszczyk](https://github.com/jakul) for helping push this
|
|||
|
||||
---
|
||||
|
||||
## New field types
|
||||
## New field types
|
||||
|
||||
Django 1.8's new `ArrayField`, `HStoreField` and `UUIDField` are now all fully supported.
|
||||
|
||||
|
@ -192,7 +192,7 @@ All these attributes and options will still work in 3.1, but their usage will ra
|
|||
|
||||
---
|
||||
|
||||
## What's next?
|
||||
## What's next?
|
||||
|
||||
The next focus will be on HTML renderings of API output and will include:
|
||||
|
||||
|
|
|
@ -39,12 +39,10 @@ update your REST framework settings to include `DEFAULT_SCHEMA_CLASS` explicitly
|
|||
|
||||
**settings.py**:
|
||||
|
||||
```python
|
||||
REST_FRAMEWORK = {
|
||||
...
|
||||
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
|
||||
}
|
||||
```
|
||||
REST_FRAMEWORK = {
|
||||
...
|
||||
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
|
||||
}
|
||||
|
||||
You'll still be able to keep using CoreAPI schemas, API docs, and client for the
|
||||
foreseeable future. We'll aim to ensure that the CoreAPI schema generator remains
|
||||
|
@ -54,7 +52,7 @@ from REST framework, scheduled for version 3.12.
|
|||
We have removed the old documentation for the CoreAPI based schema generation.
|
||||
You may view the [Legacy CoreAPI documentation here][legacy-core-api-docs].
|
||||
|
||||
----
|
||||
---
|
||||
|
||||
## OpenAPI Quickstart
|
||||
|
||||
|
@ -66,21 +64,19 @@ shortcut.
|
|||
|
||||
In your `urls.py`:
|
||||
|
||||
```python
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from rest_framework.schemas import get_schema_view
|
||||
|
||||
urlpatterns = [
|
||||
# ...
|
||||
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
|
||||
# * `title` and `description` parameters are passed to `SchemaGenerator`.
|
||||
# * Provide view name for use with `reverse()`.
|
||||
path('openapi', get_schema_view(
|
||||
title="Your Project",
|
||||
description="API for all things …"
|
||||
), name='openapi-schema'),
|
||||
# ...
|
||||
]
|
||||
```
|
||||
urlpatterns = [
|
||||
# ...
|
||||
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
|
||||
# * `title` and `description` parameters are passed to `SchemaGenerator`.
|
||||
# * Provide view name for use with `reverse()`.
|
||||
path('openapi', get_schema_view(
|
||||
title="Your Project",
|
||||
description="API for all things …"
|
||||
), name='openapi-schema'),
|
||||
# ...
|
||||
]
|
||||
|
||||
### Customization
|
||||
|
||||
|
|
|
@ -41,20 +41,18 @@ include:
|
|||
In this example view operation descriptions for the `get` and `post` methods will
|
||||
be extracted from the class docstring:
|
||||
|
||||
```python
|
||||
class DocStringExampleListView(APIView):
|
||||
"""
|
||||
get: A description of my GET operation.
|
||||
post: A description of my POST operation.
|
||||
"""
|
||||
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
|
||||
class DocStringExampleListView(APIView):
|
||||
"""
|
||||
get: A description of my GET operation.
|
||||
post: A description of my POST operation.
|
||||
"""
|
||||
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
...
|
||||
def get(self, request, *args, **kwargs):
|
||||
...
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
...
|
||||
```
|
||||
def post(self, request, *args, **kwargs):
|
||||
...
|
||||
|
||||
## Validator / Default Context
|
||||
|
||||
|
@ -71,23 +69,19 @@ The `__call__` method should then include an additional `serializer_field` argum
|
|||
|
||||
Validator implementations will look like this:
|
||||
|
||||
```python
|
||||
class CustomValidator:
|
||||
requires_context = True
|
||||
class CustomValidator:
|
||||
requires_context = True
|
||||
|
||||
def __call__(self, value, serializer_field):
|
||||
...
|
||||
```
|
||||
def __call__(self, value, serializer_field):
|
||||
...
|
||||
|
||||
Default implementations will look like this:
|
||||
|
||||
```python
|
||||
class CustomDefault:
|
||||
requires_context = True
|
||||
class CustomDefault:
|
||||
requires_context = True
|
||||
|
||||
def __call__(self, serializer_field):
|
||||
...
|
||||
```
|
||||
def __call__(self, serializer_field):
|
||||
...
|
||||
|
||||
---
|
||||
|
||||
|
|
|
@ -30,20 +30,39 @@ in the URL path.
|
|||
|
||||
For example...
|
||||
|
||||
Method | Path | Tags
|
||||
--------------------------------|-----------------|-------------
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']`
|
||||
`GET`, `POST` | `/users/` | `['users']`
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']`
|
||||
`GET`, `POST` | `/orders/` | `['orders']`
|
||||
<table border=1>
|
||||
<tr>
|
||||
<th>Method</th>
|
||||
<th>Path</th>
|
||||
<th>Tags</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>GET</code>, <code>PUT</code>, <code>PATCH</code>, <code>DELETE</code></td>
|
||||
<td><code>/users/{id}/</code></td>
|
||||
<td><code>['users']</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>GET</code>, <code>POST</code></td>
|
||||
<td><code>/users/</code></td>
|
||||
<td><code>['users']</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>GET</code>, <code>PUT</code>, <code>PATCH</code>, <code>DELETE</code></td>
|
||||
<td><code>/orders/{id}/</code></td>
|
||||
<td><code>['orders']</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>GET</code>, <code>POST</code></td>
|
||||
<td><code>/orders/</code></td>
|
||||
<td><code>['orders']</code></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
The tags used for a particular view may also be overridden...
|
||||
|
||||
```python
|
||||
class MyOrders(APIView):
|
||||
schema = AutoSchema(tags=['users', 'orders'])
|
||||
...
|
||||
```
|
||||
class MyOrders(APIView):
|
||||
schema = AutoSchema(tags=['users', 'orders'])
|
||||
...
|
||||
|
||||
See [the schema documentation](https://www.django-rest-framework.org/api-guide/schemas/#grouping-operations-with-tags) for more information.
|
||||
|
||||
|
@ -66,10 +85,8 @@ The names used for a component default to using the serializer class name, [but
|
|||
may be overridden if needed](https://www.django-rest-framework.org/api-guide/schemas/#components
|
||||
)...
|
||||
|
||||
```python
|
||||
class MyOrders(APIView):
|
||||
schema = AutoSchema(component_name="OrderDetails")
|
||||
```
|
||||
class MyOrders(APIView):
|
||||
schema = AutoSchema(component_name="OrderDetails")
|
||||
|
||||
## More Public API
|
||||
|
||||
|
@ -111,35 +128,31 @@ The class now supports nested search within `JSONField` and `HStoreField`, using
|
|||
the double underscore notation for traversing which element of the field the
|
||||
search should apply to.
|
||||
|
||||
```python
|
||||
class SitesSearchView(generics.ListAPIView):
|
||||
"""
|
||||
An API view to return a list of archaeological sites, optionally filtered
|
||||
by a search against the site name or location. (Location searches are
|
||||
matched against the region and country names.)
|
||||
"""
|
||||
queryset = Sites.objects.all()
|
||||
serializer_class = SitesSerializer
|
||||
filter_backends = [filters.SearchFilter]
|
||||
search_fields = ['site_name', 'location__region', 'location__country']
|
||||
```
|
||||
class SitesSearchView(generics.ListAPIView):
|
||||
"""
|
||||
An API view to return a list of archaeological sites, optionally filtered
|
||||
by a search against the site name or location. (Location searches are
|
||||
matched against the region and country names.)
|
||||
"""
|
||||
queryset = Sites.objects.all()
|
||||
serializer_class = SitesSerializer
|
||||
filter_backends = [filters.SearchFilter]
|
||||
search_fields = ['site_name', 'location__region', 'location__country']
|
||||
|
||||
### Searches against annotate fields
|
||||
|
||||
Django allows querysets to create additional virtual fields, using the `.annotate`
|
||||
method. We now support searching against annotate fields.
|
||||
|
||||
```python
|
||||
class PublisherSearchView(generics.ListAPIView):
|
||||
"""
|
||||
Search for publishers, optionally filtering the search against the average
|
||||
rating of all their books.
|
||||
"""
|
||||
queryset = Publisher.objects.annotate(avg_rating=Avg('book__rating'))
|
||||
serializer_class = PublisherSerializer
|
||||
filter_backends = [filters.SearchFilter]
|
||||
search_fields = ['avg_rating']
|
||||
```
|
||||
class PublisherSearchView(generics.ListAPIView):
|
||||
"""
|
||||
Search for publishers, optionally filtering the search against the average
|
||||
rating of all their books.
|
||||
"""
|
||||
queryset = Publisher.objects.annotate(avg_rating=Avg('book__rating'))
|
||||
serializer_class = PublisherSerializer
|
||||
filter_backends = [filters.SearchFilter]
|
||||
search_fields = ['avg_rating']
|
||||
|
||||
---
|
||||
|
||||
|
|
|
@ -40,15 +40,11 @@ From REST framework 3.13 onwards, this is now *explicitly enforced*.
|
|||
The most feasible cases where users might be accidentally omitting the keyword arguments
|
||||
are likely in the composite fields, `ListField` and `DictField`. For instance...
|
||||
|
||||
```python
|
||||
aliases = serializers.ListField(serializers.CharField())
|
||||
```
|
||||
aliases = serializers.ListField(serializers.CharField())
|
||||
|
||||
They must now use the more explicit keyword argument style...
|
||||
|
||||
```python
|
||||
aliases = serializers.ListField(child=serializers.CharField())
|
||||
```
|
||||
aliases = serializers.ListField(child=serializers.CharField())
|
||||
|
||||
This change has been made because using positional arguments here *does not* result in the expected behaviour.
|
||||
|
||||
|
|
|
@ -44,7 +44,6 @@ skipped depending on the other arguments.
|
|||
|
||||
See Pull Request [#7574](https://github.com/encode/django-rest-framework/pull/7574) for more details.
|
||||
|
||||
|
||||
## Make Open API `get_reference` public.
|
||||
|
||||
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
|
||||
|
|
|
@ -38,7 +38,7 @@ The AJAX based support for the browsable API means that there are a number of in
|
|||
|
||||
* 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][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][method-override].
|
||||
* 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][method-override].
|
||||
|
||||
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.
|
||||
|
||||
|
|
|
@ -59,20 +59,18 @@ For example, to include a swagger schema to your API, you would do the following
|
|||
|
||||
* Include the schema view in your URL conf:
|
||||
|
||||
```py
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Example API',
|
||||
renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]
|
||||
)
|
||||
schema_view = get_schema_view(
|
||||
title='Example API',
|
||||
renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
path('swagger/', schema_view),
|
||||
...
|
||||
]
|
||||
```
|
||||
urlpatterns = [
|
||||
path('swagger/', schema_view),
|
||||
...
|
||||
]
|
||||
|
||||
There have been a large number of fixes to the schema generation. These should
|
||||
resolve issues for anyone using the latest version of the `django-rest-swagger`
|
||||
|
|
|
@ -29,7 +29,6 @@ the foundations for future changes.
|
|||
If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by
|
||||
**[signing up for a paid plan][funding]**.
|
||||
|
||||
|
||||
*We'd like to say thanks in particular our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://machinalis.com/), and [Rollbar](https://rollbar.com).*
|
||||
|
||||
---
|
||||
|
@ -68,7 +67,6 @@ The new `action` decorator takes a boolean `detail` argument.
|
|||
* Replace `detail_route` uses with `@action(detail=True)`.
|
||||
* Replace `list_route` uses with `@action(detail=False)`.
|
||||
|
||||
|
||||
### `exclude_from_schema`
|
||||
|
||||
Both `APIView.exclude_from_schema` and the `exclude_from_schema` argument to the `@api_view` decorator are now deprecated. They will be removed entirely in 3.9.
|
||||
|
@ -84,7 +82,6 @@ For function based views the `@schema` decorator can be used to exclude the view
|
|||
There are a large number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page
|
||||
for a complete listing.
|
||||
|
||||
|
||||
## What's next
|
||||
|
||||
We're currently working towards moving to using [OpenAPI][openapi] as our default schema output. We'll also be revisiting our API documentation generation and client libraries.
|
||||
|
|
|
@ -19,7 +19,7 @@
|
|||
|
||||
# Django REST framework 3.9
|
||||
|
||||
The 3.9 release gives access to _extra actions_ in the Browsable API, introduces composable permissions and built-in [OpenAPI][openapi] schema support. (Formerly known as Swagger)
|
||||
The 3.9 release gives access to *extra actions* in the Browsable API, introduces composable permissions and built-in [OpenAPI][openapi] schema support. (Formerly known as Swagger)
|
||||
|
||||
---
|
||||
|
||||
|
@ -28,7 +28,6 @@ The 3.9 release gives access to _extra actions_ in the Browsable API, introduces
|
|||
If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by
|
||||
**[signing up for a paid plan][funding]**.
|
||||
|
||||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li>
|
||||
<li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
||||
|
@ -59,28 +58,24 @@ the schema into your repository.
|
|||
|
||||
Here's an example of adding an OpenAPI schema to the URL conf:
|
||||
|
||||
```python
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from rest_framework.renderers import JSONOpenAPIRenderer
|
||||
from django.urls import path
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from rest_framework.renderers import JSONOpenAPIRenderer
|
||||
from django.urls import path
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
renderer_classes=[JSONOpenAPIRenderer]
|
||||
)
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
renderer_classes=[JSONOpenAPIRenderer]
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
path('schema.json', schema_view),
|
||||
...
|
||||
]
|
||||
```
|
||||
urlpatterns = [
|
||||
path('schema.json', schema_view),
|
||||
...
|
||||
]
|
||||
|
||||
And here's how you can use the `generateschema` management command:
|
||||
|
||||
```shell
|
||||
$ python manage.py generateschema --format openapi > schema.yml
|
||||
```
|
||||
$ python manage.py generateschema --format openapi > schema.yml
|
||||
|
||||
There's lots of different tooling that you can use for working with OpenAPI
|
||||
schemas. One option that we're working on is the [API Star](https://docs.apistar.com/)
|
||||
|
@ -88,17 +83,13 @@ command line tool.
|
|||
|
||||
You can use `apistar` to validate your API schema:
|
||||
|
||||
```shell
|
||||
$ apistar validate --path schema.json --format openapi
|
||||
✓ Valid OpenAPI schema.
|
||||
```
|
||||
$ apistar validate --path schema.json --format openapi
|
||||
✓ Valid OpenAPI schema.
|
||||
|
||||
Or to build API documentation:
|
||||
|
||||
```shell
|
||||
$ apistar docs --path schema.json --format openapi
|
||||
✓ Documentation built at "build/index.html".
|
||||
```
|
||||
$ apistar docs --path schema.json --format openapi
|
||||
✓ Documentation built at "build/index.html".
|
||||
|
||||
API Star also includes a [dynamic client library](https://docs.apistar.com/client-library/)
|
||||
that uses an API schema to automatically provide a client library interface for making requests.
|
||||
|
@ -109,16 +100,14 @@ You can now compose permission classes using the and/or operators, `&` and `|`.
|
|||
|
||||
For example...
|
||||
|
||||
```python
|
||||
permission_classes = [IsAuthenticated & (ReadOnly | IsAdminUser)]
|
||||
```
|
||||
permission_classes = [IsAuthenticated & (ReadOnly | IsAdminUser)]
|
||||
|
||||
If you're using custom permission classes then make sure that you are subclassing
|
||||
from `BasePermission` in order to enable this support.
|
||||
|
||||
## ViewSet _Extra Actions_ available in the Browsable API
|
||||
## ViewSet *Extra Actions* available in the Browsable API
|
||||
|
||||
Following the introduction of the `action` decorator in v3.8, _extra actions_ defined on a ViewSet are now available
|
||||
Following the introduction of the `action` decorator in v3.8, *extra actions* defined on a ViewSet are now available
|
||||
from the Browsable API.
|
||||
|
||||

|
||||
|
@ -177,7 +166,6 @@ For function-based views the `@schema` decorator can be used to exclude the view
|
|||
|
||||
There are a large number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing.
|
||||
|
||||
|
||||
## What's next
|
||||
|
||||
We're planning to iteratively work towards OpenAPI becoming the standard schema
|
||||
|
@ -205,9 +193,6 @@ web server, as well as lots of functionality planned for the [Starlette](https:/
|
|||
web framework, which is building a foundational set of tooling for working with
|
||||
ASGI.
|
||||
|
||||
|
||||
[funding]: funding.md
|
||||
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886
|
||||
[gh5705]: https://github.com/encode/django-rest-framework/issues/5705
|
||||
[openapi]: https://www.openapis.org/
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
|
|
|
@ -48,16 +48,14 @@ YAML-based OpenAPI format.
|
|||
We can now include a schema for our API, by including an autogenerated schema
|
||||
view in our URL configuration.
|
||||
|
||||
```python
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from rest_framework.schemas import get_schema_view
|
||||
|
||||
schema_view = get_schema_view(title='Pastebin API')
|
||||
schema_view = get_schema_view(title='Pastebin API')
|
||||
|
||||
urlpatterns = [
|
||||
path('schema/', schema_view),
|
||||
...
|
||||
]
|
||||
```
|
||||
urlpatterns = [
|
||||
path('schema/', schema_view),
|
||||
...
|
||||
]
|
||||
|
||||
If you visit the `/schema/` endpoint in a browser you should now see `corejson`
|
||||
representation become available as an option.
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
|
||||
## Built-in API documentation
|
||||
# Built-in API documentation
|
||||
|
||||
----
|
||||
---
|
||||
|
||||
**DEPRECATION NOTICE:** Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details.
|
||||
|
||||
|
@ -10,7 +10,7 @@ If you are looking for information regarding schemas, you might want to look at
|
|||
1. [Schema](../api-guide/schemas.md)
|
||||
2. [Documenting your API](../topics/documenting-your-api.md)
|
||||
|
||||
----
|
||||
---
|
||||
|
||||
The built-in API documentation includes:
|
||||
|
||||
|
@ -35,8 +35,8 @@ To install the API documentation, you'll need to include it in your project's UR
|
|||
|
||||
This will include two different views:
|
||||
|
||||
* `/docs/` - The documentation page itself.
|
||||
* `/docs/schema.js` - A JavaScript resource that exposes the API schema.
|
||||
* `/docs/` - The documentation page itself.
|
||||
* `/docs/schema.js` - A JavaScript resource that exposes the API schema.
|
||||
|
||||
---
|
||||
|
||||
|
@ -55,10 +55,8 @@ You may ensure views are given a `request` instance by calling `include_docs_url
|
|||
path('docs/', include_docs_urls(title='My API title', public=False))
|
||||
]
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Documenting your views
|
||||
|
||||
You can document your views by including docstrings that describe each of the available actions.
|
||||
|
@ -116,7 +114,6 @@ as delimiters or by attaching the documentation to action mapping methods.
|
|||
A description of the put method on the custom action.
|
||||
"""
|
||||
|
||||
|
||||
### `documentation` API Reference
|
||||
|
||||
The `rest_framework.documentation` module provides three helper functions to help configure the interactive API documentation, `include_docs_urls` (usage shown above), `get_docs_view` and `get_schemajs_view`.
|
||||
|
@ -158,7 +155,6 @@ The `rest_framework.documentation` module provides three helper functions to hel
|
|||
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
|
||||
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`.
|
||||
|
||||
|
||||
### Customising code samples
|
||||
|
||||
The built-in API documentation includes automatically generated code samples for
|
||||
|
@ -179,4 +175,4 @@ See the [templates for the bundled languages][client-library-templates] for exam
|
|||
|
||||
---
|
||||
|
||||
[client-library-templates]: https://github.com/encode/django-rest-framework/tree/master/rest_framework/templates/rest_framework/docs/langs
|
||||
[client-library-templates]: https://github.com/encode/django-rest-framework/tree/master/rest_framework/templates/rest_framework/docs/langs
|
||||
|
|
|
@ -240,7 +240,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||
[pygments]: https://pypi.org/project/Pygments/
|
||||
[django-filter]: https://pypi.org/project/django-filter/
|
||||
[django-guardian]: https://github.com/django-guardian/django-guardian
|
||||
[index]: .
|
||||
[oauth1-section]: api-guide/authentication/#django-rest-framework-oauth
|
||||
[oauth2-section]: api-guide/authentication/#django-oauth-toolkit
|
||||
[serializer-section]: api-guide/serializers#serializers
|
||||
|
@ -263,5 +262,3 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[stack-overflow]: https://stackoverflow.com/
|
||||
[django-rest-framework-tag]: https://stackoverflow.com/questions/tagged/django-rest-framework
|
||||
[security-mail]: mailto:rest-framework-security@googlegroups.com
|
||||
[twitter]: https://twitter.com/_tomchristie
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — 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."
|
||||
>
|
||||
> — [Jeff Atwood][cite]
|
||||
> — [Jeff Atwood][cite]
|
||||
|
||||
## Javascript clients
|
||||
|
||||
|
|
|
@ -4,7 +4,6 @@
|
|||
>
|
||||
> — [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`.
|
||||
|
||||
## URLs
|
||||
|
|
|
@ -25,53 +25,49 @@ Assuming you've followed the example from the schemas documentation for routing
|
|||
a dynamic `SchemaView`, a minimal Django template for using Swagger UI might be
|
||||
this:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Swagger</title>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="swagger-ui"></div>
|
||||
<script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
|
||||
<script>
|
||||
const ui = SwaggerUIBundle({
|
||||
url: "{% url schema_url %}",
|
||||
dom_id: '#swagger-ui',
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIBundle.SwaggerUIStandalonePreset
|
||||
],
|
||||
layout: "BaseLayout",
|
||||
requestInterceptor: (request) => {
|
||||
request.headers['X-CSRFToken'] = "{{ csrf_token }}"
|
||||
return request;
|
||||
}
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Swagger</title>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="swagger-ui"></div>
|
||||
<script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
|
||||
<script>
|
||||
const ui = SwaggerUIBundle({
|
||||
url: "{% url schema_url %}",
|
||||
dom_id: '#swagger-ui',
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIBundle.SwaggerUIStandalonePreset
|
||||
],
|
||||
layout: "BaseLayout",
|
||||
requestInterceptor: (request) => {
|
||||
request.headers['X-CSRFToken'] = "{{ csrf_token }}"
|
||||
return request;
|
||||
}
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Save this in your templates folder as `swagger-ui.html`. Then route a
|
||||
`TemplateView` in your project's URL conf:
|
||||
|
||||
```python
|
||||
from django.views.generic import TemplateView
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
urlpatterns = [
|
||||
# ...
|
||||
# Route TemplateView to serve Swagger UI template.
|
||||
# * Provide `extra_context` with view name of `SchemaView`.
|
||||
path('swagger-ui/', TemplateView.as_view(
|
||||
template_name='swagger-ui.html',
|
||||
extra_context={'schema_url':'openapi-schema'}
|
||||
), name='swagger-ui'),
|
||||
]
|
||||
```
|
||||
urlpatterns = [
|
||||
# ...
|
||||
# Route TemplateView to serve Swagger UI template.
|
||||
# * Provide `extra_context` with view name of `SchemaView`.
|
||||
path('swagger-ui/', TemplateView.as_view(
|
||||
template_name='swagger-ui.html',
|
||||
extra_context={'schema_url':'openapi-schema'}
|
||||
), name='swagger-ui'),
|
||||
]
|
||||
|
||||
See the [Swagger UI documentation][swagger-ui] for advanced usage.
|
||||
|
||||
|
@ -81,46 +77,42 @@ Assuming you've followed the example from the schemas documentation for routing
|
|||
a dynamic `SchemaView`, a minimal Django template for using ReDoc might be
|
||||
this:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>ReDoc</title>
|
||||
<!-- needed for adaptive design -->
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
|
||||
<!-- ReDoc doesn't change outer page styles -->
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<redoc spec-url='{% url schema_url %}'></redoc>
|
||||
<script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"> </script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>ReDoc</title>
|
||||
<!-- needed for adaptive design -->
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
|
||||
<!-- ReDoc doesn't change outer page styles -->
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<redoc spec-url='{% url schema_url %}'></redoc>
|
||||
<script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"> </script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Save this in your templates folder as `redoc.html`. Then route a `TemplateView`
|
||||
in your project's URL conf:
|
||||
|
||||
```python
|
||||
from django.views.generic import TemplateView
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
urlpatterns = [
|
||||
# ...
|
||||
# Route TemplateView to serve the ReDoc template.
|
||||
# * Provide `extra_context` with view name of `SchemaView`.
|
||||
path('redoc/', TemplateView.as_view(
|
||||
template_name='redoc.html',
|
||||
extra_context={'schema_url':'openapi-schema'}
|
||||
), name='redoc'),
|
||||
]
|
||||
```
|
||||
urlpatterns = [
|
||||
# ...
|
||||
# Route TemplateView to serve the ReDoc template.
|
||||
# * Provide `extra_context` with view name of `SchemaView`.
|
||||
path('redoc/', TemplateView.as_view(
|
||||
template_name='redoc.html',
|
||||
extra_context={'schema_url':'openapi-schema'}
|
||||
), name='redoc'),
|
||||
]
|
||||
|
||||
See the [ReDoc documentation][redoc] for advanced usage.
|
||||
|
||||
|
@ -139,7 +131,6 @@ generation tools like `swagger-codegen`.
|
|||
|
||||
This also translates into a very useful interactive documentation viewer in the form of `swagger-ui`:
|
||||
|
||||
|
||||
![Screenshot - drf-yasg][image-drf-yasg]
|
||||
|
||||
#### drf-spectacular - Sane and flexible OpenAPI 3.0 schema generation for Django REST framework
|
||||
|
|
|
@ -207,14 +207,55 @@ 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
|
||||
----|----|----
|
||||
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
|
||||
textarea.html | `CharField` | rows, placeholder, hide_label
|
||||
select.html | `ChoiceField` or relational field types | hide_label
|
||||
radio.html | `ChoiceField` or relational field types | inline, hide_label
|
||||
select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
|
||||
checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label
|
||||
checkbox.html | `BooleanField` | hide_label
|
||||
fieldset.html | Nested serializer | hide_label
|
||||
list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label
|
||||
<table border=1>
|
||||
<tr>
|
||||
<th>base_template</th>
|
||||
<th>Valid field types</th>
|
||||
<th>Additional style options</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>input.html</td>
|
||||
<td>Any string, numeric or date/time field</td>
|
||||
<td>input_type, placeholder, hide_label, autofocus</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>textarea.html</td>
|
||||
<td><code>CharField</code></td>
|
||||
<td>rows, placeholder, hide_label</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>select.html</td>
|
||||
<td><code>ChoiceField</code> or relational field types</td>
|
||||
<td>hide_label</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>radio.html</td>
|
||||
<td><code>ChoiceField</code> or relational field types</td>
|
||||
<td>inline, hide_label</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>select_multiple.html</td>
|
||||
<td><code>MultipleChoiceField</code> or relational fields with <code>many=True</code></td>
|
||||
<td>hide_label</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>checkbox_multiple.html</td>
|
||||
<td><code>MultipleChoiceField</code> or relational fields with <code>many=True</code></td>
|
||||
<td>inline, hide_label</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>checkbox.html</td>
|
||||
<td><code>BooleanField</code></td>
|
||||
<td>hide_label</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>fieldset.html</td>
|
||||
<td>Nested serializer</td>
|
||||
<td>hide_label</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>list_fieldset.html</td>
|
||||
<td><code>ListField</code> or nested serializer with <code>many=True</code></td>
|
||||
<td>hide_label</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
# Writable nested serializers
|
||||
|
||||
> To save HTTP requests, it may be convenient to send related documents along with the request.
|
||||
>
|
||||
> — [JSON API specification for Ember Data][cite].
|
||||
|
||||
# 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.
|
||||
|
||||
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.
|
||||
|
@ -43,5 +43,4 @@ Let's take a look at updating our nested one-to-many data structure.
|
|||
|
||||
### Making PATCH requests
|
||||
|
||||
|
||||
[cite]: http://jsonapi.org/format/#url-based-json-api
|
||||
|
|
|
@ -137,6 +137,7 @@ Again, if we need more control over the API URLs we can simply drop down to usin
|
|||
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.
|
||||
|
||||
## Pagination
|
||||
|
||||
Pagination allows you to control how many objects per page are returned. To enable it add the following lines to `tutorial/settings.py`
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
|
@ -200,7 +201,6 @@ Or using the [httpie][httpie], command line tool...
|
|||
]
|
||||
}
|
||||
|
||||
|
||||
Or directly through the browser, by going to the URL `http://127.0.0.1:8000/users/`...
|
||||
|
||||
![Quick start image][image]
|
||||
|
|
Loading…
Reference in New Issue
Block a user