AWS Lambda – Create a Lambda Function in Python, Integrated with API Gateway

Pre-requisite: AWS 

We will begin with creating a lambda function in the AWS Lambda console and write our Python code for the same. We will test our function by creating the new event and verifying the response. Next, we will configure the lambda function with the JSON placeholder which is a sample API. We will be using the concept of layers in the AWS lambda function to achieve the same. Layers can be understood as a ZIP archive that contains runtimes, libraries, or other functional dependencies which can be used across multiple functions. Lastly, we will test our integration.

Step 1: Go to AWS Management Console and search for lambda. Click on “Lambda” and next click on “Create Function”.

Step 2: Give your function a name, here we have given it an if-test. Select the runtime as Python 3.9. Click on create function.

 

Step 3: For API call we will be using JSON placeholder which is a sample API. 

Basically, we will be using a request library in Python, we will call the API.

https://jsonplaceholder.typicode.com/

and whatever output is received will be shown by the lambda function.

Step 4: Create a new file config.py.

add the following line of code to config.py 

base_url = "https://jsonplaceholder.typicode.com/"

 

Step  5: Replace the code in the Lambda_function file with the following:

import json
from config import base_url
import requests

def lambda_handler(event, context):
    res = requests.get(url=base_url+'todos/1')
    return {
        'statusCode': res.status_code,
        'body': res.json
    }

 

Step 6: Once we have replaced the contents simply click on Deploy and Test. The test UI will appear, modify the changes as shown in the below image

 

Click on create Event. Once it’s done click on Test again.

 

This is the error we receive. This is because the function is not able to find the requests module. In order to resolve the issue we must pass the dependencies in the layer.

 

But before we create and add a layer we must save the dependencies in the zip file and then upload it to the layer. To do so we will use VS Code on the local computer.

Step 7: Use the following commands to create a zip folder of dependencies:

mkdir pypackages
pip3 install requests -t /home/rishaw/gfg-test/pypackages
zip -r pypackages.zip pypackages/

 

Step 8: Once the zip is created go to the AWS console and click on create a layer.

 

Once the layer is created we can attach it to our Lambda function.

Step 9: Go to your Lambda Function and scroll down to layers and click on add a layer.Make changes as shown in the image.

 

Once the layer is added, click on Test again. This time the execution is completed and the output is visible.

 



Contact Us