Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

aws-lambda

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?

like image 969
Sma Ma Avatar asked Oct 29 '25 01:10

Sma Ma


1 Answers

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())
like image 138
Sma Ma Avatar answered Nov 01 '25 13:11

Sma Ma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!