Separation of concerns becomes ever more important when working with outside data
Helps us with the separation of outside data or services and are provided through API calls
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:
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)
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.
The first word in the request line, GET, is the HTTP Request's Method.
GET => Retrieve a resource.
[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 version] [status] [reason]
[list of headers]
[response body] # typically HTML, JSON, ...
Code | Reason |
---|---|
200 | OK |
301 | Moved Permanently |
302 | Moved Temporarily |
400 | Bad Request |
403 | Forbidden |
404 | Not Found |
500 | Internal Server Error |
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:
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.
// 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.
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.
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.