2016-07-07 11:41:32 +03:00
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" >
< meta charset = "utf-8" >
< title > Schemas - Django REST framework< / title >
< link href = "../../img/favicon.ico" rel = "icon" type = "image/x-icon" >
< link rel = "canonical" href = "http://www.django-rest-framework.org/api-guide/schemas/" / >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< meta name = "description" content = "Django, API, REST, Schemas" >
< meta name = "author" content = "Tom Christie" >
<!-- Le styles -->
< link href = "../../css/prettify.css" rel = "stylesheet" >
< link href = "../../css/bootstrap.css" rel = "stylesheet" >
< link href = "../../css/bootstrap-responsive.css" rel = "stylesheet" >
< link href = "../../css/default.css" rel = "stylesheet" >
<!-- Le HTML5 shim, for IE6 - 8 support of HTML5 elements -->
<!-- [if lt IE 9]>
< script src = "http://html5shim.googlecode.com/svn/trunk/html5.js" > < / script >
<![endif]-->
< script type = "text/javascript" >
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18852272-2']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
< / script >
< style >
#sidebarInclude img {
margin-bottom: 10px;
}
#sidebarInclude a.promo {
color: black;
}
@media (max-width: 767px) {
div.promo {
display: none;
}
}
< / style >
< / head >
< body onload = "prettyPrint()" class = "-page" >
< div class = "wrapper" >
< div class = "navbar navbar-inverse navbar-fixed-top" >
< div class = "navbar-inner" >
< div class = "container-fluid" >
< a class = "repo-link btn btn-primary btn-small" href = "https://github.com/tomchristie/django-rest-framework/tree/master" > GitHub< / a >
< a class = "repo-link btn btn-inverse btn-small " rel = "prev" href = "../format-suffixes/" >
Next < i class = "icon-arrow-right icon-white" > < / i >
< / a >
< a class = "repo-link btn btn-inverse btn-small " rel = "next" href = "../metadata/" >
< i class = "icon-arrow-left icon-white" > < / i > Previous
< / a >
< a id = "search_modal_show" class = "repo-link btn btn-inverse btn-small" href = "#mkdocs_search_modal" data-toggle = "modal" data-target = "#mkdocs_search_modal" > < i class = "icon-search icon-white" > < / i > Search< / a >
< a class = "btn btn-navbar" data-toggle = "collapse" data-target = ".nav-collapse" >
< span class = "icon-bar" > < / span >
< span class = "icon-bar" > < / span >
< span class = "icon-bar" > < / span >
< / a >
< a class = "brand" href = "http://www.django-rest-framework.org" > Django REST framework< / a >
< div class = "nav-collapse collapse" >
<!-- Main navigation -->
< ul class = "nav navbar-nav" >
< li >
< a href = "../.." > Home< / a >
< / li >
< li class = "dropdown" >
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > Tutorial < b class = "caret" > < / b > < / a >
< ul class = "dropdown-menu" >
< li >
< a href = "../../tutorial/quickstart/" > Quickstart< / a >
< / li >
< li >
< a href = "../../tutorial/1-serialization/" > 1 - Serialization< / a >
< / li >
< li >
< a href = "../../tutorial/2-requests-and-responses/" > 2 - Requests and responses< / a >
< / li >
< li >
< a href = "../../tutorial/3-class-based-views/" > 3 - Class based views< / a >
< / li >
< li >
< a href = "../../tutorial/4-authentication-and-permissions/" > 4 - Authentication and permissions< / a >
< / li >
< li >
< a href = "../../tutorial/5-relationships-and-hyperlinked-apis/" > 5 - Relationships and hyperlinked APIs< / a >
< / li >
< li >
< a href = "../../tutorial/6-viewsets-and-routers/" > 6 - Viewsets and routers< / a >
< / li >
2016-07-14 15:05:57 +03:00
< li >
< a href = "../../tutorial/7-schemas-and-client-libraries/" > 7 - Schemas and client libraries< / a >
< / li >
2016-07-07 11:41:32 +03:00
< / ul >
< / li >
< li class = "dropdown active" >
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > API Guide < b class = "caret" > < / b > < / a >
< ul class = "dropdown-menu" >
< li >
< a href = "../requests/" > Requests< / a >
< / li >
< li >
< a href = "../responses/" > Responses< / a >
< / li >
< li >
< a href = "../views/" > Views< / a >
< / li >
< li >
< a href = "../generic-views/" > Generic views< / a >
< / li >
< li >
< a href = "../viewsets/" > Viewsets< / a >
< / li >
< li >
< a href = "../routers/" > Routers< / a >
< / li >
< li >
< a href = "../parsers/" > Parsers< / a >
< / li >
< li >
< a href = "../renderers/" > Renderers< / a >
< / li >
< li >
< a href = "../serializers/" > Serializers< / a >
< / li >
< li >
< a href = "../fields/" > Serializer fields< / a >
< / li >
< li >
< a href = "../relations/" > Serializer relations< / a >
< / li >
< li >
< a href = "../validators/" > Validators< / a >
< / li >
< li >
< a href = "../authentication/" > Authentication< / a >
< / li >
< li >
< a href = "../permissions/" > Permissions< / a >
< / li >
< li >
< a href = "../throttling/" > Throttling< / a >
< / li >
< li >
< a href = "../filtering/" > Filtering< / a >
< / li >
< li >
< a href = "../pagination/" > Pagination< / a >
< / li >
< li >
< a href = "../versioning/" > Versioning< / a >
< / li >
< li >
< a href = "../content-negotiation/" > Content negotiation< / a >
< / li >
< li >
< a href = "../metadata/" > Metadata< / a >
< / li >
< li class = "active" >
< a href = "./" > Schemas< / a >
< / li >
< li >
< a href = "../format-suffixes/" > Format suffixes< / a >
< / li >
< li >
< a href = "../reverse/" > Returning URLs< / a >
< / li >
< li >
< a href = "../exceptions/" > Exceptions< / a >
< / li >
< li >
< a href = "../status-codes/" > Status codes< / a >
< / li >
< li >
< a href = "../testing/" > Testing< / a >
< / li >
< li >
< a href = "../settings/" > Settings< / a >
< / li >
< / ul >
< / li >
< li class = "dropdown" >
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > Topics < b class = "caret" > < / b > < / a >
< ul class = "dropdown-menu" >
< li >
< a href = "../../topics/documenting-your-api/" > Documenting your API< / a >
< / li >
< li >
< a href = "../../topics/api-clients/" > API Clients< / a >
< / li >
< li >
< a href = "../../topics/internationalization/" > Internationalization< / a >
< / li >
< li >
< a href = "../../topics/ajax-csrf-cors/" > AJAX, CSRF & CORS< / a >
< / li >
< li >
< a href = "../../topics/html-and-forms/" > HTML & Forms< / a >
< / li >
< li >
< a href = "../../topics/browser-enhancements/" > Browser Enhancements< / a >
< / li >
< li >
< a href = "../../topics/browsable-api/" > The Browsable API< / a >
< / li >
< li >
< a href = "../../topics/rest-hypermedia-hateoas/" > REST, Hypermedia & HATEOAS< / a >
< / li >
< li >
< a href = "../../topics/third-party-resources/" > Third Party Resources< / a >
< / li >
< li >
< a href = "../../topics/contributing/" > Contributing to REST framework< / a >
< / li >
< li >
< a href = "../../topics/project-management/" > Project management< / a >
< / li >
< li >
< a href = "../../topics/3.0-announcement/" > 3.0 Announcement< / a >
< / li >
< li >
< a href = "../../topics/3.1-announcement/" > 3.1 Announcement< / a >
< / li >
< li >
< a href = "../../topics/3.2-announcement/" > 3.2 Announcement< / a >
< / li >
< li >
< a href = "../../topics/3.3-announcement/" > 3.3 Announcement< / a >
< / li >
2016-07-14 15:05:57 +03:00
< li >
< a href = "../../topics/3.4-announcement/" > 3.4 Announcement< / a >
< / li >
2016-10-20 18:31:37 +03:00
< li >
< a href = "../../topics/3.5-announcement/" > 3.5 Announcement< / a >
< / li >
2016-07-07 11:41:32 +03:00
< li >
< a href = "../../topics/kickstarter-announcement/" > Kickstarter Announcement< / a >
< / li >
< li >
< a href = "../../topics/mozilla-grant/" > Mozilla Grant< / a >
< / li >
< li >
< a href = "../../topics/funding/" > Funding< / a >
< / li >
< li >
< a href = "../../topics/release-notes/" > Release Notes< / a >
< / li >
< / ul >
< / li >
< / ul >
< / div >
<!-- /.nav - collapse -->
< / div >
< / div >
< / div >
< div class = "body-content" >
< div class = "container-fluid" >
<!-- Search Modal -->
< div id = "mkdocs_search_modal" class = "modal hide fade" tabindex = "-1" role = "dialog" aria-labelledby = "myModalLabel" aria-hidden = "true" >
< div class = "modal-header" >
< button type = "button" class = "close" data-dismiss = "modal" aria-hidden = "true" > × < / button >
< h3 id = "myModalLabel" > Documentation search< / h3 >
< / div >
< div class = "modal-body" >
< form role = "form" autocomplete = "off" >
< div class = "form-group" >
< input type = "text" name = "q" class = "form-control" placeholder = "Search..." id = "mkdocs-search-query" >
< / div >
< / form >
< div id = "mkdocs-search-results" > < / div >
< / div >
< div class = "modal-footer" >
< button class = "btn" data-dismiss = "modal" aria-hidden = "true" > Close< / button >
< / div >
< / div >
< div class = "row-fluid" >
< div class = "span3" >
< div id = "table-of-contents" >
< ul class = "nav nav-list side-nav well sidebar-nav-fixed" >
< li class = "main" >
< a href = "#schemas" > Schemas< / a >
< / li >
< li >
< a href = "#representing-schemas-internally" > Representing schemas internally< / a >
< / li >
< li >
< a href = "#schema-output-formats" > Schema output formats< / a >
< / li >
< li >
< a href = "#schemas-vs-hypermedia" > Schemas vs Hypermedia< / a >
< / li >
< li class = "main" >
< a href = "#adding-a-schema" > Adding a schema< / a >
< / li >
< li >
2016-10-14 16:33:49 +03:00
< a href = "#the-get_schema_view-shortcut" > The get_schema_view shortcut< / a >
2016-07-07 11:41:32 +03:00
< / li >
< li >
2016-10-14 16:33:49 +03:00
< a href = "#using-an-explicit-schema-view" > Using an explicit schema view< / a >
2016-07-07 11:41:32 +03:00
< / li >
< li >
< a href = "#explicit-schema-definition" > Explicit schema definition< / a >
< / li >
< li >
< a href = "#static-schema-file" > Static schema file< / a >
< / li >
2016-10-14 16:33:49 +03:00
< li class = "main" >
< a href = "#schemas-as-documentation" > Schemas as documentation< / a >
< / li >
< li >
< a href = "#examples" > Examples< / a >
< / li >
2016-07-14 15:05:57 +03:00
< li class = "main" >
< a href = "#alternate-schema-formats" > Alternate schema formats< / a >
< / li >
< li >
< a href = "#example" > Example< / a >
< / li >
2016-07-07 11:41:32 +03:00
< li class = "main" >
< a href = "#api-reference" > API Reference< / a >
< / li >
< li >
< a href = "#schemagenerator" > SchemaGenerator< / a >
< / li >
< li >
< a href = "#core-api" > Core API< / a >
< / li >
< div class = "promo" >
< hr / >
< div id = "sidebarInclude" >
< / div >
< / ul >
< / div >
< / div >
< div id = "main-content" class = "span9" >
< a class = "github" href = "https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/schemas.py" >
< span class = "label label-info" > schemas.py< / span >
< / a >
< h1 id = "schemas" > < a class = "toclink" href = "#schemas" > Schemas< / a > < / h1 >
< blockquote >
< p > 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.< / p >
< p > — Heroku, < a href = "https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api" > JSON Schema for the Heroku Platform API< / a > < / p >
< / blockquote >
< p > API schemas are a useful tool that allow for a range of use cases, including
generating reference documentation, or driving dynamic client libraries that
can interact with your API.< / p >
< h2 id = "representing-schemas-internally" > < a class = "toclink" href = "#representing-schemas-internally" > Representing schemas internally< / a > < / h2 >
< p > REST framework uses < a href = "http://www.coreapi.org/" > Core API< / a > in order to model schema information in
a format-independent representation. This information can then be rendered
into various different schema formats, or used to generate API documentation.< / p >
< p > When using Core API, a schema is represented as a < code > Document< / code > which is the
top-level container object for information about the API. Available API
interactions are represented using < code > Link< / code > objects. Each link includes a URL,
HTTP method, and may include a list of < code > Field< / code > instances, which describe any
parameters that may be accepted by the API endpoint. The < code > Link< / code > and < code > Field< / code >
instances may also include descriptions, that allow an API schema to be
rendered into user documentation.< / p >
< p > Here's an example of an API description that includes a single < code > search< / code >
endpoint:< / p >
< pre > < code > coreapi.Document(
title='Flight Search API',
url='https://api.example.org/',
content={
'search': coreapi.Link(
url='/search/',
action='get',
fields=[
coreapi.Field(
name='from',
required=True,
location='query',
description='City name or airport code.'
),
coreapi.Field(
name='to',
required=True,
location='query',
description='City name or airport code.'
),
coreapi.Field(
name='date',
required=True,
location='query',
description='Flight date in "YYYY-MM-DD" format.'
)
],
description='Return flight availability and prices.'
)
}
)
< / code > < / pre >
< h2 id = "schema-output-formats" > < a class = "toclink" href = "#schema-output-formats" > Schema output formats< / a > < / h2 >
< p > In order to be presented in an HTTP response, the internal representation
has to be rendered into the actual bytes that are used in the response.< / p >
< p > < a href = "http://www.coreapi.org/specification/encoding/#core-json-encoding" > Core JSON< / a > is designed as a canonical format for use with Core API.
REST framework includes a renderer class for handling this media type, which
is available as < code > renderers.CoreJSONRenderer< / code > .< / p >
2016-07-14 15:05:57 +03:00
< p > Other schema formats such as < a href = "https://openapis.org/" > Open API< / a > ("Swagger"),
2016-07-07 11:41:32 +03:00
< a href = "http://json-schema.org/latest/json-schema-hypermedia.html" > JSON HyperSchema< / a > , or < a href = "https://apiblueprint.org/" > API Blueprint< / a > can
also be supported by implementing a custom renderer class.< / p >
< h2 id = "schemas-vs-hypermedia" > < a class = "toclink" href = "#schemas-vs-hypermedia" > Schemas vs Hypermedia< / a > < / h2 >
< p > It's worth pointing out here that Core API can also be used to model hypermedia
responses, which present an alternative interaction style to API schemas.< / p >
< p > With an API schema, the entire available interface is presented up-front
as a single endpoint. Responses to individual API endpoints are then typically
presented as plain data, without any further interactions contained in each
response.< / p >
< p > With Hypermedia, the client is instead presented with a document containing
both data and available interactions. Each interaction results in a new
document, detailing both the current state and the available interactions.< / p >
< p > Further information and support on building Hypermedia APIs with REST framework
is planned for a future version.< / p >
< hr / >
< h1 id = "adding-a-schema" > < a class = "toclink" href = "#adding-a-schema" > Adding a schema< / a > < / h1 >
< p > You'll need to install the < code > coreapi< / code > package in order to add schema support
for REST framework.< / p >
< pre > < code > pip install coreapi
< / code > < / pre >
< p > 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.< / p >
2016-10-14 16:33:49 +03:00
< h2 id = "the-get_schema_view-shortcut" > < a class = "toclink" href = "#the-get_schema_view-shortcut" > The get_schema_view shortcut< / a > < / h2 >
< p > The simplest way to include a schema in your project is to use the
< code > get_schema_view()< / code > function.< / p >
< pre > < code > schema_view = get_schema_view(title="Server Monitoring API")
urlpatterns = [
url('^$', schema_view),
...
]
2016-07-07 11:41:32 +03:00
< / code > < / pre >
2016-10-14 16:33:49 +03:00
< p > Once the view has been added, you'll be able to make API requests to retrieve
the auto-generated schema definition.< / p >
2016-07-07 11:41:32 +03:00
< pre > < code > $ http http://127.0.0.1:8000/ Accept:application/vnd.coreapi+json
HTTP/1.0 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/vnd.coreapi+json
{
"_meta": {
"title": "Server Monitoring API"
},
"_type": "document",
...
}
< / code > < / pre >
2016-10-14 16:33:49 +03:00
< p > The arguments to < code > get_schema_view()< / code > are:< / p >
< h4 id = "title" > < a class = "toclink" href = "#title" > < code > title< / code > < / a > < / h4 >
< p > May be used to provide a descriptive title for the schema definition.< / p >
< h4 id = "url" > < a class = "toclink" href = "#url" > < code > url< / code > < / a > < / h4 >
< p > May be used to pass a canonical URL for the schema.< / p >
< pre > < code > schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/'
)
< / code > < / pre >
2017-01-27 13:36:59 +03:00
< h4 id = "urlconf" > < a class = "toclink" href = "#urlconf" > < code > urlconf< / code > < / a > < / h4 >
< p > A string representing the import path to the URL conf that you want
to generate an API schema for. This defaults to the value of Django's
ROOT_URLCONF setting.< / p >
< pre > < code > schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/',
urlconf='myproject.urls'
)
< / code > < / pre >
2016-10-14 16:33:49 +03:00
< h4 id = "renderer_classes" > < a class = "toclink" href = "#renderer_classes" > < code > renderer_classes< / code > < / a > < / h4 >
< p > May be used to pass the set of renderer classes that can be used to render the API root endpoint.< / p >
2016-07-14 15:05:57 +03:00
< pre > < code > from rest_framework.renderers import CoreJSONRenderer
from my_custom_package import APIBlueprintRenderer
2016-10-14 16:33:49 +03:00
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/',
renderer_classes=[CoreJSONRenderer, APIBlueprintRenderer]
2016-07-28 15:37:14 +03:00
)
< / code > < / pre >
2016-10-14 16:33:49 +03:00
< h2 id = "using-an-explicit-schema-view" > < a class = "toclink" href = "#using-an-explicit-schema-view" > Using an explicit schema view< / a > < / h2 >
< p > If you need a little more control than the < code > get_schema_view()< / code > shortcut gives you,
then you can use the < code > SchemaGenerator< / code > class directly to auto-generate the
< code > Document< / code > instance, and to return that from a view.< / p >
2016-07-07 11:41:32 +03:00
< p > This option gives you the flexibility of setting up the schema endpoint
2016-10-14 16:33:49 +03:00
with whatever behaviour you want. For example, you can apply different
permission, throttling, or authentication policies to the schema endpoint.< / p >
2016-07-07 11:41:32 +03:00
< p > Here's an example of using < code > SchemaGenerator< / code > together with a view to
return the schema.< / p >
< p > < strong > views.py:< / strong > < / p >
< pre > < code > from rest_framework.decorators import api_view, renderer_classes
2016-07-18 18:23:30 +03:00
from rest_framework import renderers, response, schemas
2016-07-07 11:41:32 +03:00
2016-10-14 16:33:49 +03:00
generator = schemas.SchemaGenerator(title='Bookings API')
2016-07-07 11:41:32 +03:00
@api_view()
@renderer_classes([renderers.CoreJSONRenderer])
def schema_view(request):
2016-10-14 16:33:49 +03:00
schema = generator.get_schema(request)
return response.Response(schema)
2016-07-07 11:41:32 +03:00
< / code > < / pre >
< p > < strong > urls.py:< / strong > < / p >
< pre > < code > urlpatterns = [
url('/', schema_view),
...
]
< / code > < / pre >
< p > You can also serve different schemas to different users, depending on the
permissions they have available. This approach can be used to ensure that
unauthenticated requests are presented with a different schema to
authenticated requests, or to ensure that different parts of the API are
made visible to different users depending on their role.< / p >
< p > In order to present a schema with endpoints filtered by user permissions,
you need to pass the < code > request< / code > argument to the < code > get_schema()< / code > method, like so:< / p >
< pre > < code > @api_view()
@renderer_classes([renderers.CoreJSONRenderer])
def schema_view(request):
2016-07-18 18:23:30 +03:00
generator = schemas.SchemaGenerator(title='Bookings API')
return response.Response(generator.get_schema(request=request))
2016-07-07 11:41:32 +03:00
< / code > < / pre >
< h2 id = "explicit-schema-definition" > < a class = "toclink" href = "#explicit-schema-definition" > Explicit schema definition< / a > < / h2 >
< p > An alternative to the auto-generated approach is to specify the API schema
explicitly, by declaring a < code > Document< / code > object in your codebase. Doing so is a
little more work, but ensures that you have full control over the schema
representation.< / p >
< pre > < code > import coreapi
from rest_framework.decorators import api_view, renderer_classes
2016-07-18 18:23:30 +03:00
from rest_framework import renderers, response
2016-07-07 11:41:32 +03:00
schema = coreapi.Document(
title='Bookings API',
content={
...
}
)
@api_view()
@renderer_classes([renderers.CoreJSONRenderer])
def schema_view(request):
2016-07-18 18:23:30 +03:00
return response.Response(schema)
2016-07-07 11:41:32 +03:00
< / code > < / pre >
< h2 id = "static-schema-file" > < a class = "toclink" href = "#static-schema-file" > Static schema file< / a > < / h2 >
< p > A final option is to write your API schema as a static file, using one
of the available formats, such as Core JSON or Open API.< / p >
< p > You could then either:< / p >
< ul >
2016-12-09 19:07:34 +03:00
< li > Write a schema definition as a static file, and < a href = "https://docs.djangoproject.com/en/stable/howto/static-files/" > serve the static file directly< / a > .< / li >
2016-07-07 11:41:32 +03:00
< li > Write a schema definition that is loaded using < code > Core API< / code > , and then
rendered to one of many available formats, depending on the client request.< / li >
< / ul >
< hr / >
2016-10-14 16:33:49 +03:00
< h1 id = "schemas-as-documentation" > < a class = "toclink" href = "#schemas-as-documentation" > Schemas as documentation< / a > < / h1 >
< p > One common usage of API schemas is to use them to build documentation pages.< / p >
< p > The schema generation in REST framework uses docstrings to automatically
populate descriptions in the schema document.< / p >
< p > These descriptions will be based on:< / p >
< ul >
< li > The corresponding method docstring if one exists.< / li >
< li > A named section within the class docstring, which can be either single line or multi-line.< / li >
< li > The class docstring.< / li >
< / ul >
< h2 id = "examples" > < a class = "toclink" href = "#examples" > Examples< / a > < / h2 >
< p > An < code > APIView< / code > , with an explicit method docstring.< / p >
< pre > < code > class ListUsernames(APIView):
def get(self, request):
"""
Return a list of all user names in the system.
"""
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
< / code > < / pre >
< p > A < code > ViewSet< / code > , with an explict action docstring.< / p >
< pre > < code > class ListUsernames(ViewSet):
def list(self, request):
"""
Return a list of all user names in the system.
"""
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
< / code > < / pre >
< p > A generic view with sections in the class docstring, using single-line style.< / p >
< pre > < code > class UserList(generics.ListCreateAPIView):
"""
2017-01-06 12:08:44 +03:00
get: List all the users.
post: Create a new user.
2016-10-14 16:33:49 +03:00
"""
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (IsAdminUser,)
< / code > < / pre >
< p > A generic viewset with sections in the class docstring, using multi-line style.< / p >
< pre > < code > class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
retrieve:
Return a user instance.
list:
Return all users, ordered by most recently joined.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
< / code > < / pre >
< hr / >
2016-07-14 15:05:57 +03:00
< h1 id = "alternate-schema-formats" > < a class = "toclink" href = "#alternate-schema-formats" > Alternate schema formats< / a > < / h1 >
< p > In order to support an alternate schema format, you need to implement a custom renderer
class that handles converting a < code > Document< / code > instance into a bytestring representation.< / p >
< p > If there is a Core API codec package that supports encoding into the format you
want to use then implementing the renderer class can be done by using the codec.< / p >
< h2 id = "example" > < a class = "toclink" href = "#example" > Example< / a > < / h2 >
< p > For example, the < code > openapi_codec< / code > package provides support for encoding or decoding
to the Open API ("Swagger") format:< / p >
< pre > < code > from rest_framework import renderers
from openapi_codec import OpenAPICodec
class SwaggerRenderer(renderers.BaseRenderer):
2016-07-28 15:37:14 +03:00
media_type = 'application/openapi+json'
2016-07-14 15:05:57 +03:00
format = 'swagger'
def render(self, data, media_type=None, renderer_context=None):
codec = OpenAPICodec()
2016-07-28 15:37:14 +03:00
return codec.dump(data)
2016-07-14 15:05:57 +03:00
< / code > < / pre >
< hr / >
2016-07-07 11:41:32 +03:00
< h1 id = "api-reference" > < a class = "toclink" href = "#api-reference" > API Reference< / a > < / h1 >
< h2 id = "schemagenerator" > < a class = "toclink" href = "#schemagenerator" > SchemaGenerator< / a > < / h2 >
< p > A class that deals with introspecting your API views, which can be used to
generate a schema.< / p >
< p > Typically you'll instantiate < code > SchemaGenerator< / code > with a single argument, like so:< / p >
< pre > < code > generator = SchemaGenerator(title='Stock Prices API')
< / code > < / pre >
< p > Arguments:< / p >
< ul >
2016-10-20 18:31:37 +03:00
< li > < code > title< / code > < strong > required< / strong > - The name of the API.< / li >
2016-07-28 15:37:14 +03:00
< li > < code > url< / code > - The root URL of the API schema. This option is not required unless the schema is included under path prefix.< / li >
2016-07-07 11:41:32 +03:00
< li > < code > patterns< / code > - A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.< / li >
< li > < code > urlconf< / code > - A URL conf module name to use when generating the schema. Defaults to < code > settings.ROOT_URLCONF< / code > .< / li >
< / ul >
2016-10-20 18:31:37 +03:00
< h3 id = "get_schemaself-request" > < a class = "toclink" href = "#get_schemaself-request" > get_schema(self, request)< / a > < / h3 >
2016-07-07 11:41:32 +03:00
< p > Returns a < code > coreapi.Document< / code > instance that represents the API schema.< / p >
< pre > < code > @api_view
@renderer_classes([renderers.CoreJSONRenderer])
def schema_view(request):
2016-07-18 18:23:30 +03:00
generator = schemas.SchemaGenerator(title='Bookings API')
return Response(generator.get_schema())
2016-07-07 11:41:32 +03:00
< / code > < / pre >
2016-10-20 18:31:37 +03:00
< p > The < code > request< / code > argument is optional, and may be used if you want to apply per-user
permissions to the resulting schema generation.< / p >
< h3 id = "get_linksself-request" > < a class = "toclink" href = "#get_linksself-request" > get_links(self, request)< / a > < / h3 >
< p > Return a nested dictionary containing all the links that should be included in the API schema.< / p >
< p > This is a good point to override if you want to modify the resulting structure of the generated schema,
as you can build a new dictionary with a different layout.< / p >
< h3 id = "get_linkself-path-method-view" > < a class = "toclink" href = "#get_linkself-path-method-view" > get_link(self, path, method, view)< / a > < / h3 >
< p > Returns a < code > coreapi.Link< / code > instance corresponding to the given view.< / p >
< p > You can override this if you need to provide custom behaviors for particular views.< / p >
< h3 id = "get_descriptionself-path-method-view" > < a class = "toclink" href = "#get_descriptionself-path-method-view" > get_description(self, path, method, view)< / a > < / h3 >
< p > Returns a string to use as the link description. By default this is based on the
view docstring as described in the "Schemas as Documentation" section above.< / p >
< h3 id = "get_encodingself-path-method-view" > < a class = "toclink" href = "#get_encodingself-path-method-view" > get_encoding(self, path, method, view)< / a > < / h3 >
< p > Returns a string to indicate the encoding for any request body, when interacting
with the given view. Eg. < code > 'application/json'< / code > . May return a blank string for views
that do not expect a request body.< / p >
< h3 id = "get_path_fieldsself-path-method-view" > < a class = "toclink" href = "#get_path_fieldsself-path-method-view" > get_path_fields(self, path, method, view):< / a > < / h3 >
< p > Return a list of < code > coreapi.Link()< / code > instances. One for each path parameter in the URL.< / p >
< h3 id = "get_serializer_fieldsself-path-method-view" > < a class = "toclink" href = "#get_serializer_fieldsself-path-method-view" > get_serializer_fields(self, path, method, view)< / a > < / h3 >
< p > Return a list of < code > coreapi.Link()< / code > instances. One for each field in the serializer class used by the view.< / p >
< h3 id = "get_pagination_fieldsself-path-method-view" > < a class = "toclink" href = "#get_pagination_fieldsself-path-method-view" > get_pagination_fields(self, path, method, view< / a > < / h3 >
< p > Return a list of < code > coreapi.Link()< / code > instances, as returned by the < code > get_schema_fields()< / code > method on any pagination class used by the view.< / p >
< h3 id = "get_filter_fieldsself-path-method-view" > < a class = "toclink" href = "#get_filter_fieldsself-path-method-view" > get_filter_fields(self, path, method, view)< / a > < / h3 >
< p > Return a list of < code > coreapi.Link()< / code > instances, as returned by the < code > get_schema_fields()< / code > method of any filter classes used by the view.< / p >
2016-07-07 11:41:32 +03:00
< hr / >
< h2 id = "core-api" > < a class = "toclink" href = "#core-api" > Core API< / a > < / h2 >
< p > This documentation gives a brief overview of the components within the < code > coreapi< / code >
package that are used to represent an API schema.< / p >
< p > Note that these classes are imported from the < code > coreapi< / code > package, rather than
from the < code > rest_framework< / code > package.< / p >
< h3 id = "document" > < a class = "toclink" href = "#document" > Document< / a > < / h3 >
< p > Represents a container for the API schema.< / p >
2016-10-14 16:33:49 +03:00
< h4 id = "title_1" > < a class = "toclink" href = "#title_1" > < code > title< / code > < / a > < / h4 >
2016-07-07 11:41:32 +03:00
< p > A name for the API.< / p >
2016-10-14 16:33:49 +03:00
< h4 id = "url_1" > < a class = "toclink" href = "#url_1" > < code > url< / code > < / a > < / h4 >
2016-07-07 11:41:32 +03:00
< p > A canonical URL for the API.< / p >
< h4 id = "content" > < a class = "toclink" href = "#content" > < code > content< / code > < / a > < / h4 >
< p > A dictionary, containing the < code > Link< / code > objects that the schema contains.< / p >
< p > In order to provide more structure to the schema, the < code > content< / code > dictionary
may be nested, typically to a second level. For example:< / p >
< pre > < code > content={
"bookings": {
"list": Link(...),
"create": Link(...),
...
},
"venues": {
"list": Link(...),
...
},
...
}
< / code > < / pre >
< h3 id = "link" > < a class = "toclink" href = "#link" > Link< / a > < / h3 >
< p > Represents an individual API endpoint.< / p >
2016-10-14 16:33:49 +03:00
< h4 id = "url_2" > < a class = "toclink" href = "#url_2" > < code > url< / code > < / a > < / h4 >
2016-07-07 11:41:32 +03:00
< p > The URL of the endpoint. May be a URI template, such as < code > /users/{username}/< / code > .< / p >
< h4 id = "action" > < a class = "toclink" href = "#action" > < code > action< / code > < / a > < / h4 >
< p > The HTTP method associated with the endpoint. Note that URLs that support
more than one HTTP method, should correspond to a single < code > Link< / code > for each.< / p >
< h4 id = "fields" > < a class = "toclink" href = "#fields" > < code > fields< / code > < / a > < / h4 >
< p > A list of < code > Field< / code > instances, describing the available parameters on the input.< / p >
< h4 id = "description" > < a class = "toclink" href = "#description" > < code > description< / code > < / a > < / h4 >
< p > A short description of the meaning and intended usage of the endpoint.< / p >
< h3 id = "field" > < a class = "toclink" href = "#field" > Field< / a > < / h3 >
< p > Represents a single input parameter on a given API endpoint.< / p >
< h4 id = "name" > < a class = "toclink" href = "#name" > < code > name< / code > < / a > < / h4 >
< p > A descriptive name for the input.< / p >
< h4 id = "required" > < a class = "toclink" href = "#required" > < code > required< / code > < / a > < / h4 >
< p > A boolean, indicated if the client is required to included a value, or if
the parameter can be omitted.< / p >
< h4 id = "location" > < a class = "toclink" href = "#location" > < code > location< / code > < / a > < / h4 >
< p > Determines how the information is encoded into the request. Should be one of
the following strings:< / p >
< p > < strong > "path"< / strong > < / p >
< p > Included in a templated URI. For example a < code > url< / code > value of < code > /products/{product_code}/< / code > could be used together with a < code > "path"< / code > field, to handle API inputs in a URL path such as < code > /products/slim-fit-jeans/< / code > .< / p >
2016-12-09 19:07:34 +03:00
< p > These fields will normally correspond with < a href = "https://docs.djangoproject.com/en/stable/topics/http/urls/#named-groups" > named arguments in the project URL conf< / a > .< / p >
2016-07-07 11:41:32 +03:00
< p > < strong > "query"< / strong > < / p >
< p > Included as a URL query parameter. For example < code > ?search=sale< / code > . Typically for < code > GET< / code > requests.< / p >
< p > These fields will normally correspond with pagination and filtering controls on a view.< / p >
< p > < strong > "form"< / strong > < / p >
< p > Included in the request body, as a single item of a JSON object or HTML form. For example < code > {"colour": "blue", ...}< / code > . Typically for < code > POST< / code > , < code > PUT< / code > and < code > PATCH< / code > requests. Multiple < code > "form"< / code > fields may be included on a single link.< / p >
< p > These fields will normally correspond with serializer fields on a view.< / p >
< p > < strong > "body"< / strong > < / p >
< p > Included as the complete request body. Typically for < code > POST< / code > , < code > PUT< / code > and < code > PATCH< / code > requests. No more than one < code > "body"< / code > field may exist on a link. May not be used together with < code > "form"< / code > fields.< / p >
< p > These fields will normally correspond with views that use < code > ListSerializer< / code > to validate the request input, or with file upload views.< / p >
< h4 id = "encoding" > < a class = "toclink" href = "#encoding" > < code > encoding< / code > < / a > < / h4 >
< p > < strong > "application/json"< / strong > < / p >
< p > JSON encoded request content. Corresponds to views using < code > JSONParser< / code > .
Valid only if either one or more < code > location="form"< / code > fields, or a single
< code > location="body"< / code > field is included on the < code > Link< / code > .< / p >
< p > < strong > "multipart/form-data"< / strong > < / p >
< p > Multipart encoded request content. Corresponds to views using < code > MultiPartParser< / code > .
Valid only if one or more < code > location="form"< / code > fields is included on the < code > Link< / code > .< / p >
< p > < strong > "application/x-www-form-urlencoded"< / strong > < / p >
< p > URL encoded request content. Corresponds to views using < code > FormParser< / code > . Valid
only if one or more < code > location="form"< / code > fields is included on the < code > Link< / code > .< / p >
< p > < strong > "application/octet-stream"< / strong > < / p >
< p > Binary upload request content. Corresponds to views using < code > FileUploadParser< / code > .
Valid only if a < code > location="body"< / code > field is included on the < code > Link< / code > .< / p >
< h4 id = "description_1" > < a class = "toclink" href = "#description_1" > < code > description< / code > < / a > < / h4 >
< p > A short description of the meaning and intended usage of the input field.< / p >
< / div > <!-- /span -->
< / div > <!-- /row -->
< / div > <!-- /.fluid - container -->
< / div > <!-- /.body content -->
< div id = "push" > < / div >
< / div > <!-- /.wrapper -->
< footer class = "span12" >
< p > Documentation built with < a href = "http://www.mkdocs.org/" > MkDocs< / a > .
< / p >
< / footer >
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
< script src = "../../js/jquery-1.8.1-min.js" > < / script >
< script src = "../../js/prettify-1.0.js" > < / script >
< script src = "../../js/bootstrap-2.1.1-min.js" > < / script >
< script src = "https://fund.django-rest-framework.org/sidebar_include.js" > < / script >
< script > var base _url = '../..' ; < / script >
< script src = "../../mkdocs/js/require.js" > < / script >
< script src = "../../js/theme.js" > < / script >
< script >
var shiftWindow = function() {
scrollBy(0, -50)
};
if (location.hash) shiftWindow();
window.addEventListener("hashchange", shiftWindow);
$('.dropdown-menu').on('click touchstart', function(event) {
event.stopPropagation();
});
// Dynamically force sidenav/dropdown to no higher than browser window
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
$(function() {
$(window).resize(function() {
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
});
});
< / script >
< / body >
< / html >