Wilson Mar bio photo

Wilson Mar

Hello!

Calendar YouTube Github

LinkedIn

Call REST APIs from static client browsers

US (English)   Norsk (Norwegian)   Español (Spanish)   Français (French)   Deutsch (German)   Italiano   Português   Estonian   اَلْعَرَبِيَّةُ (Egypt Arabic)   Napali   中文 (简体) Chinese (Simplified)   日本語 Japanese   한국어 Korean

Overview

This is a hands-on narrated tour on how to code JavaScript in client static sites to reach REST APIs in the cloud.

I want you to feel confident that you’ve mastered this skill. That’s why this takes a hands-on approach where you type in commands and we explain the responses and possible troubleshooting. This is a “deep dive” because all details are presented.

Like a good music DJ, I’ve carefully arranged the presentation of concepts into a sequence for easy learning, so you don’t have to spend as much time as me making sense of the flood of material around this subject.

Sentences that begin with PROTIP are a high point of this website to point out wisdom and advice from experience. NOTE point out observations that many miss. Search for them if you only want “TL;DR” (Too Long Didn’t Read) highlights.

Stuck? Contact me and I or one of my friends will help you.


jQuery or Not?

This is the question because different coding is needed.

We start with plain XHR (XMLHttpRequest) as described in this tutorial by CodeAcademy

createRequest(); // var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.codecademy.com/", false);
xhr.send();
 
console.log(xhr.status);
console.log(xhr.statusText);
   

Despite the XML in its name, neither the request nor the response has to involve XML.

http://rest.elkstein.org/2008/02/using-rest-in-javascript.html

CreateRequest

This function is a cross-browser solution that covers both MSIE and others:

function createRequest() {
  var result = null;
  if (window.XMLHttpRequest) {
    // FireFox, Safari, etc.
    xhr = new XMLHttpRequest();
    if (typeof xmlhttp.overrideMimeType != 'undefined') {
      xhr.overrideMimeType('text/xml'); // Or anything else
    }
  }
  else if (window.ActiveXObject) {
    // MSIE
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  } 
  else {
    // No known mechanism -- consider aborting the application
  }
  return result;
}
   

Define Callback

XMLHttpRequest objects do not immediately return a value. Rather, you have to supply a callback function that will be invoked when the request completes.

A callback is invoked several times (up to four times, depending on the browser), during different stages of the client/server interaction. Only the fourth and final stage that interests us; the readyState field can be used to test for the stage:

var req = createRequest(); // defined above
// Create the callback:
req.onreadystatechange = function() {
  if (req.readyState != 4) return; // Not there yet
  if (req.status != 200) {
    // Handle request failure here...
    return;
  }
  // Request successful, read the response
  var resp = req.responseText;
  // ... and use it as needed by your app.
}
   

Note that if the response is an XML response (denoted by the server using MIME type text/xml), it can also be read using the responseXML property. This property contains an XML document, and can be used as such using JavaScript’s DOM navigation facilities.

Send Request

Now that the request object and its callback function has been setup, send the request.

For GET requests:

req.open("GET", url, true);
req.send();
   

For POST requests:

req.open("POST", url, true);
req.setRequestHeader("Content-Type",
                     "application/x-www-form-urlencoded");
req.send(form-encoded request body);
   

jQuery way

This blog makes a call to an active service endpoint which does not require authentication:

https://spring.io/guides/gs/consuming-rest-jquery/

which returns this when called without any parameters:

{“id”:1,”content”:”Hello, World!”}

The jQuery call:

jQuery.get( "http://public-api.wordpress.com/rest/v1/sites/en.blog.wordpress.com/", function( response ) { 
    // response contains site information
} );
   

Authentication

  
jQuery.ajax( {
    url: 'https://public-api.wordpress.com/rest/v1/sites/' + site_id + '/posts/new',
    type: 'POST',
    data: { content: 'testing test' },
    beforeSend : function( xhr ) {
        xhr.setRequestHeader( "Authorization", "BEARER " + access_token );
    },
    success: function( response ) {
        // response
    }
} );

More on cloud

This is one of a series on cloud computing: