Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return byte array from AWS Lambda API gateway?

I am a beginner so I am hoping to get some help here.

I want create a lambda function (written in Python) that is able to read an image stored in S3 then return the image as a binary file (eg. a byte array). The lambda function is triggered by an API gateway.

Right now, I have setup the API gateway to trigger the Lambda function and it can return a hello message. I also have a gif image stored in a S3 bucket.

import base64
import json
import boto3

s3 = boto.client('s3')

def lambda_handler(event, context):
# TODO implement
bucket = 'mybucket'
key = 'myimage.gif'

s3.get_object(Bucket=bucket, Key=key)['Body'].read()
return {
    "statusCode": 200,
    "body": json.dumps('Hello from AWS Lambda!!')
}

I really have no idea how to continue. Can anyone advise? Thanks in advance!

like image 964
Kian Avatar asked Sep 16 '25 14:09

Kian


1 Answers

you can return Base64 encoded data from your Lambda function with appropriate headers.

Here the updated Lambda function:

import base64
import boto3

s3 = boto3.client('s3')


def lambda_handler(event, context):
    bucket = 'mybucket'
    key = 'myimage.gif'

    image_bytes = s3.get_object(Bucket=bucket, Key=key)['Body'].read()

    # We will now convert this image to Base64 string
    image_base64 = base64.b64encode(image_bytes)

    return {'statusCode': 200,
            # Providing API Gateway the headers for the response
            'headers': {'Content-Type': 'image/gif'},
            # The image in a Base64 encoded string
            'body': image_base64,
            'isBase64Encoded': True}

For further details and step by step guide, you can refer to this official blog.

like image 102
Mayank Raj Avatar answered Sep 19 '25 06:09

Mayank Raj