Intermediate tutorial: Creating HTTP requests from Web services

In this tutorial, you can separate your code into multiple files and make an HTTP request to the OpenWeatherMap API.

Prerequisites

Before you begin, it is recommended that you complete the Beginners' tutorial.

Download and install the following tools:

Steps

  1. Install axios by running the following command:

    npm install axios
  2. Create the file that you will use for the Web service:

    mkdir src && touch src/MyWeatherService.js
  3. Consider what you would like your input and output to look like. To get a response from OpenWeatherMap, you must supply two items in the request:

    • The name of a city

    • An API key

      The response is returned in JSON format and contains a lot of data. However, you extract only some simple information.

  4. Copy the following code into the src/MyWeatherService.js file:

    "use strict"
    import { ServiceDefinition, WebServiceError } from '@sirensolutions/web-service-interface';
    import axios from 'axios';
    
    export class MyWeatherService extends ServiceDefinition { (1)
      name = 'weatherservice';
      inputSchema = {
        city_name: {
          type: 'text',
          description: 'name of the city to get weather information for',
          required: true
        }
      };
      outputConfiguration = { (2)
        weather: {
            name: 'keyword',
            main: 'text',
            location: 'geo_point',
            temperature: 'long'
        }
      };
      // Called to invoke the service. The inputs argument will have fields described in this.inputSchema
      async invoke(inputs) { (3)
        // The API endpoint to send a query to
        const url = 'https://api.openweathermap.org/data/2.5/weather?';
    
        // Parameters are added to the end of a URL:
        // E.g.  https://api.openweathermap.org/data/2.5/weather?q=London&appid=<your-api-key>
        const params = {
          q: inputs.city_name,
          appid: '<your-api-key>'
        }
        const headers = {
          'Content-Type': 'application/json'
        }
    
        // The axios library is used here, but you can use a different library/implementation for querying an API
        const response = await axios.get(url, { params, headers })
          .catch(error => Promise.reject(error.response && error.response.status < 500 ? new WebServiceError(error.response.data) : error)); (4)
    
        // Must return objects with the same structure as in this.outputConfiguration. These are stored in Elasticsearch automatically.
        return {
          weather: [{
            name: response.data.name,
            main: response.data.weather[0].main,
            location: response.data.coord,
            temperature: response.data.main.temp
        }]};
      }
    }
    1 You need to export the class so that you can import it later in the index.js file.
    2 The outputConfiguration used here specifies that the objects be stored in dedicated indices: web-services-example-web-service-group-MyWeatherService-results-weather. For more information, see the Storing in dedicated data indices section of the Output configuration topic.
    3 The invoke function uses the async flag, which allows you to await the response from OpenWeatherMap. This saves you from having to write out a chain of callback handlers. The invoke function queries the OpenWeatherMap API with the city and the API key.
    4 Here, you catch any errors if they should occur. There are two types of error that you can expect: a WebServiceError, which indicates invalid input or configuration, and any generic error which indicates a fault with the code or the external API. For more information, see Error handling
  5. Now, modify the index.js file to contain only the following code:

    "use strict";
    import { registerServices } from '@sirensolutions/web-service-interface';
    import { MyWeatherService } from './MyWeatherService'; (1)
    export default registerServices('example-web-service-group', [MyWeatherService]);
    1 You import the weather Web service into the index.js file, so that you can register it to the Web service group on the next line.
  6. It’s ready to go! Copy or move the current directory into the plugins folder in Siren Investigate by running the following command:

    cp -r . path/to/investigate/plugins
  7. Start Elasticsearch and Siren Investigate by running the following commands:

    cd path/to/elasticsearch
    ./bin/elasticseach
    cd path/to/investigate
    ./bin/investigate
  8. To start using the service, copy and paste localhost:5606 into your browser.

    invokation-vis

Next steps