Skip to main content

Working with HTTP request

This article is a part of a tutorial about creating a bot which reports the current weather in any city of the world.

  1. Configuration file setup
  2. HTTP request to OpenWeatherMap API (you are here)
  3. Script development
  4. Testing

In this step, we will write a function to call OpenWeatherMap API.

Create a file called functions.js and put it in the src folder.

var OPENWEATHERMAP_API_KEY = $injector.api_key;

function openWeatherMapCurrent(units, lang, q){
return $http.get("http://api.openweathermap.org/data/2.5/weather?APPID=${APPID}&units=${units}&lang=${lang}&q=${q}", {
timeout: 10000,
query:{
APPID: OPENWEATHERMAP_API_KEY,
units: units,
lang: lang,
q: q
}
});
}

To identify the user, the server requires the API key. We will create the variable OPENWEATHERMAP_API_KEY to store the key from the chatbot.yaml configuration file.

var OPENWEATHERMAP_API_KEY = $ injector.api_key;

Now, let’s execute the HTTP request:

return $http.get("http://api.openweathermap.org/data/2.5/weather?APPID=${APPID}&units=${units}&lang=${lang}&q=${q}", {
timeout: 10000,
query:{
APPID: OPENWEATHERMAP_API_KEY,
units: units,
lang: lang,
q: q
}
});
}

The openWeatherMapCurrent function includes:

  • units for temperature measurement unit;
  • lang for display language;
  • q for the city name.

It sends an HTTP request using the $http.get method and returns an API response. In this method let’s specify the server URL and parameters from the query{} we will send to the server.

"http://api.openweathermap.org/data/2.5/weather?APPID=${APPID}&units=${units}&lang=${lang}&q=${q}"

The openWeatherMapCurrent function returns a promise object that contains a reply from service API in JSON format.

Let’s set up the timeout — the time period during allowed to elapse before the response from the server. The timeout is specified in milliseconds, with 10000 being equal to 10 seconds. If the request hasn’t been executed within the specified time, it will be interrupted.

tip
Learn more about working with $http.query (url, settings)

Next, move on to working with the script.