Use Your Lambda Function to call an External API

Use your Lambda Function to call an External API

In the last article, you have seen how an AWS Lambda function can be created. In this article, you will see how a Lambda function can be used to call an external API. You will also see how to run a Lambda function at a specific time using Cloudwatch event trigger and cron expressions.

We have used an external API from the website https://openweathermap.org/api. This Current weather data API could be used to access the current weather data for any location for about 200,000 cities in the world. When the API is called, it returns the data in JSON format. The website allows you to generate an API key for both, signup and paid plans. The API can be called by using this key along with parameters such as city name, city id, geographic coordinates, etc. In this example, we have used the City name to access weather information for the city of Washington, US.

The API call is as follows :
http://api.openweathermap.org/data/2.5/forecast?q=Washington,us&APPID=53d6430c1eccacb54e827045d1aee3d3

The json structure returned by the API for the weather forecast of Washington is as follows :

{

'message': 0.005,

'city': {

'country': 'US',

'coord': {

'lon': -77.0367,

'lat': 38.895

},

'population': 863420,

'name': 'Washington DC.',

'id': 4366164

},

'list': [{

'weather': [{

'icon': '03n',

'description': 'scattered clouds',

'main': 'Clouds',

'id': 802

}],

'wind': {

'deg': 329.505,

'speed': 3.07

},

'dt': 1531299600,

'clouds': {

'all': 36

},

'sys': {

'pod': 'n'

},

'main': {

'temp_kf': -1.04,

'temp': 296.24,

'temp_min': 296.24,

'temp_max': 297.273,

'humidity': 77,

'sea_level': 1026.12,

'pressure': 1019.66,

'grnd_level': 1019.66

},

'dt_txt': '2018-07-11 09:00:00'

}, {

'weather': [{

'icon': '01d',

'description': 'clear sky',

'main': 'Clear',

'id': 800

}],

'wind': {

'deg': 348.5,

'speed': 3.12

},

'dt': 1531310400,

'clouds': {

'all': 0

},

'sys': {

'pod': 'd'

},

'main': {

'temp_kf': -0.78,

'temp': 298.35,

'temp_min': 298.35,

'temp_max': 299.131,

'humidity': 61,

'sea_level': 1027.41,

'pressure': 1020.9,

'grnd_level': 1020.9

},

'dt_txt': '2018-07-11 12:00:00'

}, {

'weather': [{

'icon': '02d',

'description': 'clear sky',

'main': 'Clear',

'id': 800

}],

'wind': {

'deg': 354.5,

'speed': 2.86

},

'dt': 1531321200,

'clouds': {

'all': 8

},

'sys': {

'pod': 'd'

},

You can use the following steps to call an API from your Lambda function and schedule the function at a specific interval, say 1 minute.

Step 1: Create your Lambda function to call an external API

The current weather data API returns weather information in JSON format, for the city of Washington, for six consecutive days including the current date and for three-hour intervals such as 12 pm, 3 pm, 6 pm, etc. The lambda function returns the weather data for the city of Washington for the current date, for the first three-hour interval that is scheduled after the current time.

The code written in Python is as follows :

# import libraries here

from botocore.vendored import requests

from datetime import datetime

def lambda_handler(event, context):

# Get the current date and time in yy–mm-dd hours:minutes:seconds format
now = datetime.now()
now_str = now.strftime(‘%Y-%m-%d %H:%M:%S’)

# API call
response = requests.get(‘http://api.openweathermap.org/data/2.5/forecast?
q=Washington,us&APPID=53d6430c1eccacb54e827045d1aee3d3′)

# Check if the request completed successfully
if response.status_code == 200:

# Convert response data to python dictionary object
datadictionary = response.json()

# Return the desired weather information for today from the dictionary object
for data in datadictionary[‘list’]:
if data[‘dt_txt’] > now_str:

# Return data and print data
description = data[‘weather’][0][‘description’]humidity = data[‘main’][‘humidity’]sea_level = data[‘main’][‘sea_level’]temp = data[‘main’][‘temp’]print(“weather:{}, humidity: {}, sea_level: {},temperature:
{}”.format(description,humidity,sea_level,temp))
return “weather:{}, humidity: {}, sea_level: {},temperature:
{}”.format(description,humidity,sea_level,temp)

 

 

Once you are done with the code, save the function, test it and check whether it is successful in the Execution result.

 

 

 

Step 2: Schedule the Lambda function at specific intervals

To schedule your Lambda function at specific intervals, go to Add Triggers section and click on Cloudwatch Events.

 

 

Then, configure your trigger in the configure trigger section by performing the following actions

  1. In the Rule, section select the option to create a new rule
  2. Specify a name for the rule in the Rule name section
  3. Provide a description of the rule you have specified in the Rule Description section.
  4. 4.Under the Rule Type section select schedule expression 
  1. Under the schedule expression section specify your cron expression for the specific interval for which you would be scheduling your lambda function. You can get your cron expression for the site: http://www.cronmaker.com/. In this case, we have selected the specific interval to be 1 minute.
  2. Ensure that Enable Trigger option is clicked.
  3. Finally, click on Add to add the trigger to your function and Save the changes.

 

 

 

 

Step 3: Check the Cloudwatch event logs

To check whether your Lambda function is triggered at regular intervals, (1 minute in this case), check the Cloudwatch event logs, as shown below.