Add API Gateway to AWS Lambda — a simple Python test case

Wenjing Zhan
3 min readAug 9, 2020

This is an attempt to explore AWS lambda. Final output as below

https://4vhxmcwh24.execute-api.us-east-1.amazonaws.com/dev/test-lambda

with extra option pic=1 or pic=2 (> 3 will be the default) to switch between different pictures

Prerequisite:

register an AWS account. Their free tier package is good enough for simple testing and experiments.

But the amount of access is limited. So please do not crawl the above link with bots for fun 😂

Set up Lambda Function

1 go to Compute Section -> Lambda service

2. Choose Runtime, either build from scratch or use a blueprint

3. Once create the Function, the page will be redirected to the graphical interface of the Configuration.

4. update the lambda handler with something interesting.

import json
import boto3
import botocore
import base64
s3 = boto3.resource('s3')def lambda_handler(event, context):

BUCKET_NAME = #my_bucket
KEY = #my_s3_file

if 'pic=' in event['rawQueryString']:
if event['queryStringParameters'][#parameter]== '1':
KEY = #optional source file option
... ...
try:
s3.Bucket(BUCKET_NAME).download_file(KEY, #local_file_path)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
print("The object does not exist.")
else:
raise


with open(#local_file_path, "rb") as imageFile:
image_content = imageFile.read()

return {
"isBase64Encoded": True,
"statusCode": 200,
"headers": { "content-type": "image/jpg"},
"body": base64.b64encode(image_content).decode("utf-8")
}

Here my chin’s photos are used for the test. Arguments can be passed to the lambda handler through url directly.

5. If the first test shows a download failure as below, it is an authorization issue. Lamda is denied by s3. To solve this, go check IAM roles and add AmazonS3FullAccess to the role.

use Attach Policies to add s3 full access, then go back and check the Lambda function test again.

Add API Gateway

  1. build a HTTP API

2. Link the Lambda Function to the API gateway through Add Integration

After naming the stage, review, and create the API. Invoke URL will be poped up.

To call the real URL, just add the resource path to the end of the Invoke URL.

--

--