Jacobian
Jacobian

Reputation: 10812

How to get api format response from Django

I followed "Writing regular Django views..." from the official documentation of Django Rest framework and got this kind of code:

#views.py file

#imports go here

class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

def items(request):
    output = [{"a":"1","b":"2"},{"c":"3","d":"4"}]
    return JSONResponse(output)

And it works well. When a user goes to /items/ page, he or she sees a nicely looking json-formated data [{"a":"1","b":"2"},{"c":"3","d":"4"}]. But, how can I get (code?) api-formated data, or check if a user requested ?format=api then render in api format manner and if not, then in json format. By api-formated data I mean this kind of view

Upvotes: 2

Views: 954

Answers (1)

Erik Svedin
Erik Svedin

Reputation: 1286

Try using the @api_view() decorator as described here. And make sure you use the built in Response instead of JSONResponse.

Your view should then look something like this:

from rest_framework.decorators import api_view

...

@api_view()   
def items(request):
    output = [{"a":"1","b":"2"},{"c":"3","d":"4"}]
    return Response(output)    

In the case of getting the error

Cannot apply DjangoModelPermissions on a view that does not have model or queryset property

Remove DjangoModelPermissions from your rest framework permissions settings in you settings.py

Upvotes: 1

Related Questions