Image upload using AWS API- Gateway and Lambda

Today I am writing my experience on how to build an REST API to upload an image on AWS S3 using Lambda function.

You can find the complete project on GitHub , I have completed this using AWS CDK.

Objective : REST service to upload image.

Project has 3 parts as : AWS S3 Bucket, AWS Lambda function, API-Gateway REST Api.

AWS S3 Bucket : Bucket to store uploaded Images, in this example we will create bucket using CDK and pass bucket name as environment variable to Lambda function

AWS Lambda Function to upload image to S3 : We need to create lambda function which will take the base64 encoded image and upload it to S3. If we dont find fileName as input , we will extract extension from base64 encoding and generate uuid as file name, then we upload file to s3 using boto3 python library. we are going to generate pre-signed URL of uploaded image and will pass in output so that user can download it.

Lets see the code, it start with “def handler (event, context)” is main function triggered by API gateway.

Input to Lambda would be found in body section of event, read the content

payload = json.loads(event['body'])
image = payload['content']

Decode the image base64 content to upload

file_content = base64.b64decode(image) # decode to get actual image

Upload to S3, we need to pass s3_key=file name with path like /images/myImage.jpg , actual file_content and metadata if we want to add additional content about image.

If user is not going to provide us file name and extension, we can extract extension fron base64 content like

You can find complete Lambda code here

API Gateway REST service: we will create a REST API which will be called by users to upload and image, it will take image base64 encoded content as input like

Now to create API Gateway and Lambda function infrastructure , we have used AWS CDK stack like

Create a s3-bucket, lambda function and integration

Add POST method to API and integrate lambda function

You can find complete API gateway stack code here

Happy Coding :-)

Technology Evangelist, Cloud apprentice