Django REST Framework XML

2.0.0 · active · verified Wed Apr 15

djangorestframework-xml provides XML parsing and rendering support for Django REST Framework. It was previously part of DRF itself but is now maintained as a separate, third-party package. The library is currently at version 2.0.0 and offers a stable way to integrate XML into DRF APIs, with releases occurring periodically to maintain compatibility with newer Django and DRF versions.

Warnings

Install

Imports

Quickstart

To enable XML support globally, add `XMLParser` and `XMLRenderer` to your `REST_FRAMEWORK` settings in `settings.py`. For view-specific control, you can apply `@parser_classes` and `@renderer_classes` decorators to function-based views or set `parser_classes` and `renderer_classes` attributes in class-based views. Ensure `rest_framework_xml` is in your `INSTALLED_APPS` (though often not strictly necessary for just renderers/parsers, it's good practice).

import os

# settings.py
# Add 'rest_framework_xml' to INSTALLED_APPS if using specific template renderers or custom configurations
INSTALLED_APPS = [
    # ... other Django apps
    'rest_framework',
    'rest_framework_xml',
]

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
        'rest_framework_xml.parsers.XMLParser',
    ],
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework_xml.renderers.XMLRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer' # Optional: for DRF's browsable API
    ],
}

# views.py example
from rest_framework.decorators import api_view, renderer_classes, parser_classes
from rest_framework.response import Response
from rest_framework_xml.parsers import XMLParser
from rest_framework_xml.renderers import XMLRenderer

@api_view(['GET', 'POST'])
@parser_classes([XMLParser])
@renderer_classes([XMLRenderer])
def example_xml_view(request):
    """ A view that can accept/return XML content. """
    if request.method == 'GET':
        data = {'message': 'Hello from XML API!', 'status': 'success'}
        return Response(data)
    elif request.method == 'POST':
        received_data = request.data
        # Process received_data (which will be parsed from XML)
        return Response({'received_data': received_data, 'processed': True})

view raw JSON →