Quantcast
Channel: 懒得折腾
Viewing all articles
Browse latest Browse all 764

Integrating External APIs into your Meteor.js application

$
0
0

Integrating External APIs into your Meteor.js application

05.07.2015

Meteor itself does not rely on REST APIs, but it can easily access data from other services. This article is an excerpt from the book Meteor in Action and explains how you can integrate third-party data into your applications by accessing RESTful URLs from the server-side.

Many applications rely on external APIs to retrieve data. Getting information regarding your friends from Facebook, looking up the current weather in your area, or simply retrieving an avatar image from another website – there are endless uses for integrating additional data. They all share a common challenge: APIs must be called from the server, but an API usually takes longer than executing the method itself. You need to ensure that the result gets back to the client – even if it takes a couple of seconds. Let’s talk about how to integrate an external API via HTTP.

Based on the IP address of a visitor, you can tell various information about their current location, e.g., coordinates, city or timezone. There is a simple API that takes an IPv4 address and returns all these tidbits as a JSON object. The API is called Telize.

Making RESTful calls with the http package

In order to communicate with RESTful external APIs such as Telize, you need to add the http package:

While the http package allows you to make HTTP calls from both client and server, the API call in this example will be performed from the server only. Many APIs require you to provide an ID as well as a secret key to identify the application that makes an API request. In those cases you should always run your requests from the server. That way you never have to share secret keys with clients.

Let’s look at a graphic to explain the basic concept.

A user requests location information for an IP address (step 1). The client application calls a server method called geoJsonforIp(step 2) that makes an (asynchronous) call to the external API using the HTTP.get() method (step 3). The response (step 4) is a JSON object with information regarding the geographic location associated with an IP address, which gets sent back to the client via a callback (step 5).

Using a synchronous method to query an API

Let’s add a method that queries telize.com for a given IP address as shown in the following listing. This includes only the bare essentials for querying an API for now. Remember: This code belongs in a server-side only file or inside a if (Meteor.isServer) {}block.

01.Meteor.methods({
02.// The method expects a valid IPv4 address
03.'geoJsonForIp': function (ip) {
04.console.log('Method.geoJsonForIp for', ip);
05.// Construct the API URL
06.var apiUrl = 'http://www.telize.com/geoip/' + ip;
07.// query the API
08.var response = HTTP.get(apiUrl).data;
09.return response;
10.}
11.});

Once the method is available on the server, querying the location of an IP works simply by calling the method with a callback from the client:

1.Meteor.call('geoJsonForIp', '8.8.8.8', function(err,res){
2.console.log(res);
3.});

While this solution appears to be working fine there are two major flaws to this approach:

  1. If the API is slow to respond requests will start queuing up.
  2. Should the API return an error there is no way to return it back to the UI.

To address the issue of queuing, you can add an unblock() statement to the method:

Calling an external API should always be done asynchronously. That way you can also return possible error values back to the browser, which will solve the second issue. Let’s create a dedicated function for calling the API asynchronously to keep the method itself clean.

Using an asynchronous method to call an API

The listing below shows how to issue an HTTP.get call and return the result via a callback. It also includes error handling that can be shown on the client.

01.var apiCall = function (apiUrl, callback) {
02.// try…catch allows you to handle errors
03. 
04.try {
05.var response = HTTP.get(apiUrl).data;
06.// A successful API call returns no error
07.// but the contents from the JSON response
08.callback(null, response);
09.} catch (error) {
10.// If the API responded with an error message and a payload
11.if (error.response) {
12.var errorCode = error.response.data.code;
13.var errorMessage = error.response.data.message;
14.// Otherwise use a generic error message
15.} else {
16.var errorCode = 500;
17.var errorMessage = 'Cannot access the API';
18.}
19.// Create an Error object and return it via callback
20.var myError = new Meteor.Error(errorCode, errorMessage);
21.callback(myError, null);
22.}
23.}

Inside a try…catch block, you can differentiate between a successful API call (the try block) and an error case (the catch block). A successful call may return null for the error object of the callback, an error will return only an error object and null for the actual response.

There are different types of errors and you want to differentiate between a problem with accessing the API and an API call that got an error inside the returned response. This is what the if statement checks for – in case the error object has a response property both code and message for the error should be taken from it; otherwise you can display a generic error 500 that the API could not be accessed.

Each case, success and failure, returns a callback that can be passed back to the UI. In order to make the API call asynchronous you need to update the method as shown in the next code snippet. The improved code unblocks the method and wraps the API call in a wrapAsync function.

01.Meteor.methods({
02.'geoJsonForIp': function (ip) {
03.// avoid blocking other method calls from the same client
04.this.unblock();
05.var apiUrl = 'http://www.telize.com/geoip/' + ip;
06.// asynchronous call to the dedicated API calling function
07.var response = Meteor.wrapAsync(apiCall)(apiUrl);
08.return response;
09.}
10.});

Finally, to allow requests from the browser and show error messages you should add a template similar to the following code.

01.<template name="telize">
02.<p>Query the location data for an IPp>
03.<input id="ipv4" name="ipv4" type="text" />
04.<button>Look up locationbutton>
05.
06.{{#with location}}
07.
08.{{#if error}}
09.<p>There was an error: {{error.errorType}} {{error.message}}!p>
10.{{else}}
11.<p>The IP address {{location.ip}} is in {{location.city}}
12.({{location.country}}).p>
13.{{/if}}
14.{{/with}}
15.template

A Session variable called location is used to store the results from the API call. Clicking the button takes the content of the input box and sends it as a parameter to the geoJsonForIp method. The Session variable is set to the value of the callback.

This is the required JavaScript code for connecting the template with the method call:

01.Template.telize.helpers({
02.location: function () {
03.return Session.get('location');
04.}
05.});
06. 
07.Template.telize.events({
08.'click button': function (evt, tpl) {
09.var ip = tpl.find('input#ipv4').value;
10.Meteor.call('geoJsonForIp', ip, function (err, res) {
11.// The method call sets the Session variable to the callback value
12.if (err) {
13.Session.set('location', {error: err});
14.} else {
15.Session.set('location', res);
16.return res;
17.}
18.});
19.}
20.});

As a result you will be able to make API calls from the browser just like in this figure:

And that’show to integrate an external API via HTTP!

Published at DZone with permission of its author, Stephan Hochhaus.



Viewing all articles
Browse latest Browse all 764

Trending Articles