Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get djangorestframework to return xml using format suffix?

I can get djangorestframework to return json via a format suffix .json, but not return xml via a .xml suffix

http://127.0.0.1:8000/chat/rooms/.json

[
{
id: 1,
timestamp: "2013-12-05T04:27:42Z",
topic: "important one"
},
{
id: 2,
timestamp: "2013-12-05T04:27:49Z",
topic: "important two"
},
{
id: 3,
timestamp: "2013-12-05T04:27:55Z",
topic: "important three"
},
{
id: 4,
timestamp: "2013-12-05T04:28:01Z",
topic: "important four"
},
{
id: 5,
timestamp: "2013-12-05T06:43:38Z",
topic: "another great stimulating topic"
}
]


http://127.0.0.1:8000/chat/rooms/.xml

{
detail: "Not found"
}

Could anyone tell me what I did wrong, b/c the REST api is clearly working...thanks!

like image 842
user798719 Avatar asked Dec 05 '13 06:12

user798719


2 Answers

You need to add the XMLRenderer which is not enabled by default.

To do this in settings have something like this:

REST_FRAMEWORK = {
  'DEFAULT_RENDERER_CLASSES': (
    'rest_framework.renderers.XMLRenderer',
    'rest_framework.renderers.JSONRenderer',
    'rest_framework.renderers.BrowsableAPIRenderer',
  )
}

To set renderers at the view level use the render_classes attribute.

Take a look at the Renderers documentation.

Update: It occurs to me the above is only half the answer. You'll also need to add the xml format suffix, as documented here.

I hope that helps.

like image 131
Carlton Gibson Avatar answered Oct 11 '22 16:10

Carlton Gibson


Now XMLRenderer is available as third-party package.

$ pip install djangorestframework-xml

settings.py

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework_xml.renderers.XMLRenderer',
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
}

Full django-rest-framework-xml Docs

like image 24
Ravi Kumar Avatar answered Oct 11 '22 15:10

Ravi Kumar