0
votes

I am migrating an existing API from Django Piston to Django Tastypie. I am using Django 1.7.

The existing API outputs JSON by default, but supports XML queries if ?format=xml is appended to the URL.

I am finding it hard to work out how to replicate this in Tastypie. There's a very similar question here, but all the answers only explain how to totally disable all other formats except JSON. So I'm wondering if it's actually possible to do this in Tastypie.

If I do this in my settings file:

TASTYPIE_DEFAULT_FORMATS = ['json']

JSON becomes the default, but I can't then output XML with a ?format=xml parameter, because XML is disabled.

Similarly if I add a determine_format method to the resource.

Is it possible to specify JSON as the default format, but also allow XML?

1
Did you set the "serializer" attribute in your ModelResources's meta class? See: django-tastypie.readthedocs.org/en/latest/serialization.html - kchan

1 Answers

0
votes

You can override the determine_format for default format as JSON. It will work for other format too.

class MyAppResource(ModelResource):
    """It is inheriting Model Resources of tastypie"""

    def determine_format(self, request):
        """
        return application/json as the default format
        """
        fmt = determine_format(request, self._meta.serializer,\
                               default_format=self._meta.default_format)
        if fmt == 'text/html' and 'format' not in request:
            fmt = 'application/json'
        return fmt

Now, Instead of Base as ModelResource use MyAppResource for your Resource classes.