<p>Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client.</p>
<p>REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types.</p>
<p>The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request.</p>
<p>The basic process of content negotiation involves examining the request's <code>Accept</code> header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL <code>http://example.com/api/users_count.json</code> might be an endpoint that always returns JSON data.</p>
<p>The default set of renderers may be set globally, using the <code>DEFAULT_RENDERER_CLASSES</code> setting. For example, the following settings would use <code>JSON</code> as the main media type and also include the self describing API.</p>
<p>It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an <code>Accept: */*</code> header, or not including an <code>Accept</code> header at all, then REST framework will select the first renderer in the list to use for the response.</p>
<p>For example if your API serves JSON responses and the HTML browsable API, you might want to make <code>JSONRenderer</code> your default renderer, in order to send <code>JSON</code> responses to clients that do not specify an <code>Accept</code> header.</p>
<p>If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making <code>TemplateHTMLRenderer</code> your default renderer, in order to play nicely with older browsers that send <ahref="http://www.gethifi.com/blog/browser-rest-http-accept-headers">broken accept headers</a>.</p>
<p>The client may additionally include an <code>'indent'</code> media type parameter, in which case the returned <code>JSON</code> will be indented. For example <code>Accept: application/json; indent=4</code>.</p>
<p>Renders data to HTML, using Django's standard template rendering.
Unlike other renderers, the data passed to the <code>Response</code> does not need to be serialized. Also, unlike other renderers, you may want to include a <code>template_name</code> argument when creating the <code>Response</code>.</p>
<p>The TemplateHTMLRenderer will create a <code>RequestContext</code>, using the <code>response.data</code> as the context dict, and determine a template name to use to render the context.</p>
<p>The template name is determined by (in order of preference):</p>
<ol>
<li>An explicit <code>template_name</code> argument passed to the response.</li>
<li>An explicit <code>.template_name</code> attribute set on this class.</li>
<li>The return result of calling <code>view.get_template_names()</code>.</li>
</ol>
<p>An example of a view that uses <code>TemplateHTMLRenderer</code>:</p>
<p>You can use <code>TemplateHTMLRenderer</code> either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.</p>
<p>If you're building websites that use <code>TemplateHTMLRenderer</code> along with other renderer classes, you should consider listing <code>TemplateHTMLRenderer</code> as the first class in the <code>renderer_classes</code> list, so that it will be prioritised first even for browsers that send poorly formed <code>ACCEPT:</code> headers.</p>
<p>See the <ahref="../../topics/html-and-forms/"><em>HTML & Forms</em> Topic Page</a> for further examples of <code>TemplateHTMLRenderer</code> usage.</p>
<p>A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned.</p>
<p>You can use <code>StaticHTMLRenderer</code> either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.</p>
<p>This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.</p>
<p>By default the response content will be rendered with the highest priority renderer apart from <code>BrowsableAPIRenderer</code>. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the <code>get_default_renderer()</code> method. For example:</p>
<p>This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data.</p>
<p>Note that views that have nested or list serializers for their input won't work well with the <code>AdminRenderer</code>, as the HTML forms are unable to properly support them.</p>
<p><strong>Note</strong>: The <code>AdminRenderer</code> is only able to include links to detail pages when a properly configured <code>URL_FIELD_NAME</code> (<code>url</code> by default) attribute is present in the data. For <code>HyperlinkedModelSerializer</code> this will be the case, but for <code>ModelSerializer</code> or plain <code>Serializer</code> classes you'll need to make sure to include the field explicitly. For example here we use models <code>get_absolute_url</code> method:</p>
<p>Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing <code><form></code> tags, a hidden CSRF input or any submit buttons.</p>
<p>This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the <code>render_form</code> template tag.</p>
<p>This renderer is used for rendering HTML multipart form data. <strong>It is not suitable as a response renderer</strong>, but is instead used for creating test requests, using REST framework's <ahref="../testing/">test client and test request factory</a>.</p>
<p>To implement a custom renderer, you should override <code>BaseRenderer</code>, set the <code>.media_type</code> and <code>.format</code> properties, and implement the <code>.render(self, data, media_type=None, renderer_context=None)</code> method.</p>
<p>The method should return a bytestring, which will be used as the body of the HTTP response.</p>
<p>The arguments passed to the <code>.render()</code> method are:</p>
<p>Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.</p>
<p>Depending on the client's <code>Accept:</code> header, this may be more specific than the renderer's <code>media_type</code> attribute, and may include media type parameters. For example <code>"application/json; nested=true"</code>.</p>
<p>Optional. If provided, this is a dictionary of contextual information provided by the view.</p>
<p>By default this will include the following keys: <code>view</code>, <code>request</code>, <code>response</code>, <code>args</code>, <code>kwargs</code>.</p>
<p>By default renderer classes are assumed to be using the <code>UTF-8</code> encoding. To use a different encoding, set the <code>charset</code> attribute on the renderer.</p>
<p>Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the <code>Response</code> class, with the <code>charset</code> attribute set on the renderer used to determine the encoding.</p>
<p>If the renderer returns a bytestring representing raw binary content, you should set a charset value of <code>None</code>, which will ensure the <code>Content-Type</code> header of the response will not have a <code>charset</code> value set.</p>
<p>In some cases you may also want to set the <code>render_style</code> attribute to <code>'binary'</code>. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string.</p>
<li>Underspecify a renderer's media type, such as using <code>media_type = 'image/*'</code>, and use the <code>Accept</code> header to vary the encoding of the response.</li>
<p>In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access <code>request.accepted_renderer</code> to determine the negotiated renderer that will be used for the response.</p>
<p>In some cases you might want a renderer to serve a range of media types.
In this case you can underspecify the media types it should respond to, by using a <code>media_type</code> value such as <code>image/*</code>, or <code>*/*</code>.</p>
<p>If you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the <code>content_type</code> attribute. For example:</p>
<p>For the purposes of many Web APIs, simple <code>JSON</code> responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and <ahref="http://timelessrepo.com/haters-gonna-hateoas">HATEOAS</a> you'll need to consider the design and usage of your media types in more detail.</p>
<p>In <ahref="https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven">the words of Roy Fielding</a>, "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.".</p>
<p>For good examples of custom media types, see GitHub's use of a custom <ahref="https://developer.github.com/v3/media/">application/vnd.github+json</a> media type, and Mike Amundsen's IANA approved <ahref="http://www.amundsen.com/media-types/collection/">application/vnd.collection+json</a> JSON-based hypermedia.</p>
<p>Typically a renderer will behave the same regardless of if it's dealing with a regular response, or with a response caused by an exception being raised, such as an <code>Http404</code> or <code>PermissionDenied</code> exception, or a subclass of <code>APIException</code>.</p>
<p>If you're using either the <code>TemplateHTMLRenderer</code> or the <code>StaticHTMLRenderer</code> and an exception is raised, the behavior is slightly different, and mirrors <ahref="https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views">Django's default handling of error views</a>.</p>
<p>Exceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence.</p>
<ul>
<li>Load and render a template named <code>{status_code}.html</code>.</li>
<li>Load and render a template named <code>api_exception.html</code>.</li>
<li>Render the HTTP status code and text, for example "404 Not Found".</li>
</ul>
<p>Templates will render with a <code>RequestContext</code> which includes the <code>status_code</code> and <code>details</code> keys.</p>
<p><strong>Note</strong>: If <code>DEBUG=True</code>, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text.</p>
<p><ahref="https://jpadilla.github.io/django-rest-framework-yaml/">REST framework YAML</a> provides <ahref="http://www.yaml.org/">YAML</a> parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.</p>
<p><ahref="https://jpadilla.github.io/django-rest-framework-xml/">REST Framework XML</a> provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.</p>
<p><ahref="https://jpadilla.github.io/django-rest-framework-jsonp/">REST framework JSONP</a> provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.</p>
<p><strong>Warning</strong>: If you require cross-domain AJAX requests, you should generally be using the more modern approach of <ahref="https://www.w3.org/TR/cors/">CORS</a> as an alternative to <code>JSONP</code>. See the <ahref="https://www.django-rest-framework.org/topics/ajax-csrf-cors/">CORS documentation</a> for more details.</p>
<p>The <code>jsonp</code> approach is essentially a browser hack, and is <ahref="https://stackoverflow.com/questions/613962/is-jsonp-safe-to-use">only appropriate for globally readable API endpoints</a>, where <code>GET</code> requests are unauthenticated and do not require any user permissions.</p>
<p><ahref="https://msgpack.org/">MessagePack</a> is a fast, efficient binary serialization format. <ahref="https://github.com/juanriaza">Juan Riaza</a> maintains the <ahref="https://github.com/juanriaza/django-rest-framework-msgpack">djangorestframework-msgpack</a> package which provides MessagePack renderer and parser support for REST framework.</p>
<p>XLSX is the world's most popular binary spreadsheet format. <ahref="https://github.com/flipperpa">Tim Allen</a> of <ahref="https://github.com/wharton">The Wharton School</a> maintains <ahref="https://github.com/wharton/drf-renderer-xlsx">drf-renderer-xlsx</a>, which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.</p>
<h4id="installation-configuration_3"><aclass="toclink"href="#installation-configuration_3">Installation & configuration</a></h4>
<p>Install using pip.</p>
<pre><code>$ pip install drf-renderer-xlsx
</code></pre>
<p>Modify your REST framework settings.</p>
<pre><code>REST_FRAMEWORK = {
...
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
'drf_renderer_xlsx.renderers.XLSXRenderer',
),
}
</code></pre>
<p>To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the <code>Content-Disposition</code> header. If no filename is provided, it will default to <code>export.xlsx</code>. For example:</p>
<p>Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. <ahref="https://github.com/mjumbewu">Mjumbe Poe</a> maintains the <ahref="https://github.com/mjumbewu/django-rest-framework-csv">djangorestframework-csv</a> package which provides CSV renderer support for REST framework.</p>
<p><ahref="https://github.com/esnme/ultrajson">UltraJSON</a> is an optimized C JSON encoder which can give significantly faster JSON rendering. <ahref="https://github.com/hzy">Jacob Haslehurst</a> maintains the <ahref="https://github.com/gizmag/drf-ujson-renderer">drf-ujson-renderer</a> package which implements JSON rendering using the UJSON package.</p>
<p><ahref="https://github.com/vbabiy/djangorestframework-camel-case">djangorestframework-camel-case</a> provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by <ahref="https://github.com/vbabiy">Vitaly Babiy</a>.</p>
<p><ahref="https://github.com/wq/django-rest-pandas">Django REST Pandas</a> provides a serializer and renderers that support additional data processing and output via the <ahref="https://pandas.pydata.org/">Pandas</a> DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both <code>.xls</code> and <code>.xlsx</code>), and a number of <ahref="https://github.com/wq/django-rest-pandas#supported-formats">other formats</a>. It is maintained by <ahref="https://github.com/sheppard">S. Andrew Sheppard</a> as part of the <ahref="https://github.com/wq">wq Project</a>.</p>
<p><ahref="https://github.com/mypebble/rest-framework-latex">Rest Framework Latex</a> provides a renderer that outputs PDFs using Laulatex. It is maintained by <ahref="https://github.com/mypebble">Pebble (S/F Software)</a>.</p>