XML response in Django using Django-rest-framework

Installation & configuration

REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework_xml.parsers.XMLParser',
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework_xml.renderers.XMLRenderer',
],
}
[
{
"id": 1,
"name": "Montfort",
"email": "montfort@gmail.com",
"address": "12, New foundland, USA",
"student_count": 4
},
{
"id": 2,
"name": "Vidyashram",
"email": "Vidyashramschool@gmaill.com",
"address": "Chennai",
"student_count": 0
}
]
<root>
<list-item>
<id>1</id>
<name>Montfort</name>
<email>montfort@gmail.com</email>
<address>12, New foundland, USA</address>
<student_count>4</student_count>
</list-item>
<list-item>
<id>2</id>
<name>Vidyashram</name>
<email>Vidyashramschool@gmaill.com</email>
<address>Chennai</address>
<student_count>0</student_count>
</list-item>
</root>
from rest_framework_xml.renderers import XMLRendererclass MyXMLRenderer(XMLRenderer):
root_tag_name = 'schools'class SchoolView(APIView):
renderer_classes = [MyXMLRenderer, ]
def get(self, request):
schools = School.objects.all()
school_serializer = SchoolListSerializer(schools, many=True)
return Response(school_serializer.data)
<schools>
<list-item>
<id>1</id>
<name>Montfort</name>
<email>montfort@gmail.com</email>
<address>12, New foundland, USA</address>
<student_count>4</student_count>
</list-item>
<list-item>
<id>2</id>
<name>Vidyashram</name>
<email>Vidyashramschool@gmaill.com</email>
<address>Chennai</address>
<student_count>0</student_count>
</list-item>
</schools>
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_xml.renderers import XMLRenderer
from student.models import School
from student.serializers import SchoolListSerializer
class MyXMLRenderer(XMLRenderer):
root_tag_name = 'schools'
item_tag_name = 'school'
class SchoolView(APIView):
renderer_classes = [MyXMLRenderer, ]
def get(self, request):
schools = School.objects.all()
school_serializer = SchoolListSerializer(schools, many=True)
return Response(school_serializer.data)
<schools>
<school>
<id>1</id>
<name>Montfort</name>
<email>montfort@gmail.com</email>
<address>12, New foundland, USA</address>
<student_count>4</student_count>
</school>
<school>
<id>2</id>
<name>Vidyashram</name>
<email>Vidyashramschool@gmaill.com</email>
<address>Chennai</address>
<student_count>0</student_count>
</school>
</schools>

Conclusion

Python Developer | Django Developer | Python Enthusiast