Skip to content

Commit

Permalink
Update docs for OpenAPI. (#6668)
Browse files Browse the repository at this point in the history
* Update schema docs for OpenAPI

* Begin v3.10 Release Announcement.

* Update docs/topics/documenting-your-api.md

Co-Authored-By: Martin Pajuste <pajusmar@users.noreply.github.com>

* Update docs/topics/documenting-your-api.md

Co-Authored-By: Martin Pajuste <pajusmar@users.noreply.github.com>

* Update docs/topics/documenting-your-api.md

Co-Authored-By: Martin Pajuste <pajusmar@users.noreply.github.com>

* Update docs/topics/documenting-your-api.md

Co-Authored-By: Martin Pajuste <pajusmar@users.noreply.github.com>
  • Loading branch information
2 people authored and tomchristie committed Jul 8, 2019
1 parent 7762aaa commit 7915485
Show file tree
Hide file tree
Showing 9 changed files with 1,388 additions and 926 deletions.
873 changes: 125 additions & 748 deletions docs/api-guide/schemas.md

Large diffs are not rendered by default.

104 changes: 104 additions & 0 deletions docs/community/3.10-announcement.md
@@ -0,0 +1,104 @@

# Django REST framework 3.10


* Reworked OpenAPI schema generation.
* Python 3 only.


## OpenAPI Schema Generation.

Since we first introduced schema support in Django REST Framework 3.5, OpenAPI has emerged as the widely adopted standard for modelling Web APIs.

This release deprecates the old CoreAPI based schema generation, and introduces improved OpenAPI schema generation in its place.

----

**Switching mode between `CoreAPI` and `OpenAPI`**

Both the `generateschema` management command and `get_schema_view()` helper
function will automatically switch between `CoreAPI` and `OpenAPI` modes,
depending on the value of `api_settings.DEFAULT_SCHEMA_CLASS`.

If `api_settings.DEFAULT_SCHEMA_CLASS` is a subclass of
`rest_framework.schemas.coreapi.AutoSchema` then `CoreAPI` mode will be
selected. Otherwise the new `OpenAPI` will apply.

This means that, unless you previously overrode
`api_settings.DEFAULT_SCHEMA_CLASS`, you automatically be opted-in to the new
`OpenAPI` based schemas.

You can continue to use CoreAPI schemas by setting the appropriate default
schema class:

```python
# In settings.py
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
```

----

### Quickstart

To get going with `OpenAPI` schemas, use the `get_schema_view()` shortcut.

In your `urls.py`:

```python
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'),
# ...
]
```

See the Schemas documentation for more details.

### Feature Roadmap

For v3.7 (with `CoreAPI`) we tried to anticipate customizations that people
were likely to need. (Introducing `manual_fields` and `ManaualSchema`, for
example.) These were under-utilised. They weren't the right abstractions.

So, for a fresh start with `OpenAPI`, customizing schema generation has two
simple rules:

* Subclass `SchemaGenerator` for schema-level cusomizations.
* Subclass `AutoSchema` for view-level customizations.

We'll wait to see what subclasses people actually come up with, for the
customizations they actually need, before trying to bring that back into the
core framework.

There are two kinds of changes that easily predictable:

* General improvements which fill in gaps in the automatic schema generation.
* More use-case specific adjustments, which adjust the API of `SchemaGenerator`
or `AutoSchema`

We'll aim to bring the first type of change quickly in point releases. For the
second kind we'd like to adopt a slower approach, to make sure we keep the API
simple, and as widely applicable as possible, before we bring in API changes.

We trust that approach makes sense.

### Deprecating CoreAPI Schema Generation.

The in-built docs that were introduced in Django REST Framework v3.5 were built on CoreAPI. These are now deprecated. You may continue to use them but they will be **removed in Django REST Framework v 3.12**.

You should migrate to using the new OpenAPI based schema generation as soon as you can.

We have removed the old documentation for the CoreAPI based schema generation.
You may view the [Legacy CoreAPI documentation here][legacy-core-api-docs].

[legacy-core-api-docs]:https://github.com/encode/django-rest-framework/blob/master/docs/coreapi/index.md
171 changes: 171 additions & 0 deletions docs/coreapi/from-documenting-your-api.md
@@ -0,0 +1,171 @@

## Built-in API documentation

The built-in API documentation includes:

* Documentation of API endpoints.
* Automatically generated code samples for each of the available API client libraries.
* Support for API interaction.

### Installation

The `coreapi` library is required as a dependency for the API docs. Make sure
to install the latest version. The `Pygments` and `Markdown` libraries
are optional but recommended.

To install the API documentation, you'll need to include it in your project's URLconf:

from rest_framework.documentation import include_docs_urls

urlpatterns = [
...
url(r'^docs/', include_docs_urls(title='My API title'))
]

This will include two different views:

* `/docs/` - The documentation page itself.
* `/docs/schema.js` - A JavaScript resource that exposes the API schema.

---

**Note**: By default `include_docs_urls` configures the underlying `SchemaView` to generate _public_ schemas.
This means that views will not be instantiated with a `request` instance. i.e. Inside the view `self.request` will be `None`.

To be compatible with this behaviour, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.

You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`:

from rest_framework.documentation import include_docs_urls

urlpatterns = [
...
# Generate schema with valid `request` instance:
url(r'^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.
For example:

class UserList(generics.ListAPIView):
"""
Return a list of all the existing users.
"""

If a view supports multiple methods, you should split your documentation using `method:` style delimiters.

class UserList(generics.ListCreateAPIView):
"""
get:
Return a list of all the existing users.

post:
Create a new user instance.
"""

When using viewsets, you should use the relevant action names as delimiters.

class UserViewSet(viewsets.ModelViewSet):
"""
retrieve:
Return the given user.

list:
Return a list of all the existing users.

create:
Create a new user instance.
"""

Custom actions on viewsets can also be documented in a similar way using the method names
as delimiters or by attaching the documentation to action mapping methods.

class UserViewSet(viewsets.ModelViewset):
...

@action(detail=False, methods=['get', 'post'])
def some_action(self, request, *args, **kwargs):
"""
get:
A description of the get method on the custom action.

post:
A description of the post method on the custom action.
"""

@some_action.mapping.put
def put_some_action():
"""
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`.

`include_docs_urls` employs `get_docs_view` and `get_schemajs_view` to generate the url patterns for the documentation page and JavaScript resource that exposes the API schema respectively. They expose the following options for customisation. (`get_docs_view` and `get_schemajs_view` ultimately call `rest_frameworks.schemas.get_schema_view()`, see the Schemas docs for more options there.)

#### `include_docs_urls`

* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
* `description`: Default `None`. May be used to provide a description for the schema definition.
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
* `public`: Default `True`. Should the schema be considered _public_? If `True` schema is generated without a `request` instance being passed to views.
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
* `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`.
* `renderer_classes`: Default `None`. May be used to pass custom renderer classes to the `SchemaView`.

#### `get_docs_view`

* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
* `description`: Default `None`. May be used to provide a description for the schema definition.
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views.
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
* `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`.
* `renderer_classes`: Default `None`. May be used to pass custom renderer classes to the `SchemaView`. If `None` the `SchemaView` will be configured with `DocumentationRenderer` and `CoreJSONRenderer` renderers, corresponding to the (default) `html` and `corejson` formats.

#### `get_schemajs_view`

* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
* `description`: Default `None`. May be used to provide a description for the schema definition.
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views.
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
* `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
each of the available API client libraries.

You may customise these samples by subclassing `DocumentationRenderer`, setting
`languages` to the list of languages you wish to support:

from rest_framework.renderers import DocumentationRenderer


class CustomRenderer(DocumentationRenderer):
languages = ['ruby', 'go']

For each language you need to provide an `intro` template, detailing installation instructions and such,
plus a generic template for making API requests, that can be filled with individual request details.
See the [templates for the bundled languages][client-library-templates] for examples.

---

[client-library-templates]: https://github.com/encode/django-rest-framework/tree/master/rest_framework/templates/rest_framework/docs/langs
29 changes: 29 additions & 0 deletions docs/coreapi/index.md
@@ -0,0 +1,29 @@
# Legacy CoreAPI Schemas Docs

Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation in Django REST Framework v3.10.

See the [Version 3.10 Release Announcement](/community/3.10-announcement.md) for more details.

----

You can continue to use CoreAPI schemas by setting the appropriate default schema class:

```python
# In settings.py
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
```

Under-the-hood, any subclass of `coreapi.AutoSchema` here will trigger use of the old CoreAPI schemas.
**Otherwise** you will automatically be opted-in to the new OpenAPI schemas.

All CoreAPI related code will be removed in Django REST Framework v3.12. Switch to OpenAPI schemas by then.

----

For reference this folder contains the old CoreAPI related documentation:

* [Tutorial 7: Schemas & client libraries](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//7-schemas-and-client-libraries.md).
* [Excerpts from _Documenting your API_ topic page](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//from-documenting-your-api.md).
* [`rest_framework.schemas` API Reference](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//schemas.md).

1 comment on commit 7915485

@bih19
Copy link

@bih19 bih19 commented on 7915485 Nov 16, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

excelente

Please sign in to comment.