uannabi
uannabi

Reputation: 184

Django REST API in XML & JSON

How could I produce Django REST API in XML & JSON at the same time from a same model?

I have a model and need to create 2 different outputs from that model, one in XML and one in JSON.

Upvotes: 1

Views: 2237

Answers (1)

cezar
cezar

Reputation: 12012

If you need a custom behavior for just a particular model, you can specify the renderer_classes only in the view for that model.

Assuming you have a model, let's call it Foo:

# models.py
class Foo(models.Model):
    # properties

you can do this in your views.py:

from rest_framework.renderers import JSONRenderer
from rest_framework_xml.renderers import XMLRenderer
from rest_framework.views import APIView

class FooView(APIView):
    renderer_classes = (JSONRenderer, XMLRenderer)
    # the rest

The XMLRenderer is not anymore integral part of the Django REST Framework and has to be installed as an additional package:

$ pip install djangorestframework-xml

The offical documentation describes the use of renderers.

Upvotes: 4

Related Questions