How to make a HTTP rest call in AWS lambda using python?

孤街浪徒 提交于 2021-02-19 08:08:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!