Sma Ma
Sma Ma

Reputation: 3715

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

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?

Upvotes: 4

Views: 17830

Answers (1)

Sma Ma
Sma Ma

Reputation: 3715

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())

Upvotes: 13

Related Questions