How to use requests module in AWS Lambda

Python requests library is by default not avaialble in AWS Lambda Python environments. For using requests library in Lambda function a Lambda Layer needs to attached to the Lambda function. This tutorials lists the required steps for creating and attaching Lambda Layer for requests module.

Step 1: Create Python Virtual Environment

python3 -m venv test_venv

Step 2: Activate Virtual Environment


# [On Ubuntu]

source test_venv/bin/activate

# [On Windows]

.\test_venv\Scripts\activate

Step 3: Check Python Version


python --version  

Step 4: Create directory with name python


mkdir python  

Step 5: Install requests package in python directory created in Step 4


pip install requests -t python  

Step 6: Zip python directory


# [On Ubuntu]

zip -r requests.zip python

# [On Windows]

powershell Compress-Archive python requests.zip  

Step 7: Login to AWS account and Navigate to AWS Lambda Service.

Step 8: In AWS Lambda select Layers from Additional resources.

Step 9: Click on create layer, enter the required information.
  • Name: requests_layer
  • Description: Lambda layer for requests module
  • Select Upload a .zip file, click on upload and choose requests.zip created in Step 6
  • Compatible runtimes - Choose run time as per the python version from output of Step 3

Step 10: Click on Create

Step 11: Navigate to AWS Lambda function and select Functions

Step 12: Click on Create function

Step 13: Select Author from scratch

Step 14: Enter Below details in Basic information
  • Function name: test_lambda_function
  • Runtime: choose run time as per the python version from output of Step 3

Step 15: Click on create function

Step 16: In the Function overview pane click on Layers or Scroll down to select Layers section

Step 17: Click on Add a layer

Step 18: Select Custom layers , choose layer created in Step 9, select version 1 and click on Add.

Step 19: Write below code in lambda function and click on Deploy


import json
import logging
import requests

logger = logging.getLogger()
logger.setLevel(logging.INFO)


def lambda_handler(event, context):
    logger.info(requests.__version__)


Step 20: Click on Test, enter any name for Configure test event and click on create

Step 21: Click on Test again, you should see requests version in the output.