问题
To make an http call using python my way was to use requests
.
But requests
is not installed in lambda context. Using import requests
resulted in module is not found error.
The other way is to use the provided lib from botocore.vendored import requests
. But this lib is deprecated by AWS.
I want to avoid to package dependencies within my lambda zip file.
What is the smartest solution to make a REST call in python based lambda?
回答1:
Solution 1)
Since from botocore.vendored import requests
is deprecated the recomended way is to install your dependencies.
$ pip install requests
import requests
response = requests.get('https://...')
See also. https://aws.amazon.com/de/blogs/developer/removing-the-vendored-version-of-requests-from-botocore/
But you have to take care for packaging the dependencies within your lambda zip.
Solution 2)
My preferred solution is to use urllib
. It's within your lambda execution context.
https://repl.it/@SmaMa/DutifulChocolateApplicationprogrammer
import urllib.request
import json
res = urllib.request.urlopen(urllib.request.Request(
url='http://asdfast.beobit.net/api/',
headers={'Accept': 'application/json'},
method='GET'),
timeout=5)
print(res.status)
print(res.reason)
print(json.loads(res.read()))
Solution 3)
Using http.client
, it's also within your lambda execution context.
https://repl.it/@SmaMa/ExoticUnsightlyAstrophysics
import http.client
connection = http.client.HTTPSConnection('fakerestapi.azurewebsites.net')
connection.request('GET', '/api/Books')
response = connection.getresponse()
print(response.read().decode())
来源:https://stackoverflow.com/questions/58994119/how-to-make-a-http-rest-call-in-aws-lambda-using-python