Parsers In Django Rest Framework

Parsers In Django Rest Framework

Parsers in Django REST are used to parse the content of incoming HTTP request. In HTTP request we receive the data as a string format. Parsers will parse the HTTP contents in to python data types based on the Content-Type header received in the HTTP request. Django REST Framework provides a number of built-in parsers which parses different types of contents like "application/json", "multipart/form-data", "application/xml", etc., based on the Content-Type header received in the HTTP request.

Parser Classes in Django REST:

JSONParser

  • It parses the incoming request JSON content into python content type dict.
  • It is used if "Content-Type" is set to "application/json".

FormParser

  • It parses the incoming request form contents into QueryDict.
  • It is used if "Content-Type" is set to "application/x-www-form-urlencoded".

MultiPartParser

  • It parses the incoming request form contents into QueryDict.
  • It is used if "Content-Type" is set to "multipart/form-data".
  • request.data will be a QueryDict containing all the form parameters.
  • request.files will be a QueryDict containing all the form files.
  • FormParser and MultiPartParser together used for full support of HTML form data.

FileUploadParser

  • It is used to parse a single file sent in HTTP request.
  • It expects a url keyword argument "filename". If it's not provided then we should provide the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg.

  • request.file is used to access the contents of uploaded file.

  • To work with XML data we have use third party library "REST Framework XML" .

Configuring default parsers in Django REST:

We configure the parsers in django settings.py . We configure the default parsers using DEFAULT_PARSER_CLASSES setting. Let's see some code below.

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.JSONParser',
    )
}

How to override default parsers in views or viewsets ?

If we do not specify parser classes in views or viewsets then it will use the default parsers classes defined in DEFAULT\_PARSER\_CLASSES in settings. Let's do some code.

from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    """
    A view that can accept POST requests with JSON content.
    """
    parser_classes = (JSONParser,)

    def post(self, request, format=None):
        return Response({'received data': request.data})

We override default parser classes views or viewsets using the attribute "parser_classes" . We can also specify multiple parsers.

Reference: https://www.django-rest-framework.org/api-guide/parsers