Binary Data Upload to S3 Using API Gateway + Lambda

Earlier tutorial I showed you how to upload image to a s3 bucket using api gateway directly, but here my focus is for uploading images to s3 bucket using API gateway and lambda integration. In this integration is might be helpful for most of the software/system deployment because lambda functions gives more control over the code and it leads to configure it with more further integrations.

Let’s look at how we can configure API Gateway and Lambda together for this binary data uploading. In this tutorial which shows the easy steps to setup it.

Login to the AWS console and create a new API gateway & s3 bucket where you want to upload binary files.

  • Create a new Lambda function with python 3.7 called “upload”, and then add the following code in to it. Make sure you add the s3 bucket PUT permission to the IAM role itself while you are creating the Lambda.
import json
import base64
import boto3

def lambda_handler(event, context):
    s3 = boto3.client("s3")
    get_file_content = event["content"]
    decode_content = base64.b64decode(get_file_content)
    # Add Bucket name and key
    s3_upload = s3.put_object(Bucket="my-image-tester-frmx", Key="content.jpg", Body=decode_content)

    
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }
  • Create an API Gateway and configure resource and name it as “upload”
  • Add method POST and configure it to integrate with lambda function
  • Go to mapping template in the same integration page and add the following content to accept the image/jpeg Content-Type
{
    "content": "$input.body"
}
  • Go to settings and add binary media settings.
  • Now deploy the API Gateway configurations to a stage called “v1” and copy the URL

Once you’re done with required configurations above, you can try uploading a image to the s3 bucket using a postman to test it. Therefor, go to postman and add the above copied URL and then add “upload” to the end of the url as below.

https://sj7dfd.execute-api.us-east-1.amazonaws.com/v1/upload

Select authorizations headers and add Content-Type as image/jepg and then select binary data. In binary data you can select the image.

You have done it. ๐Ÿ™‚ I can see my image is there in the S3 bucket with name “content.jpg”

Hope you find this tutorial helpful ๐Ÿ™‚

Leave a comment