Consuming my Quotes web api

You might not have noticed the quotes web api that has serves the ‘Quote of the Day’ on my main site’s homepage.  Underlying it is a JSON web api that you can incorporate in to your own apps or website.  This post will describe how you might do that using javascript.

To begin it is useful to describe what you can currently accomplish by calling my quote web api.  You can either, get a list of quotes, get a quote by it’s id, or get a random quote.  Each is accomplished by calling a slightly different URL listed below.

To retrieve this via a javascript function you can simply cut and paste the following code in to the dev tools console (press F12 > then go to Console):

var xhr = new XMLHttpRequest();
xhr.open('GET', 
'http://www.michaelsmale.com/api/quoteservice/random');
  xhr.send(null);
  xhr.onreadystatechange = function () {
  var DONE = 4;
  var OK = 200;
  if (xhr.readyState === DONE) {
    if (xhr.status === OK)
      var responseText = xhr.responseText;
      var jsonResponse = JSON.parse(responseText);
      alert(jsonResponse.QuoteText + jsonResponse.Author);
    }
  };

If you want to include it as a function in a web page you simply wrap it in a function replacing the code above in the ellipsis below:

<script type="text/javascript"> 
function getNewRandomQuote() {
    ...
};</script>

One interesting thing is that if you just click the link in the browser, a browser will not add a header for the Content-Type it is expecting, and by default the web api will return XML.  In contrast javascript will always make an additional header for JSON since it prefers javascript object notation.

0 comments… add one

Leave a Comment