Consuming multiple APIs asynchronously
4 minutes read
I recently worked on a few Facebook apps that used several APIs on top of the Facebook Graph API. Apps usually talk to an API through the SDK it provides, and on the frontend most developers use the JavaScript SDKs. Using several APIs in one app can get tricky, especially through their JavaScript SDKs.
The obvious reason is that you can't know how long an SDK will take to load. It varies between apps and even between pages. Load several SDKs and call their APIs in parallel and you can get unexpected responses. With the Graph API, the classic example is the warning about calling FB methods too early.
Ideally, JavaScript SDKs load asynchronously, nearly every time, so the app itself loads first and every API call gets a valid response.
The USA Outdoors Adventure app identifies users through the Graph API, then loads their latest progress using the Graph API, Google Maps and its own Outdoors Adventure (OA) API. The flow is:
- Check user status (Graph API)
- Confirm user registration (OA API)
- Check user status and get user data (OA API)
- Load user status (Google Maps API)
Each step depends on the one before, so the API calls have to be chained to avoid errors, odd results or early call warnings:
- Call Graph API
- Call OA API as a callback to Graph API
- Call Google Maps API as a callback to OA API
- Setup Frontend using final data in hand
Below I go through each step. 1
Facebook Graph API
The app uses the Facebook user ID to identify users and track their progress. The Facebook JavaScript SDK has a built-in async hook that holds back your own code until the SDK has fully loaded and its functions are available. Here's the standard initialisation code:
window.fbAsyncInit = function () {
FB.init({
appId: '1234567890',
xfbml: true,
version: 'v2.0',
});
// Callback function goes here
FB.getLoginStatus(myCallbackFunc);
};
(function (d, s, id) {
var js,
fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = '//connect.facebook.net/en_US/sdk.js';
fjs.parentNode.insertBefore(js, fjs);
})(document, 'script', 'facebook-jssdk');
myCallbackFunc, passed to FB.getLoginStatus(...), runs later as the callback.
You may or may not like working that way. With Socialmedia.js the same call is shorter:
var myFbApp = new Socialmedia.Facebook({
appid: '12345678',
callback: myCallbackFunc,
});
Outdoors Adventure (OA) API
The Facebook SDK is ready and we have the user's status from the Graph API. That status tells us whether they've connected to the app yet. If they have, we can call the OA API. If not, we ask them to connect.
A plain jQuery.getJSON call gets the user's data from the OA API. First, though, the user has to authorise the app with the right permissions so we know who they are. The whole thing:
function myCallbackFunc(response) {
if ( isConnectedUser(response) ) {
FB.api('/me', function(info) {
return
$.getJSON('/api/user?uid=info.id&token=secretToken')
.done(loadGoogleMapsFunc),
.fail(function(jqxhr, textStatus, error) {
// handle errors here
});
});
}
else {
FB.login(myCallbackFunc, { scope: 'email' });
}
}
function isConnectedUser(response) {
return (response && response.status && response.status === 'connected') ? true : false;
}
Google Maps API
With the user's identity, status and progress in JSON, we can build a personalised Google Map. Loading the map:
function loadGoogleMapsFunc(json) {
var map = null,
mapOptions = {
center: new google.maps.LatLng(35.589439, -106.387605),
zoom: 9,
disableDefaultUI: false
};
map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions);
/**
* Using built-in event listener of Google Maps API, we can
* defer loading the data on map until map is fully loaded,
*/
google.maps.event.addListenerOnce(map, 'tiles_loaded', function() {
return setupLocationData(map, json);
}
}
Once the map is ready, put the user's data on it:
function setupLocationData(map, json) {
for (var i = 0; i < json.length; i++) {
var info = json[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(info.lat, info.lng),
id: info.id,
info: info,
map: map,
});
}
}
The chain grows as you add more interactivity. You could also show a loading message or a spinner between calls so users aren't left staring at nothing.
Give the USA Outdoors Adventure app a try2. Feedback and questions are welcome.