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
requestslibrary.mkdir lambda_function cd lambda_function -
Install the
requestsLibrary Locally: You need to install therequestslibrary and all its dependencies into this directory. Use the--targetoption withpipto specify the current directory.pip install requests -t .This command will install the
requestslibrary and all its dependencies in the current directory. -
Add Your Lambda Function: Create a
lambda_function.pyfile inside the same directory where you installed therequestsmodule. 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.zipfile that contains both yourlambda_function.pyand therequestsmodule. -
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.zipfile you just created.
-
Test the Lambda Function: Now, test the function in the Lambda Console to verify that the
requestslibrary 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
pythondirectory):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
requestslayer 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!
