Search code examples
amazon-web-servicesaws-lambdaaws-api-gateway

Handling an image/jpeg response from Lambda in API Gateway


I have been at this for hours trying to resolve my issue and I cannot for the life of me.

I have an API that simply fetches an image from another API. All I would like to do is run a GET request and the response be the image.

I am using AWS services Lambda & API Gateway - I have followed every implementation I can see online however it doesn't work in the way I need it to.

I have an endpoint, a GET request that runs a Lambda proxy integration

API Gateway Integration Request

When this is called it then runs my Lambda function which looks as follows. This is a Base64 response, which is how I've read this needs to be handled in Lambda.

Lambda Function

I also read that I needed to specifically add binary media type so API Gateway knows how to handle the response. Now this is the key problem, when I set the binary media type to */* it works as expected, an image is returned in the browser, however this now converts all my API responses to binary which is not ideal as typically they are json - as such, I only want images to be converted. When I use image/jpeg which has been configured as my response body in API Gateway and my response header in Lambda I no longer can see the image. See below example of binary media type configuration enter image description here

See below example of API response how image is viewed in browser when setting binary media type to image/jpeg No image from API

See below example of API response with how image is viewed in browser when setting binary media type to */* (functioning as I'd like) Image from API

and the thing that really throws me off, is when I test my API in postman, with the binary media type set as */* I can see the image, but looking into the response headers I can clearly see its been set to image/jpeg so I can't understand why API Gateway doesn't work when I expect it to. enter image description here


Solution

  • I discovered the issue was because if you specify the binary media type in the form of image/jpeg you are then required to add an Accept Header to your GET Request. Your accept header must explicitly state image/jpeg.

    The reason it didn't work in the browser is because I am not passing any accept headers. When I used a tool such as Postman, I had no issues and got the response I was expecting.

    Luckily for me I am able to add accept headers to my API request in future. However if you are a programmer looking to be able to get your image purely from a browser request this won't be the answer you are looking for.

    enter image description here