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?

1

1 Answer 1

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.