Debian Codegraph @

docs/api-guide/renderers.md

raw
1 ---
2 source:
3 - renderers.py
4 ---
5
6 # Renderers
7
8 > 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.
9 >
10 > — [Django documentation][cite]
11
12 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.
13
14 ## How the renderer is determined
15
16 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.
17
18 The basic process of content negotiation involves examining the request's `Accept` 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 `http://example.com/api/users_count.json` might be an endpoint that always returns JSON data.
19
20 For more information see the documentation on [content negotiation][conneg].
21
22 ## Setting the renderers
23
24 The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CLASSES` setting. For example, the following settings would use `JSON` as the main media type and also include the self describing API.
25
26 REST_FRAMEWORK = {
27 'DEFAULT_RENDERER_CLASSES': [
28 'rest_framework.renderers.JSONRenderer',
29 'rest_framework.renderers.BrowsableAPIRenderer',
30 ]
31 }
32
33 You can also set the renderers used for an individual view, or viewset,
34 using the `APIView` class-based views.
35
36 from django.contrib.auth.models import User
37 from rest_framework.renderers import JSONRenderer
38 from rest_framework.response import Response
39 from rest_framework.views import APIView
40
41 class UserCountView(APIView):
42 """
43 A view that returns the count of active users in JSON.
44 """
45 renderer_classes = [JSONRenderer]
46
47 def get(self, request, format=None):
48 user_count = User.objects.filter(active=True).count()
49 content = {'user_count': user_count}
50 return Response(content)
51
52 Or, if you're using the `@api_view` decorator with function based views.
53
54 @api_view(['GET'])
55 @renderer_classes([JSONRenderer])
56 def user_count_view(request, format=None):
57 """
58 A view that returns the count of active users in JSON.
59 """
60 user_count = User.objects.filter(active=True).count()
61 content = {'user_count': user_count}
62 return Response(content)
63
64 ## Ordering of renderer classes
65
66 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 `Accept: */*` header, or not including an `Accept` header at all, then REST framework will select the first renderer in the list to use for the response.
67
68 For example if your API serves JSON responses and the HTML browsable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header.
69
70 If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making `TemplateHTMLRenderer` your default renderer, in order to play nicely with older browsers that send [broken accept headers][browser-accept-headers].
71
72 ---
73
74 ## API Reference
75
76 ### JSONRenderer
77
78 Renders the request data into `JSON`, using utf-8 encoding.
79
80 Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace:
81
82 {"unicode black star":"★","value":999}
83
84 The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`.
85
86 {
87 "unicode black star": "★",
88 "value": 999
89 }
90
91 The default JSON encoding style can be altered using the `UNICODE_JSON` and `COMPACT_JSON` settings keys.
92
93 **.media_type**: `application/json`
94
95 **.format**: `'json'`
96
97 **.charset**: `None`
98
99 ### TemplateHTMLRenderer
100
101 Renders data to HTML, using Django's standard template rendering.
102 Unlike other renderers, the data passed to the `Response` does not need to be serialized. Also, unlike other renderers, you may want to include a `template_name` argument when creating the `Response`.
103
104 The TemplateHTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context.
105
106 !!! note
107 When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the `TemplateHTMLRenderer` to render it. For example:
108
109 response.data = {'results': response.data}
110
111 The template name is determined by (in order of preference):
112
113 1. An explicit `template_name` argument passed to the response.
114 2. An explicit `.template_name` attribute set on this class.
115 3. The return result of calling `view.get_template_names()`.
116
117 An example of a view that uses `TemplateHTMLRenderer`:
118
119 class UserDetail(generics.RetrieveAPIView):
120 """
121 A view that returns a templated HTML representation of a given user.
122 """
123 queryset = User.objects.all()
124 renderer_classes = [TemplateHTMLRenderer]
125
126 def get(self, request, *args, **kwargs):
127 self.object = self.get_object()
128 return Response({'user': self.object}, template_name='user_detail.html')
129
130 You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
131
132 If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritized first even for browsers that send poorly formed `ACCEPT:` headers.
133
134 See the [_HTML & Forms_ Topic Page][html-and-forms] for further examples of `TemplateHTMLRenderer` usage.
135
136 **.media_type**: `text/html`
137
138 **.format**: `'html'`
139
140 **.charset**: `utf-8`
141
142 See also: `StaticHTMLRenderer`
143
144 ### StaticHTMLRenderer
145
146 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.
147
148 An example of a view that uses `StaticHTMLRenderer`:
149
150 @api_view(['GET'])
151 @renderer_classes([StaticHTMLRenderer])
152 def simple_html_view(request):
153 data = '<html><body><h1>Hello, world</h1></body></html>'
154 return Response(data)
155
156 You can use `StaticHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
157
158 **.media_type**: `text/html`
159
160 **.format**: `'html'`
161
162 **.charset**: `utf-8`
163
164 See also: `TemplateHTMLRenderer`
165
166 ### BrowsableAPIRenderer
167
168 Renders data into HTML for the Browsable API:
169
170 ![The BrowsableAPIRenderer](../img/quickstart.png)
171
172 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.
173
174 It also renders an HTML form for each method the view allows, which involves calling back into the view with the request method overridden. See [form rendering][browsable-api-form-rendering] for the implications of this.
175
176 **.media_type**: `text/html`
177
178 **.format**: `'api'`
179
180 **.charset**: `utf-8`
181
182 **.template**: `'rest_framework/api.html'`
183
184 #### Customizing BrowsableAPIRenderer
185
186 By default the response content will be rendered with the highest priority renderer apart from `BrowsableAPIRenderer`. 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 `get_default_renderer()` method. For example:
187
188 class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
189 def get_default_renderer(self, view):
190 return JSONRenderer()
191
192 ### AdminRenderer
193
194 Renders data into HTML for an admin-like display:
195
196 ![The AdminRender view](../img/admin.png)
197
198 This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data.
199
200 Note that views that have nested or list serializers for their input won't work well with the `AdminRenderer`, as the HTML forms are unable to properly support them.
201
202 !!! note
203 The `AdminRenderer` is only able to include links to detail pages when a properly configured `URL_FIELD_NAME` (`url` by default) attribute is present in the data. For `HyperlinkedModelSerializer` this will be the case, but for `ModelSerializer` or plain `Serializer` classes you'll need to make sure to include the field explicitly.
204
205 For example here we use models `get_absolute_url` method:
206
207 class AccountSerializer(serializers.ModelSerializer):
208 url = serializers.CharField(source='get_absolute_url', read_only=True)
209
210 class Meta:
211 model = Account
212
213
214 **.media_type**: `text/html`
215
216 **.format**: `'admin'`
217
218 **.charset**: `utf-8`
219
220 **.template**: `'rest_framework/admin.html'`
221
222 ### HTMLFormRenderer
223
224 Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing `<form>` tags, a hidden CSRF input or any submit buttons.
225
226 This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the `render_form` template tag.
227
228 {% load rest_framework %}
229
230 <form action="/submit-report/" method="post">
231 {% csrf_token %}
232 {% render_form serializer %}
233 <input type="submit" value="Save" />
234 </form>
235
236 For more information see the [HTML & Forms][html-and-forms] documentation.
237
238 **.media_type**: `text/html`
239
240 **.format**: `'form'`
241
242 **.charset**: `utf-8`
243
244 **.template**: `'rest_framework/horizontal/form.html'`
245
246 ### MultiPartRenderer
247
248 This renderer is used for rendering HTML multipart form data. **It is not suitable as a response renderer**, but is instead used for creating test requests, using REST framework's [test client and test request factory][testing].
249
250 **.media_type**: `multipart/form-data; boundary=BoUnDaRyStRiNg`
251
252 **.format**: `'multipart'`
253
254 **.charset**: `utf-8`
255
256 ---
257
258 ## Custom renderers
259
260 To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, accepted_media_type=None, renderer_context=None)` method.
261
262 The method should return a bytestring, which will be used as the body of the HTTP response.
263
264 The arguments passed to the `.render()` method are:
265
266 - `data`: the request data, as set by the `Response()` instantiation.
267
268 - `accepted_media_type=None`: optional. If provided, this is the accepted media type, as determined by the content negotiation stage. Depending on the client's `Accept:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"application/json; nested=true"`.
269
270 - `renderer_context=None`: optional. If provided, this is a dictionary of contextual information provided by the view. By default this will include the following keys: `view`, `request`, `response`, `args`, `kwargs`.
271
272 ### Example
273
274 The following is an example plaintext renderer that will return a response with the `data` parameter as the content of the response.
275
276 from django.utils.encoding import smart_str
277 from rest_framework import renderers
278
279
280 class PlainTextRenderer(renderers.BaseRenderer):
281 media_type = 'text/plain'
282 format = 'txt'
283
284 def render(self, data, accepted_media_type=None, renderer_context=None):
285 return smart_str(data, encoding=self.charset)
286
287 ### Setting the character set
288
289 By default renderer classes are assumed to be using the `UTF-8` encoding. To use a different encoding, set the `charset` attribute on the renderer.
290
291 class PlainTextRenderer(renderers.BaseRenderer):
292 media_type = 'text/plain'
293 format = 'txt'
294 charset = 'iso-8859-1'
295
296 def render(self, data, accepted_media_type=None, renderer_context=None):
297 return data.encode(self.charset)
298
299 Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the `Response` class, with the `charset` attribute set on the renderer used to determine the encoding.
300
301 If the renderer returns a bytestring representing raw binary content, you should set a charset value of `None`, which will ensure the `Content-Type` header of the response will not have a `charset` value set.
302
303 In some cases you may also want to set the `render_style` attribute to `'binary'`. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string.
304
305 class JPEGRenderer(renderers.BaseRenderer):
306 media_type = 'image/jpeg'
307 format = 'jpg'
308 charset = None
309 render_style = 'binary'
310
311 def render(self, data, accepted_media_type=None, renderer_context=None):
312 return data
313
314 ---
315
316 ## Advanced renderer usage
317
318 You can do some pretty flexible things using REST framework's renderers. Some examples...
319
320 * Provide either flat or nested representations from the same endpoint, depending on the requested media type.
321 * Serve both regular HTML webpages, and JSON based API responses from the same endpoints.
322 * Specify multiple types of HTML representation for API clients to use.
323 * Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
324
325 ### Varying behavior by media type
326
327 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 `request.accepted_renderer` to determine the negotiated renderer that will be used for the response.
328
329 For example:
330
331 @api_view(['GET'])
332 @renderer_classes([TemplateHTMLRenderer, JSONRenderer])
333 def list_users(request):
334 """
335 A view that can return JSON or HTML representations
336 of the users in the system.
337 """
338 queryset = Users.objects.filter(active=True)
339
340 if request.accepted_renderer.format == 'html':
341 # TemplateHTMLRenderer takes a context dict,
342 # and additionally requires a 'template_name'.
343 # It does not require serialization.
344 data = {'users': queryset}
345 return Response(data, template_name='list_users.html')
346
347 # JSONRenderer requires serialized data as normal.
348 serializer = UserSerializer(instance=queryset)
349 data = serializer.data
350 return Response(data)
351
352 ### Underspecifying the media type
353
354 In some cases you might want a renderer to serve a range of media types.
355 In this case you can underspecify the media types it should respond to, by using a `media_type` value such as `image/*`, or `*/*`.
356
357 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 `content_type` attribute. For example:
358
359 return Response(data, content_type='image/png')
360
361 ### Designing your media types
362
363 For the purposes of many Web APIs, simple `JSON` responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and [HATEOAS] you'll need to consider the design and usage of your media types in more detail.
364
365 In [the words of Roy Fielding][quote], "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.".
366
367 For good examples of custom media types, see GitHub's use of a custom [application/vnd.github+json] media type, and Mike Amundsen's IANA approved [application/vnd.collection+json] JSON-based hypermedia.
368
369 ### HTML error views
370
371 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 `Http404` or `PermissionDenied` exception, or a subclass of `APIException`.
372
373 If you're using either the `TemplateHTMLRenderer` or the `StaticHTMLRenderer` and an exception is raised, the behavior is slightly different, and mirrors [Django's default handling of error views][django-error-views].
374
375 Exceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence.
376
377 * Load and render a template named `{status_code}.html`.
378 * Load and render a template named `api_exception.html`.
379 * Render the HTTP status code and text, for example "404 Not Found".
380
381 Templates will render with a `RequestContext` which includes the `status_code` and `details` keys.
382
383 !!! note
384 If `DEBUG=True`, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text.
385
386 ## Third party packages
387
388 The following third party packages are also available.
389
390 ### YAML
391
392 [REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
393
394 #### Installation & configuration
395
396 Install using pip.
397
398 $ pip install djangorestframework-yaml
399
400 Modify your REST framework settings.
401
402 REST_FRAMEWORK = {
403 'DEFAULT_PARSER_CLASSES': [
404 'rest_framework_yaml.parsers.YAMLParser',
405 ],
406 'DEFAULT_RENDERER_CLASSES': [
407 'rest_framework_yaml.renderers.YAMLRenderer',
408 ],
409 }
410
411 ### XML
412
413 [REST Framework XML][rest-framework-xml] 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.
414
415 #### Installation & configuration
416
417 Install using pip.
418
419 $ pip install djangorestframework-xml
420
421 Modify your REST framework settings.
422
423 REST_FRAMEWORK = {
424 'DEFAULT_PARSER_CLASSES': [
425 'rest_framework_xml.parsers.XMLParser',
426 ],
427 'DEFAULT_RENDERER_CLASSES': [
428 'rest_framework_xml.renderers.XMLRenderer',
429 ],
430 }
431
432 ### JSONP
433
434 [REST framework JSONP][rest-framework-jsonp] provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
435
436 !!! warning
437 If you require cross-domain AJAX requests, you should generally be using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details.
438
439 The `jsonp` approach is essentially a browser hack, and is [only appropriate for globally readable API endpoints][jsonp-security], where `GET` requests are unauthenticated and do not require any user permissions.
440
441 #### Installation & configuration
442
443 Install using pip.
444
445 $ pip install djangorestframework-jsonp
446
447 Modify your REST framework settings.
448
449 REST_FRAMEWORK = {
450 'DEFAULT_RENDERER_CLASSES': [
451 'rest_framework_jsonp.renderers.JSONPRenderer',
452 ],
453 }
454
455 ### MessagePack
456
457 [MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
458
459 ### Microsoft Excel: XLSX (Binary Spreadsheet Endpoints)
460
461 XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-excel][drf-excel], 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.
462
463 #### Installation & configuration
464
465 Install using pip.
466
467 $ pip install drf-excel
468
469 Modify your REST framework settings.
470
471 REST_FRAMEWORK = {
472 ...
473
474 'DEFAULT_RENDERER_CLASSES': [
475 'rest_framework.renderers.JSONRenderer',
476 'rest_framework.renderers.BrowsableAPIRenderer',
477 'drf_excel.renderers.XLSXRenderer',
478 ],
479 }
480
481 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 `Content-Disposition` header. If no filename is provided, it will default to `export.xlsx`. For example:
482
483 from rest_framework.viewsets import ReadOnlyModelViewSet
484 from drf_excel.mixins import XLSXFileMixin
485 from drf_excel.renderers import XLSXRenderer
486
487 from .models import MyExampleModel
488 from .serializers import MyExampleSerializer
489
490 class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):
491 queryset = MyExampleModel.objects.all()
492 serializer_class = MyExampleSerializer
493 renderer_classes = [XLSXRenderer]
494 filename = 'my_export.xlsx'
495
496 ### CSV
497
498 Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework.
499
500 ### UltraJSON
501
502 [UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Adam Mertz][Amertz08] maintains [drf_ujson2][drf_ujson2], a fork of the now unmaintained [drf-ujson-renderer][drf-ujson-renderer], which implements JSON rendering using the UJSON package.
503
504 ### CamelCase JSON
505
506 [djangorestframework-camel-case] 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 [Vitaly Babiy][vbabiy].
507
508 ### Pandas (CSV, Excel, PNG)
509
510 [Django REST Pandas] provides a serializer and renderers that support additional data processing and output via the [Pandas] DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both `.xls` and `.xlsx`), and a number of [other formats]. It is maintained by [S. Andrew Sheppard][sheppard] as part of the [wq Project][wq].
511
512 ### LaTeX
513
514 [Rest Framework Latex] provides a renderer that outputs PDFs using Lualatex. It is maintained by [Pebble (S/F Software)][mypebble].
515
516
517 [cite]: https://docs.djangoproject.com/en/stable/ref/template-response/#the-rendering-process
518 [browsable-api-form-rendering]: ../topics/browsable-api.md#form-rendering
519 [conneg]: content-negotiation.md
520 [html-and-forms]: ../topics/html-and-forms.md
521 [browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers
522 [testing]: testing.md
523 [HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas
524 [quote]: https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
525 [application/vnd.github+json]: https://developer.github.com/v3/media/
526 [application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/
527 [django-error-views]: https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views
528 [rest-framework-jsonp]: https://jpadilla.github.io/django-rest-framework-jsonp/
529 [cors]: https://www.w3.org/TR/cors/
530 [cors-docs]: https://www.django-rest-framework.org/topics/ajax-csrf-cors/
531 [jsonp-security]: https://stackoverflow.com/questions/613962/is-jsonp-safe-to-use
532 [rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
533 [rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
534 [messagepack]: https://msgpack.org/
535 [juanriaza]: https://github.com/juanriaza
536 [mjumbewu]: https://github.com/mjumbewu
537 [flipperpa]: https://github.com/flipperpa
538 [wharton]: https://github.com/wharton
539 [drf-excel]: https://github.com/wharton/drf-excel
540 [vbabiy]: https://github.com/vbabiy
541 [rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
542 [rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
543 [yaml]: http://www.yaml.org/
544 [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
545 [djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
546 [ultrajson]: https://github.com/esnme/ultrajson
547 [Amertz08]: https://github.com/Amertz08
548 [drf-ujson-renderer]: https://github.com/gizmag/drf-ujson-renderer
549 [drf_ujson2]: https://github.com/Amertz08/drf_ujson2
550 [djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
551 [Django REST Pandas]: https://github.com/wq/django-rest-pandas
552 [Pandas]: https://pandas.pydata.org/
553 [other formats]: https://github.com/wq/django-rest-pandas#supported-formats
554 [sheppard]: https://github.com/sheppard
555 [wq]: https://github.com/wq
556 [mypebble]: https://github.com/mypebble
557 [Rest Framework Latex]: https://github.com/mypebble/rest-framework-latex