AJAX & APIs

Objectives

  • Identify all the HTTP Verbs & their uses.
  • Describe APIs and how to make calls and consume API data.
  • Access public APIs and get information back.
  • Implement an AJAX request with Vanilla JS.
  • Implement a jQuery AJAX client for a simple REST service.
  • Reiterate the benefits of separation of concerns – API vs. Client.

Review

  • jQuery DOM selection
  • jQuery events
  • Use event delegation to manage dynamic content

Intro to APIs

It's best practice to separate DOM logic from our data models

 

Separation of concerns becomes ever more important when working with outside data

(A)pplication (P)rogramming (I)nterfaces

Helps us with the separation of outside data or services and are provided through API calls

Example API situations

  • Twitter 
  • Weather forecasting app
  • Social game sharing high scores

API Gotcha's

  • Certain APIs require authentication or have limits
  • If an API call is triggered by user action, give the user feedback that something is happening.
  • Update view after we get a return from the server.
  • Account for not receiving data back due to different interruptions/causes:
    • Server timeout
    • Wrong authentication information
    • User loses connection
    • Request URL not found
  • Representational state transfer (REST) is the most common architecture style for passing information to and from these API endpoints. (good reference article)

HTTP/s

HTTP is a protocol - a system of rules - that determines how web pages get sent (transferred) from one place to another. Among other things, it defines the format of the messages passed between HTTP clients and HTTP servers.

clients make requests and servers  receive requests.

HTTP Clients make or generate HTTP Requests. Some types of clients are:

  • Browsers - Chrome, Firefox and Safari.
  • Command Line programs - curl and wget.

 

HTTP Clients respond to HTTP Responses from a Web Server. They process the data being returned form a Web Server, aka HTTP Server. (good reference article)

 

 

HTTP/Web Server

Two of the most popular HTTP of Web servers are Apache and Nginx.

 

All Web Servers receive HTTP Requests and generate HTTP Responses

 

Often Web Servers are just the middleman, passing HTTP Request and Responses between the client and web application.

Web Applications

Play by Play

  1. A client sends a HTTP Request to a HTTP Server running on a remote machine.
    • The hostname, given in the URL, indicates which server will receive the request.
  2. The HTTP server processes the HTTP Request. This may entail passing the request to some Web Application, which creates a HTTP Response.
  3. The response gets sent back to the client.
  4. The client processes the response.

 

How does the server know what the request is asking for? This is specified by the URL, a special kind of path that specifies where a resource can be found on the web.

HTTP Demo

Go to a website of your choice & open your inspector

Use theNetwork tab to see a few HTTP Requests and Responses; for each request you'll see a Path, Method, Status, Type, and Size, along with info about how long it took to get each of these resources. 

  • Some HTTP requests are for CSS, JavaScript and images that are referenced by the HTML.
  • Headers are meta-data properties of an HTTP request or response, separate from the body of the message.

HTTP Request

The first word in the request line, GET, is the HTTP Request's Method.

HTTP Request Methods

  • GET => Retrieve a resource.

  • POST => Create a resource.
  • PATCH (or PUT, but PATCH is recommended) => Update an existing resource.
  • DELETE => Delete a resource.
  • HEAD => Retrieve the headers for a resource.

HTTP Structure

[http request method] [URL] [http version]  
[list of headers]

[request body]
GET http://vermonster.com HTTP/1.1  
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8  
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8  
Connection:keep-alive  
Host:vermonster.com  
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5)  
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1659.2 Safari/537.36  

HTTP Request Method Example: (No Body)

HTTP Response

[http version] [status] [reason]  
[list of headers]

[response body] # typically HTML, JSON, ...  

Status Codes

Code Reason
200 OK
301 Moved Permanently
302 Moved Temporarily
400 Bad Request
403 Forbidden
404 Not Found
500 Internal Server Error

AJAX and JavaScript

AJAX stands for Asynchronous JavaScript and XML. It sends and receives information in a variety of formats. The most commonly used format for communicating with APIs, as we've seen, is JSON.

 

AJAX allows us to not only communicate with servers, but it allows us to do this asynchronously, meaning it happens in the background, allow us to update our interfaces and content without refreshing the page.

 // Create instance of XMLHTTPRequest
  var httpRequest = new XMLHttpRequest();

  // Set a custom function to handle the request
  httpRequest.onreadystatechange = responseMethod;

  function responseMethod() {
    // Request logic
  }

  // Alternative method:
  // httpRequest.onreadystatechange = function() {
  //   
  // }

To make an HTTP request with AJAX we need to first create an instance of XMLHttpRequest and then decide how we want to handle the response by setting the onreadystatechange method of the XMLHTTPRequest object to a custom function.

function responseMethod() {
    // Check if our state is "DONE"
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      // If our request was successful we get a return code/status of 200
      if (httpRequest.status === 200) {
        // This is where we update our UI accordingly. 
        // Our data is available to us through the responseText parameter
        console.log(httpRequest.responseText);
      } else {
        // This is the scenario that there was an error with our request
        console.log('There was a problem with the request.');
      }
    }
  }

Before we do anything with the request, we need to first check its state. If the state tells us that the request is done, we can then handle the return of the request. There are two primary scenarios for handling the request:

  • We check for a success and update our application logic
  • We check for an error and notify the user
var httpRequest = new XMLHttpRequest();

  httpRequest.onreadystatechange = responseMethod;

  // Open method accepts 3 parameter:
  // 1. Request type: these are all the HTTP verbs we covered above
  // 2. The URL
  // 3. Optional boolean third parameter, that dictates wether this 
       // is an asynchronous call (default is true)
  httpRequest.open('GET', 'http://data.consumerfinance.gov/api/views.json');

  // The send method takes an optional parameter. If our API request allows 
  // additional parameters or JSON objects to be passed through 
  // (primarily through POST requests), we pass them in the send method.
  httpRequest.send();

  // NOTE: certain APIs may require us to pass additional header data, 
  // including setting the MIME type of the request. 
  /  We can do this through the setRequestHeader method.
  // httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

After we have defined what happens in both successful and erroneous scenarios, we finally open and send our request.

 

Consumer Finance Data: Independent Practice

  • Refactor the codealong to work with user interaction. In the index.html file there is a "Get Consumer Finance Data" button. When the user clicks the button, pull data from the provided link above (http://data.consumerfinance.gov/api/views.json). Handle the link success and error responses accordingly, displaying results in console.log() if successful.
  • Separate your logic so that you can use your functions for another user button click of "Get Custom Data". Interact with an API of your choice and handle both success and error scenarios.

jQuery AJAX

  // All we need to create a get or post request
  //  is use the get or post method
  $.get( 'URL', function( r ) {
      // We get the data back from the request 
      // in the parameter we pass in the function
      console.log(r);
  });

// sub this for URL:
// https://data.cityofnewyork.us/api/views/jb7j-dtam/rows.json?accessType=DOWNLOAD

jQuery allows us to create quick get and post requests in one step, as opposed to the above multiple steps.

 

// Full list of options includes:
      // accepts: The content type sent in the request header that tells the server what kind of response it will accept in return
      // async: Set this options to false to perform a synchronous request
      // beforeSend: A pre-request callback function that can be used to modify the jqXHR object before it is sent
      // cache: Set this options to false to force requested pages not to be cached by the browser
      // complete: A function to be called when the request finishes (after success and error callbacks are executed)
      // contents: An object that determines how the library will parse the response
      // contentType: The content type of the data sent to the server
      // context: An object to use as the context (this) of all Ajax-related callbacks
      // converters: An object containing dataType-to-dataType converters
      // crossDomain: Set this property to true to force a cross-domain request (such as JSONP) on the same domain
      // data: The data to send to the server when performing the Ajax request
      // dataFilter: A function to be used to handle the raw response data of XMLHttpRequest
      // dataType: The type of data expected back from the server
      // error: A function to be called if the request fails
      // global: Whether to trigger global Ajax event handlers for this request
      // headers: An object of additional headers to send to the server
      // ifModified: Set this option to true if you want to force the request to be successful only if the response has changed since the last request
      // isLocal: Set this option to true if you want to force jQuery to recognize the current environment as “local”
      // jsonp: A string to override the callback function name in a JSONP request
      // jsonpCallback: Specifies the callback function name for a JSONP request
      // mimeType: A string that specifies the mime type to override the XHR mime type
      // password: A password to be used with XMLHttpRequest in response to an HTTP access authentication request
      // processData : Set this option to false if you don’t want that the data passed in to the data option (if not a string already) will be processed and transformed into a query string
      // scriptCharset: Sets the charset attribute on the script tag used in the request but only applies when the “script” transport is used
      // statusCode: An object of numeric HTTP codes and functions to be called when the response has the corresponding code
      // success: A function to be called if the request succeeds
      // timeout: A number that specifies a timeout (in milliseconds) for the request
      // traditional: Set this to true if you wish to use the traditional style of param serialization
      // type: The type of request to make, which can be either “POST” or “GET”
      // url: A string containing the URL to which the request is sent
      // username: A username to be used with XMLHttpRequest in response to an HTTP access authentication request
      // xhr: A callback for creating the XMLHttpRequest object
      // xhrFields: An object to set on the native XHR object

      /* Options definition referenced from http://www.sitepoint.com/use-jquerys-ajax-function/ */
 

$.ajax({
      url: "https://data.cityofnewyork.us/api/views/jb7j-dtam/rows.json?accessType=DOWNLOAD",

      // Tell YQL what we want and that we want JSON
      data: {
          // q: "select title,abstract,url from search.news where query=\"cat\"",
          format: "json"
      },

      // Work with the response
      success: function( response ) {
          console.log( response ); // server response
      }
});

Get and post methods are very useful and easy to work with, however there will be scenarios where we need more granularity to handle our requests. The $.ajax() method allows us significantly more granularity.

 

Open Weather Map: Independent Practice

Let's bring it all together. Open the main.js file. We will talk with a weather API, and retrieve weather information. Thus far we have worked with just pulling static URLs. Follow the steps below.

  • Sign up for openweathermap.org and generate an API key.

  • User either $.ajax or $.get to pull weather current data for Washington DC (hint: http://api.openweathermap.org/data/2.5/weather?q=...).

  • Print the temperature in console.

  • Bonus 1: add a form prompting user for the city and state.

  • Bonus 2: convert answer from kelvin to fahrenheit.

Conclusion

  • Reiterate the benefits of separation of concerns – API vs. Client.

  • Identify all the HTTP Verbs & their uses.

  • Implement an AJAX request with Vanilla JS.

  • Implement a jQuery AJAX client for a simple REST service.

Additional Resources

Aug 20: AJAX & APIs

By Jessica Bell

Aug 20: AJAX & APIs

  • 129