Microservice Recipe: Calling a Third-party REST API for Data Transformation

Service Recipes > Calling a Third-party REST API for Data Transformation
27 Dec 2016

This recipe provides an example of calling a third-party REST API as part of a data transformation process. In this example, longitude and latitude values are transformed in to a full textual address by the Eventn microservice using Googles Geo location API.

Use Case

Many IOT and mobile applications collect raw location data such as the longitude and latitude, however executing a full address lookup is better suited to a server side task and is a good example of a data transformation process using a third-party API.

This example uses Google Maps Geocoding API. See their documentation for a better understanding of the service.


Eventn provides a POST function that is executed when an HTTP POST request is made. This is typically used for data collection. The example function expects to be called with a body payload containing two properties as follows:

    "lat": 37.621368,
    "lng": -122.379063

The request parameters are extracted as individual variables (using ES6 destructuring) and then used as request parameters to Google's geocoding API. Note that here we make use of the request-promise library to make an HTTP(s) call out to the Google Maps API:

const rp = require('request-promise');

function onPost(context, request) {
const { lat, lng } = request.payload;
// Request params const options = { uri: 'https://maps.googleapis.com/maps/api/geocode/json', qs: { 'latlng': `${lat},${lng}` }, json: true // Automatically parses the JSON string in the response };
// Set a default address to be lat/lng let address = `${lat},${lng}`;
return rp(options) .then(response => {
if(response.results[0] && response.results[0].formatted_address) { address = response.results[0].formatted_address; }
// save to store return context.stores.default().table().insert({ data: JSON.stringify( address ) }); }) } module.exports = onPost;

The above function simply makes a request to lookup the full textual address. The response contains an array of multiple data items however, here the first value is taken and theformatted_addressproperty contains the full textual address. If this property is not available for any reason, a defult string of the lat/lng is saved instead.

Example Response

    "data": "\"101 San Francisco International Airport Tram, San Francisco, CA 94128, USA\""

Get Started For Free

Get Started