Retrieving Images from S3 using Lambda Function and API Gateway
Tags: s3imageretrieval, aws, lambdafunction, apigateway
Published: 2023-06-15 01:33:00

**Introduction:**
In this article, we will explore how to retrieve images from an Amazon S3 bucket using a Lambda function through the API Gateway. We will cover the step-by-step process, including creating an S3 bucket, uploading an image, writing a Lambda function, and configuring the API Gateway to access the images.

**1. Creating an S3 Bucket and Uploading the Image:**
To begin, we need to create an S3 bucket and upload an image into it. This step ensures that we have a source from which to retrieve images using the Lambda function.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1s807h7s67e4xtc2093i.png)

An S3 bucket named beachhhh is created and two jpg files are uploaded into it.



**2. Creating the Lambda Function:**
The next step involves creating a Lambda function. We will write a Python function that utilizes the AWS SDK, boto3, to interact with AWS services. The code snippet will include importing the necessary libraries, initializing the S3 client, and defining the Lambda handler.
`import base64
import boto3
s3 = boto3.client('s3')
`

**3. Implementing the Lambda Handler:**
`def lambda_handler(event, context):
    bucket_name = event["pathParameters"]["bucket"]
    file_name = event["queryStringParameters"]["file"]
    fileObj = s3.get_object(Bucket=bucket_name, Key=file_name)
    file_content = fileObj["Body"].read()
`
The Lambda handler is the entry point for the Lambda function. We will extract the bucket name and file name from the event object, which contains information about the request. Using the bucket name and file name, we will retrieve the file content from the S3 bucket using the `get_object` method.


**4. Constructing the Response:**
`    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/jpg",
            "Content-Disposition": "attachment; filename {}".format(file_name)
        },
        "body": base64.b64encode(file_content),
        "isBase64Encoded": True
    }
`
After retrieving the file content, we will construct the response to be returned by the Lambda function. This includes setting the appropriate status code, content type, and content disposition headers. We will encode the file content in base64 format and include it in the response body. Finally, we set the `isBase64Encoded` flag to indicate that the response body is base64 encoded.

**5. Configuring Lambda Function Permissions:**
To allow the Lambda function to access the S3 bucket, we need to assign it a role with the necessary permissions. This can be done by navigating to the Lambda function's permissions tab and configuring the execution role. Here, we can define the required S3 access permissions for the Lambda function.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/056stog9cthy3a8cnd8z.png)



**6. Setting Up API Gateway:**
Moving on to the API Gateway, we will create a new REST API. We'll define a resource with a path parameter for the bucket name and a query parameter for the file name. Enforcing a request validator ensures that the query parameter is present in the API request.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3tl1ajatycgqtgiws2za.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bnzy9oh0at72zq8cc382.png)



**7. Configuring Binary Media Type:**
To handle binary data, such as images, we need to configure the API Gateway to treat certain media types as binary. By setting the "binary media type" to `*/*`, we ensure that the API Gateway correctly handles image data.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vbks05xttf61fezmemus.png)



**8. Deploying the API and Testing:**
With the API Gateway configured, we can deploy the API and obtain the endpoint URL. We can test the functionality using tools like Postman by sending a GET request to the URL. In the request, we specify the bucket name as part of the URL path and the file name as a query parameter.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9c4an0r5jryxpcejb8ah.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/19on5pl2mhxjjl088e9y.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/izxtlcmtc4iykles4ywz.png)




**Conclusion:**
By following the steps outlined in this article, you can effectively retrieve images stored in an Amazon S3 bucket using a Lambda function and API Gateway. This integration enables seamless image retrieval and facilitates the development of image-based a