Debian Codegraph @

docs/api-guide/parsers.md

raw
1 ---
2 source:
3 - parsers.py
4 ---
5
6 # Parsers
7
8 > Machine interacting web services tend to use more
9 structured formats for sending data than form-encoded, since they're
10 sending more complex data than simple forms
11 >
12 > — Malcom Tredinnick, [Django developers group][cite]
13
14 REST framework includes a number of built-in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.
15
16 ## How the parser is determined
17
18 The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
19
20 !!! note
21 When developing client applications always remember to make sure you're setting the `Content-Type` header when sending data in an HTTP request.
22
23 If you don't set the content type, most clients will default to using `'application/x-www-form-urlencoded'`, which may not be what you want.
24
25 As an example, if you are sending `json` encoded data using jQuery with the [.ajax() method][jquery-ajax], you should make sure to include the `contentType: 'application/json'` setting.
26
27 ## Setting the parsers
28
29 The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow only requests with `JSON` content, instead of the default of JSON or form data.
30
31 REST_FRAMEWORK = {
32 'DEFAULT_PARSER_CLASSES': [
33 'rest_framework.parsers.JSONParser',
34 ]
35 }
36
37 You can also set the parsers used for an individual view, or viewset,
38 using the `APIView` class-based views.
39
40 from rest_framework.parsers import JSONParser
41 from rest_framework.response import Response
42 from rest_framework.views import APIView
43
44 class ExampleView(APIView):
45 """
46 A view that can accept POST requests with JSON content.
47 """
48 parser_classes = [JSONParser]
49
50 def post(self, request, format=None):
51 return Response({'received data': request.data})
52
53 Or, if you're using the `@api_view` decorator with function based views.
54
55 from rest_framework.decorators import api_view
56 from rest_framework.decorators import parser_classes
57 from rest_framework.parsers import JSONParser
58
59 @api_view(['POST'])
60 @parser_classes([JSONParser])
61 def example_view(request, format=None):
62 """
63 A view that can accept POST requests with JSON content.
64 """
65 return Response({'received data': request.data})
66
67 ---
68
69 ## API Reference
70
71 ### JSONParser
72
73 Parses `JSON` request content. `request.data` will be populated with a dictionary of data.
74
75 **.media_type**: `application/json`
76
77 ### FormParser
78
79 Parses HTML form content. `request.data` will be populated with a `QueryDict` of data.
80
81 You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
82
83 **.media_type**: `application/x-www-form-urlencoded`
84
85 ### MultiPartParser
86
87 Parses multipart HTML form content, which supports file uploads. `request.data` and `request.FILES` will be populated with a `QueryDict` and `MultiValueDict` respectively.
88
89 You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
90
91 **.media_type**: `multipart/form-data`
92
93 ### FileUploadParser
94
95 Parses raw file upload content. The `request.data` property will be a dictionary with a single key `'file'` containing the uploaded file.
96
97 If the view used with `FileUploadParser` is called with a `filename` URL keyword argument, then that argument will be used as the filename.
98
99 If it is called without a `filename` URL keyword argument, then the client must set the filename in the `Content-Disposition` HTTP header. For example `Content-Disposition: attachment; filename=upload.jpg`.
100
101 **.media_type**: `*/*`
102
103 !!! note
104
105 * The `FileUploadParser` is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the `MultiPartParser` instead.
106 * Since this parser's `media_type` matches any content type, `FileUploadParser` should generally be the only parser set on an API view.
107 * `FileUploadParser` respects Django's standard `FILE_UPLOAD_HANDLERS` setting, and the `request.upload_handlers` attribute. See the [Django documentation][upload-handlers] for more details.
108
109 #### Basic usage example
110
111 # views.py
112 class FileUploadView(views.APIView):
113 parser_classes = [FileUploadParser]
114
115 def put(self, request, filename, format=None):
116 file_obj = request.data['file']
117 # ...
118 # do some stuff with uploaded file
119 # ...
120 return Response(status=204)
121
122 # urls.py
123 urlpatterns = [
124 # ...
125 re_path(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view())
126 ]
127
128 ---
129
130 ## Custom parsers
131
132 To implement a custom parser, you should override `BaseParser`, set the `.media_type` property, and implement the `.parse(self, stream, media_type, parser_context)` method.
133
134 The method should return the data that will be used to populate the `request.data` property.
135
136 The arguments passed to `.parse()` are:
137
138 ### stream
139
140 A stream-like object representing the body of the request.
141
142 ### media_type
143
144 Optional. If provided, this is the media type of the incoming request content.
145
146 Depending on the request's `Content-Type:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"text/plain; charset=utf-8"`.
147
148 ### parser_context
149
150 Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content.
151
152 By default this will include the following keys: `view`, `request`, `args`, `kwargs`.
153
154 ### Example
155
156 The following is an example plaintext parser that will populate the `request.data` property with a string representing the body of the request.
157
158 class PlainTextParser(BaseParser):
159 """
160 Plain text parser.
161 """
162 media_type = 'text/plain'
163
164 def parse(self, stream, media_type=None, parser_context=None):
165 """
166 Simply return a string representing the body of the request.
167 """
168 return stream.read()
169
170 ---
171
172 ## Third party packages
173
174 The following third party packages are also available.
175
176 ### YAML
177
178 [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.
179
180 #### Installation & configuration
181
182 Install using pip.
183
184 $ pip install djangorestframework-yaml
185
186 Modify your REST framework settings.
187
188 REST_FRAMEWORK = {
189 'DEFAULT_PARSER_CLASSES': [
190 'rest_framework_yaml.parsers.YAMLParser',
191 ],
192 'DEFAULT_RENDERER_CLASSES': [
193 'rest_framework_yaml.renderers.YAMLRenderer',
194 ],
195 }
196
197 ### XML
198
199 [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.
200
201 #### Installation & configuration
202
203 Install using pip.
204
205 $ pip install djangorestframework-xml
206
207 Modify your REST framework settings.
208
209 REST_FRAMEWORK = {
210 'DEFAULT_PARSER_CLASSES': [
211 'rest_framework_xml.parsers.XMLParser',
212 ],
213 'DEFAULT_RENDERER_CLASSES': [
214 'rest_framework_xml.renderers.XMLRenderer',
215 ],
216 }
217
218 ### MessagePack
219
220 [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.
221
222 ### CamelCase JSON
223
224 [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].
225
226 [jquery-ajax]: https://api.jquery.com/jQuery.ajax/
227 [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
228 [upload-handlers]: https://docs.djangoproject.com/en/stable/topics/http/file-uploads/#upload-handlers
229 [rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
230 [rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
231 [yaml]: http://www.yaml.org/
232 [messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
233 [juanriaza]: https://github.com/juanriaza
234 [vbabiy]: https://github.com/vbabiy
235 [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
236 [djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case