| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
 | <a class="github" href="parsers.py"></a>
# Parsers
> Machine interacting web services tend to use more
structured formats for sending data than form-encoded, since they're
sending more complex data than simple forms
>
> — Malcom Tredinnick, [Django developers group][cite]
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 flexiblity to design the media types that your API accepts.
## How the parser is determined
The set of valid parsers for a view is always defined as a list of classes.  When either `request.DATA` or `request.FILES` 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.
## Setting the parsers
The default set of parsers may be set globally, using the `DEFAULT_PARSERS` setting.  For example, the following settings would allow requests with `YAML` content.
    REST_FRAMEWORK = {
        'DEFAULT_PARSERS': (
            'rest_framework.parsers.YAMLParser',
        )
    }
You can also set the renderers used for an individual view, using the `APIView` class based views.
    class ExampleView(APIView):
        """
        A view that can accept POST requests with YAML content.
        """
        parser_classes = (YAMLParser,)
        def post(self, request, format=None):
            return Response({'received data': request.DATA})
Or, if you're using the `@api_view` decorator with function based views.
    @api_view(('POST',)),
    @parser_classes((YAMLParser,))
    def example_view(request, format=None):
        """
        A view that can accept POST requests with YAML content.
        """
        return Response({'received data': request.DATA})
---
# API Reference
## JSONParser
Parses `JSON` request content.
**.media_type**: `application/json`
## YAMLParser
Parses `YAML` request content.
**.media_type**: `application/yaml`
## XMLParser
Parses REST framework's default style of `XML` request content.
Note that the `XML` markup language is used typically used as the base language for more strictly defined domain-specific languages, such as `RSS`, `Atom`, and `XHTML`.
If you are considering using `XML` for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type.
**.media_type**: `application/xml`
## FormParser
Parses HTML form content.  `request.DATA` will be populated with a `QueryDict` of data, `request.FILES` will be populated with an empty `QueryDict` of data.
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
**.media_type**: `application/x-www-form-urlencoded`
## MultiPartParser
Parses multipart HTML form content, which supports file uploads.  Both `request.DATA` and `request.FILES` will be populated with a `QueryDict`.
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
**.media_type**: `multipart/form-data`
---
# Custom parsers
To implement a custom parser, you should override `BaseParser`, set the `.media_type` property, and implement the `.parse(self, stream, parser_context)` method.
The method should return the data that will be used to populate the `request.DATA` property.
The arguments passed to `.parse()` are:
### stream
A stream-like object representing the body of the request.
### parser_context
If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content.  By default it includes the keys `'upload_handlers'` and `'meta'`, which contain the values of the `request.upload_handlers` and `request.meta` properties.
## Example
The following is an example plaintext parser that will populate the `request.DATA` property with a string representing the body of the request. 
    class PlainTextParser(BaseParser):
    """
    Plain text parser.
    """
    media_type = 'text/plain'
    def parse(self, stream, parser_context=None):
        """
        Simply return a string representing the body of the request.
        """
        return stream.read()
## Uploading file content
If your custom parser needs to support file uploads, you may return a `DataAndFiles` object from the `.parse()` method.  `DataAndFiles` should be instantiated with two arguments.  The first argument will be used to populate the `request.DATA` property, and the second argument will be used to populate the `request.FILES` property.
For example:
    class SimpleFileUploadParser(BaseParser):
        """
        A naive raw file upload parser.
        """
        def parse(self, stream, parser_context):
            content = stream.read()
            name = 'example.dat'
            content_type = 'application/octet-stream'
            size = len(content)
            charset = 'utf-8'
            # Write a temporary file based on the request content
            temp = tempfile.NamedTemporaryFile(delete=False)
            temp.write(content)
            uploaded = UploadedFile(temp, name, content_type, size, charset)
            # Return the uploaded file
            data = {}
            files = {name: uploaded}
            return DataAndFiles(data, files)
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
 |