You are on page 1of 10

3/26/2015

Publishing data from an external API

METEORCAPTURE
Follow@dburles

HOME

SUBSCRIBE

Publishing data
from an external
API
16 SEPTEMBER 2014

Publishing anything pt. 2


Continuing on from the previous article (see
Publishing anything) where we covered publishing
a very simple set of static data, we'll now take a
look at publishing data that we request from an
external API.
For this example we'll use the Google Books API.
Just to note; with a public API such as this that does
not require private authentication, a better
approach may be to make the API call client side
and simply insert the documents into the client
http://meteorcapture.com/publishing-data-from-an-external-api/

1/10

3/26/2015

Publishing data from an external API

side collection.
In the case where the API requires private
authentication or perhaps we need to decorate the
document with some other server side data, the
publication method demonstrated here is the
approach to take.
We're using a public API here simply for
demonstration.

Client
Let's start off once again with the client side code

Templates
<body>
<form>
<input type="text" name="query">
<input type="submit" value="Search">
</form>

{{#if searching}}
<p>Searching...</p>
{{else}}

http://meteorcapture.com/publishing-data-from-an-external-api/

2/10

3/26/2015

Publishing data from an external API

{{#if books.count}}
<hr>
<table>
{{#each books}}
{{> book}}
{{/each}}
</table>
{{/if}}
{{/if}}
</body>

<template name="book">
<tr>
<td class="image"><img src="{{thumb}}"></td>
<td>
<a href="{{link}}" target="_blank">{{title}}</a>
<p>{{{snippet}}}</p>
</td>
</tr>
</template>

Javascript
Books = new Mongo.Collection('books');

http://meteorcapture.com/publishing-data-from-an-external-api/

3/10

3/26/2015

Publishing data from an external API

Session.setDefault('searching', false);

Tracker.autorun(function() {
if (Session.get('query')) {
var searchHandle = Meteor.subscribe('booksSearch',
Session.get('query'));
Session.set('searching', ! searchHandle.ready());
}
});

Template.body.events({
'submit form': function(event, template) {
event.preventDefault();
var query = template.$('input[type=text]').val();
if (query)
Session.set('query', query);
}
});

Template.body.helpers({
books: function() {
return Books.find();
},
searching: function() {
return Session.get('searching');
http://meteorcapture.com/publishing-data-from-an-external-api/

4/10

3/26/2015

Publishing data from an external API

}
});

The important parts of what we're doing here are:


Creating a client side collection called books
Setting a Session variable once the form is submit
Subscribing to our publication called booksSearch
within an autorun and passing in the Session value
We've also added a helper called loading which
watches the subscription handle's ready method.
This is to indicate when the search results are
loading

Server
Now let's take a look at what's going on over on the
server. This is where the interesting stuff happens.

Meteor.publish('booksSearch', function(query) {
var self = this;
try {
var response =
HTTP.get('https://www.googleapis.com/books/v1/volumes', {
params: {

http://meteorcapture.com/publishing-data-from-an-external-api/

5/10

3/26/2015

Publishing data from an external API

q: query
}
});

_.each(response.data.items, function(item) {
var doc = {
thumb: item.volumeInfo.imageLinks.smallThumbnail,
title: item.volumeInfo.title,
link: item.volumeInfo.infoLink,
snippet: item.searchInfo &&
item.searchInfo.textSnippet
};

self.added('books', Random.id(), doc);


});

self.ready();

} catch(error) {
console.log(error);
}
});

Our booksSearch publication has been set up to


http://meteorcapture.com/publishing-data-from-an-external-api/

6/10

3/26/2015

Publishing data from an external API

take an argument ( query) which we'll use to pass


through to the HTTP request.
In order to communicate with the Google Books
API, we're using Meteor's HTTP package. On the
server we can run it synchronously if we don't pass
in a callback function. Which is exactly what we're
doing here.
The first step is making the request and assigning
the response to a variable called, well, response.
Next we're iterating over the resultset, taking what
we need and assigning it to doc, then calling
self.added for each.

Finally, to let the subscriber know that we're all


ready, self.ready().

Example app
https://github.com/dburles/meteor-capturepubsub2
Check out the example application on GitHub.
http://meteorpad.com/pad/YWbRFASEfC3NQgfN8
http://meteorcapture.com/publishing-data-from-an-external-api/

7/10

3/26/2015

Publishing data from an external API

Play around with the live app running on


MeteorPad.

David Burles

Share this post

Freelance Meteor Consultant & Developer. Hosts

Meteor Melbourne.

Melbourne, Australia

13Comments

Twitter

GitHub

MeteorCapture

Recommend 2

Share

Login

SortbyBest

Jointhediscussion
bsbechtel 3monthsago

Thisisgreat.Thanksforwritingthis!
1

Reply Share

MorganJackson 6monthsago

GreatArticleDave!
1

Reply Share

DavidBurles

Mod >MorganJackson

6monthsago

ThanksMorgan!

Reply Share

StuartMitchell 6monthsago

NicearticleDave!Easytofollowandnottoolong.Imightevenrollupmy
sleevesandgiveitagowiththediscogsAPIsoIcanfinallycatalogueallmy
oldvinyl:D
1

Reply Share

LucianoGuasco 6monthsago

VerynicearticleDavid.
FeelingtemptedtorefactormanyMeteor.methodscallingAPIstosomething
similarlikethis.
Definitelywiththisapproach,thepyramidofcallbacksisreducedoratleast
http://meteorcapture.com/publishing-data-from-an-external-api/

8/10

3/26/2015

Publishing data from an external API

Definitelywiththisapproach,thepyramidofcallbacksisreducedoratleast
removedfromtemplateslogic.
1

Reply Share

CasperSrensen 12daysago

HeyDavid,
Greattutorial!Iwentaheadandactuallygotitimplementedwith
themoviedb.orgtofetchalistoftvshowsinsteadofthebooks.Hopetosee
somemoreofthisstuffinthefuture,welldone!:)

Reply Share

DavidBurles

Mod >CasperSrensen

11daysago

That'sgreat,thanks!

Reply Share

WidaSkyDev amonthago

Nicearticledave!!thank's

Reply Share

greg amonthago

HowwouldIuseatwitterstreamapiinthesamefashion.Tosearchfortweets.

Reply Share

DavidBurles

Mod >greg

amonthago

Goodquestion,unfortunatelyI'mnotfamiliarenoughwiththetwitter
APItobeabletoanswerthatonesorry!

Reply Share

KarlPokus 6monthsago

Toobadmeteorpadisreeallyslow.

Reply Share

DavidBurles

Mod >KarlPokus

6monthsago

YeahIknow!,it'sgreatwhenit'sworkingthough:)

Reply Share

KarlPokus>DavidBurles 6monthsago

Absolutely!Acodepen.ioforMeteorisawesomebutthelagis
abitannoying.Hopefullyitwillgetbetter.
1

Reply Share

WHAT'STHIS?

ALSOONMETEORCAPTURE

Understandingspacebars

Random

16comments9monthsago

3comments7monthsago

imslavkoIwouldaddthat
http://meteorcapture.com/publishing-data-from-an-external-api/

LucianoGuascoDavid,you
9/10

3/26/2015

imslavkoIwouldaddthat

Publishing data from an external API

observingacursorismorepreferable
toreturningafetchedarray:Blazehas
anoptimizationforcursorswhenit

LucianoGuascoDavid,you

alwaysappearwhenIneedyou.
Happynewyearmate:)

Publishinganything

Joiningontheclient

11comments6monthsago

3comments9monthsago

AvatarDavidBurlesHeyJosh,itwasone

AvatarDominiquePerettiHey,IthinkI

Meteor Capture 2015

http://meteorcapture.com/publishing-data-from-an-external-api/

Proudly published with Ghost

10/10

You might also like