aws lambda Unable to import module 'lambda_function': No module named 'requests'
Give it a check to this answer
If you're working with Python on AWS Lambda, and need to use requests, you better use urllib3, it is currently supported on AWS Lambda and you can import it directly, check the example on urllib3 site.
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', 'http://httpbin.org/robots.txt')
r.data
# b'User-agent: *\nDisallow: /deny\n'
r.status
# 200
This will surely work. Just follow the steps:
Create a "python" directory inside any empty directory and pip install the modules there
mkdir lambda_layers
cd lambda_layers
mkdir python
cd python
pip install requests -t ./
cd ..
zip -r python_modules.zip .
If you want to have multiple modules in a single layer then install them inside the same 'python' directory that you have just created.
Just make sure that you zip the "python" directory itself recursively with '-r'. That way lambda handler can locate the module in the default python version that you are using.
Now you have your 'python_modules.zip' file with all the dependent modules inside. Go to the Layers of Lambda in the AWS console and create a layer uploading this zip file. Choose the runtimes as per your python version that you are using in your lambda function, or you can select multiple python runtime versions. Add this layer to your lambda function and you should be able to import your modules flawlessly.
requests
library doesn't come by default in lambda. It looks like you are trying to import it in your function / library somewhere. To import it, you need the following line:
from botocore.vendored import requests
Alternatively, you would need to zip the requests
library in the root of your zip file.
EDIT: There may be a dependency in one of your libraries that may need this. To overcome this, install requests
in your application zip. To do this, run the following command in the root directory of your application: pip install requests -t ./
.
A better way would be to create a file called requirements.txt
and add all the dependencies in there. Use virtualenv to install all the packages defined in the requirements.txt using: pip install -r requirements.txt -t ./
UPDATE: Starting 10/21/19, the vendored version of the requests library in botocore will be removed. Refer this blog post for more details.