3

I am trying to serve images from an api based on django-rest-api.

So far I have a very basic api view that loads an image and its mimetype and returns it.

@api_view(['GET'])
def get_pic(request, pk=None, format=None):
    //get image and mimetype here
    return HttpResponse(image, content_type=mimetype)

This has been working fine, however I have tested it on some new image libraries on iOS and have found that the API is returning a 406 error.

I believe this is because the client is sending a Accept image/* which this api view doesn't except.

Doing a HEAD on the api returns the following;

GET, OPTIONS
Connection → keep-alive
Content-Type → application/json
Date → Wed, 17 Jun 2015 10:11:07 GMT
Server → gunicorn/19.2.1
Transfer-Encoding → chunked
Vary → Accept, Cookie
Via → 1.1 vegur
X-Frame-Options → SAMEORIGIN

How can I change the Content-Type for this API to accept image requests?

I Have tried adding a custom parser with the right media_type but his doesn't seem to help. Is this the right approach or is there an easier way to serve images from django-rest-framework?

Lunar
  • 4,663
  • 7
  • 43
  • 51
  • 1
    [Does this question's response help you?](http://stackoverflow.com/questions/14251851/what-is-406-not-acceptable-response-in-http) – Ross Rogers Jun 17 '15 at 14:23

1 Answers1

1

You need to create a custom renderer like:

class JPEGRenderer(renderers.BaseRenderer):
    media_type = 'image/jpeg'
    format = 'jpg'
    charset = None
    render_style = 'binary'

    def render(self, data, media_type=None, renderer_context=None):
        return data