Client-side APIs

How, What, & Why

https://jtcoders.github.io/apis

What's a (web) API?

"Application Programming Interface"

Client-side APIs

Client-side APIs: How?


IMG 1993 Mosaic
SCRIPT 1995 Netscape & Sun (RIP)
IFRAME 1996 Microsoft
OBJECT/EMBED 1996 Netscape/W3C
XMLHttpRequest 1999 Microsoft/W3C

HTML APIs

IMG as API


<img src="http://otherdomain.com/service?param=x&otherparam=y">
  

First image API?


<img src="http://counter.digits.net/?
counter={d5ba6c4f-bd07-cb84-5583-0f90772b9dff}&
template=simple">
  

IMG as API: Google Maps Image APIs

<img src="
http://maps.google.com/maps/api/staticmap?
center=45.123664,-123.113775&
zoom=18&
maptype=satellite&
size=250x300&
sensor=false">
<img src="
http://maps.googleapis.com/maps/api/streetview?
size=300x250&
location=-33.86627,151.195827&
fov=20&
heading=350&
pitch=-20&
sensor=false">

Read more: Google Static Maps API | Google Street View Image API

IMG as API: Google Charts API

<img width="550" height="250" src="
http://chart.apis.google.com/chart?
cht=p&
chs=550x250&
chd=t:10,80,10&
chco=FAFAFA,FFFF00,FAFAFA&
chl=Does%20not%20resemble%20Pac-man|Resembles%20Pac-man&
chtt=Percentage%20of%20Google%20Chart%20Which%20Resembles%20Pac-man">

Read more: Google Charts API Docs
Note the deprecation notice!

EMBED/OBJECT as API

<object>
  <param name="movie" value="http://apidomain.com/widget.swf"></param>
  <param name="flashvars" value="param=x&otherparam=y"></param>
</object>

Flickr Slideshow:

<object width="400" height="300">
   <param name="movie" value="http://www.flickr.com/apps/slideshow/show.swf?v=107931"></param>
   <param name="flashvars" value="api_text=jowling&api_sort=interestingness-desc&offsite=true&lang=en-us&page_show_url=%2Fsearch%2Fshow%2F%3Fq%3Djowling%26s%3Dint&page_show_back_url=%2Fsearch%2F%3Fq%3Djowling%26s%3Dint&method=flickr.photos.search&api_params_str=&api_tag_mode=bool&api_media=all&jump_to=&start_index=0"></param>
   <embed type="application/x-shockwave-flash" src="http://www.flickr.com/apps/slideshow/show.swf?v=107931"
     flashvars="offsite=true&lang=en-us&page_show_url=%2Fsearch%2Fshow%2F%3Fq%3Djowling%26s%3Dint&page_show_back_url=%2Fsearch%2F%3Fq%3Djowling%26s%3Dint&method=flickr.photos.search&api_params_str=&api_text=jowling&api_tag_mode=bool&api_media=all&api_sort=interestingness-desc&jump_to=&start_index=0"
     width="400" height="300">
   </embed>
</object>

(Friends don't let friends use Flash APIs)

IFRAME as API: Simple

<iframe src="http://apidomain.com/widget.html"></iframe>

YouTube Embed:

<iframe width="420" height="315"
 src="http://www.youtube.com/embed/epUk3T2Kfno?rel=0&autoplay=1"
 frameborder="0" allowfullscreen></iframe>

Youtube Player Embed Reference




Exercise Time!




JS Widget/Snippet APIs

SCRIPT as API: Libraries

Your code:

<script src="http://apidomain.com/library.js"></script>
<script>
apiNamespace.apiFunction();
</script>

Their code:

window.apiNamespace.apiFunction = function() {
  // Do exciting API thing here
  // Maybe using images or iframes, too.
}

Google Analytics

<button type="button">Click Me!</button>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-964209-11']);
_gaq.push(['_trackPageview']);

$('#demo button').bind('click', function() {
    _gaq.push(['_trackEvent', 'UserInteraction', 'Click']);
});

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>

More reading: Google Analytics JS Docs

Disqus

<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'otherfancystuff';
var disqus_developer = 1;

(function() {
  var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
  dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>

More reading: Disqus Universal Code Docs

Facebook Like button

<div class="fb-like" data-href="http://gdisf-js-apis.appspot.com/"
  data-send="true" data-width="450" data-show-faces="true">
</div>

<div id="fb-root"></div>

<script>(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/all.js#xfbml=1&appId=152345878188549";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>

More reading: Facebook Like Button




Exercise Time!




JS Data APIs

XmlHttpRequest as API?

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://apidomain.com/method?param=bla');
xhr.onreadystatechange = function() {
  if(xhr.readyState == 4 && xhr.status==200) {
    var data = xhr.responseText;
  }
};
xhr.send();
Error: Same origin policy!

SCRIPT as API: JSONP

Your page:

<script src="http://imagine-it.org/api.php?callback=onLoadData">
</script>
<script>
function onLoadData(json) {
  $('#demo').html('YO YO YO ' + json.name);
}
</script>

API Server:

<?php
$callback = $_GET['callback'];

echo $callback . "({'name': 'Girl Develop It'});";
?>

reddit JSONP API

Example URL: http://www.reddit.com/r/all/search.json?q=girldevelopit

function onLoad(json) {
  var posts = json.data.children;
  console.log(posts);
  document.body.innerHTML = posts[0].data.title;
}

function fetchJSON(query) {
  var script = document.createElement('script');
  script.src = 'http://www.reddit.com/r/all/search.json?q='
    + query + '&jsonp=onLoad';
  document.getElementsByTagName('body')[0].appendChild(script);
}

fetchJSON('girldevelopit');

Reddit API docs

Flickr JSONP API

function fetchPhotos(query) {
  $.ajax({
    url: 'https://api.flickr.com/services/rest/',
    data: {api_key: 'a0de4a213ab1191732ec4db4daf586a3',
           method: 'flickr.photos.search',
           tags: query, per_page: '6', format: 'json'},
    dataType: 'jsonp',
    jsonp: 'jsoncallback',
    success: function(json){
      var photos = json.photos.photo;
      for (var i = 0; i < photos.length; i++) {
        var photo = photos[i];
        var photoUrl = 'http://farm' + photo.farm + '.static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_' + 'm.jpg';
        $('#demo').append('<img src="' + photoUrl + '">');
      }
    }
  });
}
fetchPhotos('rabbits');

See also: jQuery .ajax() | Flickr API

Combo APIs

...they do it all!

Facebook API

window.fbAsyncInit = function() {
  FB.init({appId: '174062109319467', status: true});
  FB.api('/me/friends', function(response) {
    for (var i = 0; i < response.data.length; i++) {
      var friendName = response.data[i].name;
    }
  });
};

(function() {
  var e = document.createElement('script');
  e.type = 'text/javascript';
  e.src = document.location.protocol +
   '//connect.facebook.net/en_US/all.js';
  e.async = true;
  document.getElementById('fb-root').appendChild(e);
}());



Exercise Time!

Client-side APIs: What?

See also: ProgrammableWeb.com API Directory

Client-side APIs: What?

Client-side APIs: Functionality

  • Analytics
  • Site Search
  • Text Processing (Translation/Analysis/TTS/Conversion)
  • Image Processing (Editing/Filter)
  • Payment
  • Communication (Telephony/Messaging/Chat/Email)

Text Processing: WebPurify

function purify(text) {
  var url = 'http://api1.webpurify.com/services/rest/';
  var params = {
    'api_key': '07efa9710a009bce7e2dbf01aa2cb12d',
    'method': 'webpurify.live.replace',
    'format': 'json',
    'text': encodeURIComponent(text),
    'replacesymbol': '*'
  }

  JSONP.get(url, params, null, function(json) {
    $('#demo').html(json.rsp.text);
  });
}

purify('Girl Develop It is the shit!');

See also: WebPurify JSON Docs

Image Processing: Aviary

<script type="text/javascript">
var _featherLoaded = false;
Feather_APIKey = '871670f82';
Feather_Theme = 'bluesky';
Feather_EditOptions = 'all';
Feather_OpenType = 'float';
Feather_CropSizes = '320x240,640x480,800x600,1280x1024';
Feather_OnSave = function(id, url) {
  var e = document.getElementById(id);
  e.src = url;
  aviaryeditor_close();
}
Feather_OnLoad = function() {
  aviaryeditor('image', $('#image').attr('src'));
  window.setTimeout(function() {$('#avpw_controls').css({position: 'fixed', 'z-index': '100000', 'left': '20px'});}, 20);
}
</script>
<script src="http://feather.aviary.com/js/feather.js"></script>
<img id="image" src="http://media.tumblr.com/tumblr_m6lz8rsqov1rqbtdh.jpg">

See also: Aviary Feather API

Client-side APIs: Data

  • Mapping
  • Real Estate
  • Shopping
  • Weather
  • Movies
  • Science
  • Books
  • Words
  • Government
  • Food
  • Sports
  • Travel
  • Wikipedia (Everything)

APIs: User Data

  • Social Networks
  • Multimedia: Music, Video, Photos
  • Documents

So you want to use an API...

  • Will you save time/money?
  • What are the terms?
  • What is the pricing?
  • How stable is it?
  • How will it affect performance?
  • What's your plan B?

APIs are...

function synonymify(word) {
  var url = 'https://api.wordnik.com/v4/word.json/' + word + '/related';
  var params = {
    'api_key': '98479a51ec674585e400609183c0e5d78bd7b4eba8a8810b4',
    'type': 'synonym',
    'partOfSpeech': 'adjective'
  }

  JSONP.get(url, params, null, function(json) {
    var synonyms = json[0].words;
    for (var i = 0; i < synonyms.length; i++) {
      $('#demo').append(synonyms[i] + '
'); } }); } synonymify('awesome');

See also: Wordnik API | ProgrammableWeb