The error you're seeing indicates that the requests
library is not available in the AWS Lambda environment by default, so you need to include it manually. Here’s how you can do that:
Solution: Deploy requests
with Your Lambda Function
-
Create a Local Directory for Your Lambda Function: Create a directory that will hold both your Lambda function and the
requests
library.mkdir lambda_function cd lambda_function
-
Install the
requests
Library Locally: You need to install therequests
library and all its dependencies into this directory. Use the--target
option withpip
to specify the current directory.pip install requests -t .
This command will install the
requests
library and all its dependencies in the current directory. -
Add Your Lambda Function: Create a
lambda_function.py
file inside the same directory where you installed therequests
module. Here's an example:# lambda_function.py import requests def lambda_handler(event, context): response = requests.get('https://api.example.com') return { 'statusCode': 200, 'body': response.text }
-
Zip the Directory: Once the library and your Lambda function are in the same directory, zip everything into a single file.
zip -r lambda_function.zip .
This will create a
lambda_function.zip
file that contains both yourlambda_function.py
and therequests
module. -
Upload the Zip to AWS Lambda:
- Go to the AWS Lambda Console.
- Create a new function (or select an existing one).
- In the function’s Code section, click Upload from → .zip file.
- Upload the
lambda_function.zip
file you just created.
-
Test the Lambda Function: Now, test the function in the Lambda Console to verify that the
requests
library is working properly.
Alternative: Use AWS Lambda Layers
If you need to reuse the requests
library across multiple Lambda functions, you can create an AWS Lambda Layer. Here's a brief guide for that:
-
Install Requests Locally (in a
python
directory):mkdir python pip install requests -t python/
-
Zip the Python Directory:
zip -r requests_layer.zip python
-
Create a Lambda Layer:
- Go to the AWS Lambda Console.
- Navigate to the Layers section.
- Create a new layer by uploading the
requests_layer.zip
. - Specify the compatible runtimes (e.g., Python 3.8, 3.9, etc.).
-
Attach the Layer to Your Lambda Function:
- Open your Lambda function in the AWS Console.
- Scroll down to the Layers section.
- Add the
requests
layer you created.
This will allow you to keep your Lambda function code lean and reuse the requests
library across multiple functions.
Let me know if you run into any issues!