[Django]-Django-tastypie. Output in JSON to the browser by default

41šŸ‘

āœ…

From the tastypie cookbook, in order to change the default format, you need to override the determine_format() method on your ModelResource:

class MyResource(ModelResource):
    ....
    def determine_format(self, request):
        return 'application/json'

The above link demonstrates alternative methods of determining output format.

Also, I donā€™t think a valid answer is essentially ā€œYou donā€™t need thisā€.

Edit

It appears GregMā€™s answer is probably (I havenā€™t tested it) the most correct with the new version of TastyPie, as per documentation putting the following in your settings.py will restrict the serialization output to json.

 TASTYPIE_DEFAULT_FORMATS = ['json']
šŸ‘¤mrmagooey

10šŸ‘

As of tastypie 0.9.13, if you do not need XML support you can disable it globally by setting TASTYPIE_DEFAULT_FORMATS to just ['json'] in your settings.py file. Requests should then default to JSON.

šŸ‘¤GregM

2šŸ‘

Iā€™ve tested setting TASTYPIE_DEFAULT_FORMATS to [ā€˜jsonā€™] but it doesnā€™t prevent the ā€œSorry not implemented yetā€ message when viewing the API from a browser.

I am able to make that warning go away by forcing the ā€œAcceptā€ header to ā€˜application/jsonā€™ in a middleware:

class TastyJSONMiddleware(object):
    """
    A Django middleware to make the Tastypie API always output in JSON format
    instead of telling browsers that they haven't yet implemented text/html or
    whatever.

    WARNING: This includes a hardcoded url path for /api/.  This is not 'DRY'
    because it means you have to edit two places if you ever move your API
    path.
    """

    api_prefix = '/api/'

    def process_request(self, request):
        if request.path.startswith(self.api_prefix):
            request.META['HTTP_ACCEPT'] = 'application/json'
šŸ‘¤btubbs

1šŸ‘

To examine/test your REST API, use a Rest client instead of a browser, preferably one that knows how to pretty print JSON. I use the Postman plugin for Google Chrome.

If you want pretty json in command line:

curl https://api.twitter.com/1.1/search/tweets.json | python -m json.tool

1šŸ‘

Tasytpie has the defaults set as ā€˜application/jsonā€™. But that is overridden by Browser request.

According to Tastypie, the default is overridden by Request Header ACCEPT and your format specification in GET ie. ?format=json. When you send request from browsers, if you see the Request HTTP Header sent, its something like ā€“

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

The application/xml overrides the default in Tastypie Resource. Therefore, either you can set Browser Header to have ā€˜application/jsonā€™ (Bad idea) or you just specify in GET.

If you hit the same API url using CURL, you will see the JSON output without specifying that in GET.

šŸ‘¤Ravi Kumar

Leave a comment