Search code examples
pythonamazon-web-serviceschalice

Chalice Framework: Request did not specify an Accept header with image/jpeg


I want to return an image from a Chalice/python application. My entire application code is pasted below:

from chalice import Chalice, Response
import base64

app = Chalice(app_name='hello')

@app.route('/makeImage', methods=['GET'])
def makeImage():
    return Response(
        base64.b64decode(
            "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
        ),
        headers={
            'Content-Type': 'image/jpeg'
        },
        status_code=200)

The result...

{"Code":"BadRequest","Message":"Request did not specify an Accept header with image/jpeg, The response has a Content-Type of image/jpeg. If a response has a binary Content-Type then the request must specify an Accept header that matches."}

Why does this happen?

I have poured through a ton of documentation already and most of it is outdated as binary support was added to Chalice very recently:

Just for troubleshooting purposes I'm able to obtain a response by using curl -H "accept: image/jpeg", but this is useless since browsers to not work this way, and I need to use the response in a browser (HTML IMG TAG).

UPDATE

I also tried @app.route('/makeImage', methods=['GET'], content_types=['image/jpeg'])

And result became {"Code":"UnsupportedMediaType","Message":"Unsupported media type: application/json"}


Solution

  • I had the same issue.

    If no header accept is present, AWS set it to default application/json and I receive a base64 response. If I set accept to images/jpeg or any binary content type in header, then I got the images. Great but web browser to not set the accept header.

    But if I add

    app.api.binary_types =['*/*']
    

    then ok my images apis now works. Great but now the json ones fail.

    Currently I do not see any solution except having two API gateway : one for json and one for images. If you really want only one API Gateway, I think you have to use gzip conpression on all you json response to convert them to binaries.

    It is more how AWS API Gateway works with lambda proxy than a Chalice issue. But I agree, it is a big limitation