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:
- https://github.com/aws/chalice/pull/352
- https://github.com/aws/chalice/issues/592
- https://github.com/aws/chalice/issues/348
- AWS Chalice Return an Image File from S3 (Warning: the sole answer to this question is COMPLETELY WRONG)
- https://chalice.readthedocs.io/en/latest/api.html
- https://github.com/aws/chalice/issues/391 (issue WRONGLY CLOSED in 2017 without a resolution)
- https://github.com/aws/chalice/issues/1095 is a re-open of 391 above
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"}
There was a bug in Chalice that was fixed on 14-May-2019 and documented here:
In addition to installing the latest Chalice directly from GitHub, I also had to add:
in
app.py
.The final working code looks like this: