Accessing S3 Bucket Images with API

Accessing S3 Bucket Images with API

How to Use an API to Retrieve Images from an S3 Bucket

Introduction

This blog will guide you through setting up an API to access images stored in Amazon S3. We’ll leverage AWS Lambda to create a serverless function that handles image retrieval, and API Gateway to expose this functionality as a RESTful API. To ensure everything works as expected, we'll use Postman for testing and validation.

Step 1: Setting Up The S3 Bucket

  1. Open the AWS Management Console and navigate to the S3.

  2. Click Create Bucket.

  3. Give it a suitable name.

  4. Scroll and click Create Bucket.

  5. Open the bucket.

  6. Click Upload.

  7. Click Add files.

  8. Upload an images.

    Make sure to use smaller images (in kb) for faster access.

Step 2: Creating The Lambda Function

  1. Open the Lambda and in AWS Management Console.

  2. Click Create a function.

  3. Give a suitable function name.

  4. Select Python 3.8 in Runtime.

  5. In Advanced settings enable Enable function URL, select NONE in Auth type, and enable Configure cross-origin resource sharing (CORS).

  6. Click on the Create function.

  7. Open the function.

  8. In the code area paste this code, save it, and click Deploy.

     import base64
     import boto3
    
     s3 = boto3.client('s3')
    
     def lambda_handler(event, context):
         try:
             # Extract bucket name and file name from the event
             bucket_name = event["pathParameters"]["bucket"]
             file_name = event["queryStringParameters"]["file"]
    
             # Fetch the file from S3
             response = s3.get_object(Bucket=bucket_name, Key=file_name)
             file_content = response["Body"].read()
    
             # Return the image as a base64 encoded string
             return {
                 "statusCode": 200,
                 "headers": {
                     "Content-Type": "image/jpeg",  # Adjust this if you have different image formats
                     "Content-Disposition": f"inline; filename={file_name}"  # 'inline' displays the image in the browser
                 },
                 "body": base64.b64encode(file_content).decode('utf-8'),
                 "isBase64Encoded": True
             }
    
         except s3.exceptions.NoSuchKey:
             # Handle the case where the file does not exist in the bucket
             return {
                 "statusCode": 404,
                 "body": f"File {file_name} not found in bucket {bucket_name}."
             }
    
         except Exception as e:
             # Handle any other exceptions
             return {
                 "statusCode": 500,
                 "body": f"An error occurred: {str(e)}"
             }
    

  9. Now click on Configuration -> Permissions.

  10. Click on the Role name, and a new tab will open up.

  11. Scroll and click Add permissions -> Attach policies.

  12. Search and select AmazonS3FullAccess then click Add permissions.

Step 3: Setting Up API Gateway

  1. Open the API Gateway and in AWS Management Console.

  2. Scroll and click Build on Rest API.

  3. Select New API and give a suitable name.

  4. Click on Create API.

  5. Open the API.

  6. Click on Create resource.

  7. Give a resource name {bucket}.

    Note: Do not remove the curly bracket it will hold the bucket name which will be sent with the API.

  8. Click Create resource.

  9. Now click on the Create method.

  10. Select GET for the method type and the Lambda function for the integration type.

  11. You can enable Lambda proxy integration and select the Lambda function from the drop-down.

  12. In the Method request settings, select Validate query string parameters and headers under Request validator.

  13. In URL query string parameters click Add query string, type file under Name, and check Required.

  14. Click Create method.

  15. From the left navigation panel click API settings.

  16. Click on Manage media types.

  17. Then click on Add binary media types.

  18. Enter */* and click on Save changes.

  19. From the left navigation panel click Resources.

  20. Click on Deploy API.

  21. Select *New Satge* and give a suitable name.

  22. Click on Deploy.

  23. From the left navigation panel click Stages.

  24. Click on + until to see GET then click on GET.

  25. Copy the Invoke URL.

Step 4: Testing the API with Postman

  1. Open Postman.

  2. Paste the link and replace {bucket} with the you s3 bucket name and add ?file=file_name. Replace file_name with the file name that you upload in the s3 bucket (Example: if the URL is url.com, the s3 bucket name is images.xyz, and the file name is maths.jpg then use the link url.com/images.xyz?file=maths.jpg)

  3. Click Send and you can see the file in Body section.

    You can also use this link in a browser tab and fetch the image.