Last modified: Mar 11, 2025 By Alexander Williams

Customize Django Rest Framework Response Formats

Django Rest Framework (DRF) is a powerful tool for building APIs. By default, DRF returns responses in JSON format. However, you may need to customize the response format to suit your needs.

This guide will show you how to customize DRF response formats. We will cover JSON, XML, and custom formats. You will also learn how to implement these changes in your Django project.

Why Customize Response Formats?

Customizing response formats can improve API usability. It allows clients to request data in their preferred format. This can be especially useful when integrating with third-party services.

For example, some clients may prefer XML over JSON. Others may require a custom format for legacy systems. By customizing response formats, you can meet these diverse needs.

Default JSON Response

By default, DRF returns responses in JSON format. Here is an example of a simple DRF view that returns JSON:


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

class ExampleView(APIView):
    def get(self, request):
        data = {'message': 'Hello, World!'}
        return Response(data)

When you access this view, the response will be:


{
    "message": "Hello, World!"
}

Adding XML Response Format

To add XML as a response format, you need to install the djangorestframework-xml package. Run the following command:


pip install djangorestframework-xml

Next, add 'rest_framework_xml' to your INSTALLED_APPS in settings.py:


INSTALLED_APPS = [
    ...
    'rest_framework_xml',
    ...
]

Now, you can specify the format in the URL or request header. For example, to get an XML response, append ?format=xml to the URL:


<message>Hello, World!</message>

Creating Custom Response Formats

Sometimes, you may need a custom response format. DRF allows you to create custom renderers for this purpose. Here’s how to create a custom CSV renderer:


import csv
from rest_framework.renderers import BaseRenderer

class CSVRenderer(BaseRenderer):
    media_type = 'text/csv'
    format = 'csv'

    def render(self, data, media_type=None, renderer_context=None):
        response = renderer_context['response']
        response['Content-Disposition'] = 'attachment; filename="data.csv"'
        writer = csv.writer(response)
        for row in data:
            writer.writerow(row)
        return response

Add the custom renderer to your DEFAULT_RENDERER_CLASSES in settings.py:


REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
        'path.to.your.CSVRenderer',
    ]
}

Now, you can request a CSV response by appending ?format=csv to the URL.

Handling Multiple Formats

DRF makes it easy to handle multiple response formats. You can use the format_suffix_patterns function in your URLs. This allows clients to specify the format in the URL.

Here’s an example of how to use format_suffix_patterns:


from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from .views import ExampleView

urlpatterns = [
    path('example/', ExampleView.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)

With this setup, clients can request different formats by appending .json, .xml, or .csv to the URL.

Conclusion

Customizing Django Rest Framework response formats is straightforward. You can support JSON, XML, and custom formats with minimal effort. This flexibility makes DRF a versatile tool for building APIs.

For more advanced topics, check out our guides on Django Rest Framework Nested Serializers and Pagination in Django Rest Framework.

By following this guide, you can ensure your API meets the needs of all clients. Happy coding!