Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
08c7853
Start test case
lovelydinosaur Aug 1, 2016
5abac93
Merge branch 'master' into requests-client
lovelydinosaur Aug 12, 2016
3d1fff3
Added 'requests' test client
lovelydinosaur Aug 15, 2016
e76ca6e
Address typos
lovelydinosaur Aug 15, 2016
6ede654
Graceful fallback if requests is not installed.
lovelydinosaur Aug 17, 2016
049a39e
Add cookie support
lovelydinosaur Aug 17, 2016
64e19c7
Tests for auth and CSRF
lovelydinosaur Aug 17, 2016
da47c34
Py3 compat
lovelydinosaur Aug 17, 2016
5311769
py3 compat
lovelydinosaur Aug 17, 2016
0b3db02
py3 compat
lovelydinosaur Aug 17, 2016
0cc3f50
Add get_requests_client
lovelydinosaur Aug 18, 2016
e4f6928
Added SchemaGenerator.should_include_link
lovelydinosaur Sep 2, 2016
46b9e4e
add settings for html cutoff on related fields
Aug 22, 2016
a556b9c
Router doesn't work if prefix is blank, though project urls.py handle…
c17r Sep 14, 2016
8609c9c
Fix Django 1.10 to-many deprecation
Sep 15, 2016
197b63a
Add django.core.urlresolvers compatibility
Sep 15, 2016
bb37cb7
Update django-filter & django-guardian
Sep 15, 2016
a372a8e
Check for empty router prefix; adjust URL accordingly
c17r Sep 15, 2016
a084924
Fix misc django deprecations
Sep 15, 2016
3bfb0b7
Use TOC extension instead of header
Sep 15, 2016
3bdb0e9
Fix deprecations for py3k
Sep 16, 2016
a0a8b98
Add py3k compatibility to is_simple_callable
Sep 22, 2016
adcf653
Add is_simple_callable tests
Sep 22, 2016
b3afcb2
Drop python 3.2 support (EOL, Dropped by Django)
Sep 22, 2016
b516712
schema_renderers= should *set* the renderers, not append to them.
lovelydinosaur Sep 28, 2016
37b3475
API client (#4424)
lovelydinosaur Sep 29, 2016
c2cec78
Merge master
lovelydinosaur Sep 29, 2016
a60ef8c
Merge branch 'schema-renderers-only-for-root-view' into version-3-5
lovelydinosaur Sep 29, 2016
61b1189
Fix release notes
lovelydinosaur Sep 29, 2016
bc9b522
Merge branch 'rpkilby-fix-simple-callable' into version-3-5
lovelydinosaur Sep 29, 2016
9a4ed1b
Merge branch 'should_include_link' into version-3-5
lovelydinosaur Sep 29, 2016
24bf382
Merge branch 'html_cutoff_settings' of https://github.com/MobileWorks…
lovelydinosaur Sep 29, 2016
f455c67
Merge branch 'MobileWorks-html_cutoff_settings' into version-3-5
lovelydinosaur Sep 29, 2016
b689a3b
Add note about 'User account is disabled.' vs 'Unable to log in'
lovelydinosaur Sep 29, 2016
818ab45
Merge branch 'fix-deprecations' of https://github.com/rpkilby/django-…
lovelydinosaur Sep 29, 2016
ee2b165
Merge branch 'rpkilby-fix-deprecations' into version-3-5
lovelydinosaur Sep 29, 2016
c427144
Merge branch 'router-empty-prefix' of https://github.com/c17r/django-…
lovelydinosaur Sep 29, 2016
49ce3d6
Merge branch 'c17r-router-empty-prefix' into version-3-5
lovelydinosaur Sep 29, 2016
c3a9538
Clean up schema generation (#4527)
lovelydinosaur Sep 30, 2016
4ad5256
Handle multiple methods on custom action (#4529)
lovelydinosaur Sep 30, 2016
8044d38
RequestsClient, CoreAPIClient
lovelydinosaur Oct 4, 2016
a8501f7
exclude_from_schema
lovelydinosaur Oct 5, 2016
cd826ce
Added 'get_schema_view()' shortcut
lovelydinosaur Oct 5, 2016
7e3a3a4
Added schema descriptions
lovelydinosaur Oct 5, 2016
1084dca
Better descriptions for schemas
lovelydinosaur Oct 5, 2016
7edee80
Add type annotation to schema generation
lovelydinosaur Oct 6, 2016
b44ab76
Coerce schema 'pk' in path to actual field name
lovelydinosaur Oct 6, 2016
0724420
Deprecations move into assertion errors
lovelydinosaur Oct 6, 2016
3eb7fe6
Use get_schema_view in tests
lovelydinosaur Oct 7, 2016
5858168
Updte CoreJSON media type
lovelydinosaur Oct 7, 2016
69b4acd
Handle schema structure correctly when path prefixs exist. Closes #4401
lovelydinosaur Oct 7, 2016
fcf932f
Add PendingDeprecation to Router schema generation.
lovelydinosaur Oct 7, 2016
18aebbb
Added SCHEMA_COERCE_PATH_PK and SCHEMA_COERCE_METHOD_NAMES
lovelydinosaur Oct 10, 2016
3f3213b
Renamed and documented 'get_schema_fields' interface.
lovelydinosaur Oct 10, 2016
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Added 'get_schema_view()' shortcut
  • Loading branch information
lovelydinosaur committed Oct 5, 2016
commit cd826ce422b2bbf18a675c50b989f51e253e229e
75 changes: 38 additions & 37 deletions docs/api-guide/schemas.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,15 +102,20 @@ REST framework includes functionality for auto-generating a schema,
or allows you to specify one explicitly. There are a few different ways to
add a schema to your API, depending on exactly what you need.

## Using DefaultRouter
## The get_schema_view shortcut

If you're using `DefaultRouter` then you can include an auto-generated schema,
simply by adding a `schema_title` argument to the router.
The simplest way to include a schema in your project is to use the
`get_schema_view()` function.

router = DefaultRouter(schema_title='Server Monitoring API')
schema_view = get_schema_view(title="Server Monitoring API")

The schema will be included at the root URL, `/`, and presented to clients
that include the Core JSON media type in their `Accept` header.
urlpatterns = [
url('^$', schema_view),
...
]

Once the view has been added, you'll be able to make API requests to retrieve
the auto-generated schema definition.

$ http http://127.0.0.1:8000/ Accept:application/vnd.coreapi+json
HTTP/1.0 200 OK
Expand All @@ -125,48 +130,43 @@ that include the Core JSON media type in their `Accept` header.
...
}

This is a great zero-configuration option for when you want to get up and
running really quickly.

The other available options to `DefaultRouter` are:
The arguments to `get_schema_view()` are:

#### schema_renderers

May be used to pass the set of renderer classes that can be used to render schema output.

from rest_framework.renderers import CoreJSONRenderer
from my_custom_package import APIBlueprintRenderer
#### `title`

router = DefaultRouter(schema_title='Server Monitoring API', schema_renderers=[
CoreJSONRenderer, APIBlueprintRenderer
])
May be used to provide a descriptive title for the schema definition.

#### schema_url
#### `url`

May be used to pass the root URL for the schema. This can either be used to ensure that
the schema URLs include a canonical hostname and schema, or to ensure that all the
schema URLs include a path prefix.
May be used to pass a canonical URL for the schema.

router = DefaultRouter(
schema_title='Server Monitoring API',
schema_url='https://www.example.org/api/'
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/'
)

If you want more flexibility over the schema output then you'll need to consider
using `SchemaGenerator` instead.

#### root_renderers
#### `renderer_classes`

May be used to pass the set of renderer classes that can be used to render the API root endpoint.

## Using SchemaGenerator
from rest_framework.renderers import CoreJSONRenderer
from my_custom_package import APIBlueprintRenderer

The most common way to add a schema to your API is to use the `SchemaGenerator`
class to auto-generate the `Document` instance, and to return that from a view.
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/',
renderer_classes=[CoreJSONRenderer, APIBlueprintRenderer]
)

## Using an explicit schema view

If you need a little more control than the `get_schema_view()` shortcut gives you,
then you can use the `SchemaGenerator` class directly to auto-generate the
`Document` instance, and to return that from a view.

This option gives you the flexibility of setting up the schema endpoint
with whatever behavior you want. For example, you can apply different
permission, throttling or authentication policies to the schema endpoint.
with whatever behaviour you want. For example, you can apply different
permission, throttling, or authentication policies to the schema endpoint.

Here's an example of using `SchemaGenerator` together with a view to
return the schema.
Expand All @@ -176,12 +176,13 @@ return the schema.
from rest_framework.decorators import api_view, renderer_classes
from rest_framework import renderers, response, schemas

generator = schemas.SchemaGenerator(title='Bookings API')

@api_view()
@renderer_classes([renderers.CoreJSONRenderer])
def schema_view(request):
generator = schemas.SchemaGenerator(title='Bookings API')
return response.Response(generator.get_schema())
schema = generator.get_schema(request)
return response.Response(schema)

**urls.py:**

Expand Down
21 changes: 14 additions & 7 deletions docs/tutorial/7-schemas-and-client-libraries.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,17 @@ API schema.

$ pip install coreapi

We can now include a schema for our API, by adding a `schema_title` argument to
the router instantiation.
We can now include a schema for our API, by including an autogenerated schema
view in our URL configuration.

router = DefaultRouter(schema_title='Pastebin API')
from rest_framework.schemas import get_schema_view

schema_view = get_schema_view(title='Pastebin API')

urlpatterns = [
url('^schema/$', schema_view),
...
]

If you visit the API root endpoint in a browser you should now see `corejson`
representation become available as an option.
Expand All @@ -46,7 +53,7 @@ representation become available as an option.
We can also request the schema from the command line, by specifying the desired
content type in the `Accept` header.

$ http http://127.0.0.1:8000/ Accept:application/vnd.coreapi+json
$ http http://127.0.0.1:8000/schema/ Accept:application/vnd.coreapi+json
HTTP/1.0 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/vnd.coreapi+json
Expand Down Expand Up @@ -91,8 +98,8 @@ Now check that it is available on the command line...

First we'll load the API schema using the command line client.

$ coreapi get http://127.0.0.1:8000/
<Pastebin API "http://127.0.0.1:8000/">
$ coreapi get http://127.0.0.1:8000/schema/
<Pastebin API "http://127.0.0.1:8000/schema/">
snippets: {
highlight(pk)
list()
Expand Down Expand Up @@ -150,7 +157,7 @@ Now if we fetch the schema again, we should be able to see the full
set of available interactions.

$ coreapi reload
Pastebin API "http://127.0.0.1:8000/">
Pastebin API "http://127.0.0.1:8000/schema/">
snippets: {
create(code, [title], [linenos], [language], [style])
destroy(pk)
Expand Down
52 changes: 41 additions & 11 deletions rest_framework/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
from django.utils import six
from django.utils.encoding import force_text

from rest_framework import exceptions, serializers
from rest_framework import exceptions, renderers, serializers
from rest_framework.compat import (
RegexURLPattern, RegexURLResolver, coreapi, uritemplate, urlparse
)
from rest_framework.request import clone_request
from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework.views import APIView


Expand Down Expand Up @@ -92,15 +94,14 @@ def __init__(self, patterns=None, urlconf=None):
if patterns is None:
if urlconf is None:
# Use the default Django URL conf
urls = import_module(settings.ROOT_URLCONF)
patterns = urls.urlpatterns
urlconf = settings.ROOT_URLCONF

# Load the given URLconf module
if isinstance(urlconf, six.string_types):
urls = import_module(urlconf)
else:
# Load the given URLconf module
if isinstance(urlconf, six.string_types):
urls = import_module(urlconf)
else:
urls = urlconf
patterns = urls.urlpatterns
urls = urlconf
patterns = urls.urlpatterns

self.patterns = patterns

Expand Down Expand Up @@ -189,7 +190,8 @@ def __init__(self, title=None, url=None, patterns=None, urlconf=None):
if url and not url.endswith('/'):
url += '/'

self.endpoint_inspector = self.endpoint_inspector_cls(patterns, urlconf)
self.patterns = patterns
self.urlconf = urlconf
self.title = title
self.url = url
self.endpoints = None
Expand All @@ -199,7 +201,8 @@ def get_schema(self, request=None):
Generate a `coreapi.Document` representing the API schema.
"""
if self.endpoints is None:
self.endpoints = self.endpoint_inspector.get_api_endpoints()
inspector = self.endpoint_inspector_cls(self.patterns, self.urlconf)
self.endpoints = inspector.get_api_endpoints()

links = self.get_links(request)
if not links:
Expand Down Expand Up @@ -425,3 +428,30 @@ def get_keys(self, path, method, view):

# Default action, eg "/users/", "/users/{pk}/"
return named_path_components + [action]


def get_schema_view(title=None, url=None, renderer_classes=None):
"""
Return a schema view.
"""
generator = SchemaGenerator(title=title, url=url)
if renderer_classes is None:
if renderers.BrowsableAPIRenderer in api_settings.DEFAULT_RENDERER_CLASSES:
rclasses = [renderers.CoreJSONRenderer, renderers.BrowsableAPIRenderer]
else:
rclasses = [renderers.CoreJSONRenderer]
else:
rclasses = renderer_classes

class SchemaView(APIView):
_ignore_model_permissions = True
exclude_from_schema = True
renderer_classes = rclasses

def get(self, request, *args, **kwargs):
schema = generator.get_schema(request)
if schema is None:
raise exceptions.PermissionDenied()
return Response(schema)

return SchemaView.as_view()