Objectives |
---|
Students will be able to: |
Give examples of useful APIs |
Explain why we use AJAX |
Use AJAX to GET data from an API |
An Application Program Interface (API) is the way in which you interact with a piece of software. In other words it is the interface for an application or a program.
- Organizations have APIs to publicly expose parts of their program to the outside world, allowing people to send them queries and receive data (e.g. GitHub API ), but this is a narrow view of what the term fully encompasses.
- Remember, even an
Array
has an API. Its API consists of all the methods that can be called on it, such as:.forEach
,.pop
,.length
etc. See the full list:Object.getOwnPropertyNames(Array.prototype)
.
A GUI exists to make an application more convenient for the user. An API does the same for its users, but with a lexical rather than a graphical interface.
Instagram, Food2Fork, Twitter, Spotify, Google Books, Google Maps, WeatherUnderground, etc.
With a partner, spend 10 minutes
- Discussing your understanding of APIs
- Finding an API on the internet, looking at the documentation, and answering these questions:
- What format of data does this API return?
- How would you access the data that you'd likely be interested in? For example, for Giphy, the gif data that we're interested in is located in the
data
array. - Does this API require an API key?
- Can you view an API endpoint url in your browser? Do it!
Asynchronous JavaScript And XML (AJAX) allows us to make requests to a server (ours or another application's) without refreshing the page.
Let's break that down:
Asynchronous - not happening at the same time. Some of your code will be executed at a later time. Specifically, when you hear back from a server about a request you made sometime in the past. This waiting time won't hold up the performance of the rest of your page.
XML - another format for structuring data so that it can be sent and received. XML has mostly been replaced by JSON and AJAX doesn't require the use of XML.
You may also hear the term XMLHttpRequest
. This is the same thing as AJAX! In fact, window
object in the Browser has available to it another object, XMLHttpRequest
. This is how you would make these types of requests without using jQuery.
-
AJAX lets us exchange data with the server behind the scenes. When a change is made on the client we can send off an AJAX Request to notify the server of what just happened. This is an important way to maintain state between a client and a server that communicate in HTTP, an inherently stateless protocol.
-
Limiting page reloads makes our web apps feel faster and mostly gives our users a better experience. Imagine if you experienced a full page refresh every time you "liked" a post on Facebook...
jQuery gives us several methods for making AJAX requests. We're going to stick to using the $.ajax()
method available here.
The HTTP protocol was designed specifically for web browsers and servers to communicate with each other in a request/response cycle.
GET
and POST
are the most common verbs used in HTTP requests:
- A browser will use
GET
to indicate it would like to receive a specific web page or resource from a server. - A browser will use
POST
to indicate it would like to send some data to a server.
Conveniently can use AJAX to make both GET
and POST
requests to servers. From the perspective of the server, it is just another request.
jQuery gives us the $.ajax()
method, which will allow us to perform any AJAX request.
Using jQuery's $.ajax()
method, we can specify several parameters, including:
- What kind of request
- request URL
- data type
- callback function (which will run on successful completion of the AJAX request)
Let's try sending a GET
request to Spotify's API
$.ajax({
// What kind of request
method: 'GET',
// The URL for the request
url: 'https://api.spotify.com/v1/artists/1jTAvg7eLZQFonjWIXHiiT',
// The type of data we want back
dataType: 'json',
// Code to run if the request succeeds; the JSON
// response is passed to the function as an argument.
success: onSuccess
});
// defining the callback function that will happen
// if the request succeeds.
function onSuccess(json) {
console.log(json);
// celebrate!
};
For a POST
request, we can also use the $.ajax()
method, but this time, the data type is "POST"
. Since POST
requests send data to a server, we also need to send an object of data (the book
).
var book_data = {
title: "The Giver",
author: "Lowis Lowry"
};
$.ajax({
method: "POST",
url: "/books", // this is a "relative" link
data: book_data,
dataType: "json",
success: onSuccess
});
function onSuccess(json) {
console.log(json);
// celebrate!
};
We can combine AJAX calls with any jQuery event handlers. You may want to execute an AJAX call when the user clicks and button or submits a form.
var endpoint = 'https://api.spotify.com/v1/search?q=goodbye&type=artist'
// click event on button
$('button').on('click', function(event) {
$.ajax({
method: 'GET',
url: endpoint,
dataType: 'json',
success: onClickReqSuccess
});
});
function onClickReqSuccess(json){
console.log(json);
// process data
}
// submit event on form
$('form').on('submit', function(event){
$.ajax({
method: 'GET',
url: endpoint,
dataType: 'json',
success: onSubmitReqSuccess
});
});
function onSubmitReqSuccess(json){
console.log(json);
// process data
}
We can't guarantee that our API will respond, or will respond quick enough. In these cases the AJAX request will fail or error. Using the jquery.get()
shorthand we can handle these eventualities by "chaining" additional listeners to our initial request:
var endpoint = 'https://api.spotify.com/v1/search?q=come%20together&type=track';
$.ajax({
method: 'GET',
url: endpoint,
dataType: 'json',
success: onSuccess,
error: onError,
complete: onCompletion
});
function onSuccess(json){
/* perform this function if the
status code of the response was in
the 200s */
};
function onError(xhr, status, errorThrown){
/* perform this function if the
response timed out or if the
status code of the response is
in the 400s or 500s (error)
xhr: the full response object
status: a string that describes
the response status
errorThrown: a string with any error
message associated with that status */
};
function onCompletion(json){
/* perform this no matter the status
code of the response */
};
For a solution, checkout the solution
branch or find it here on GitHub.
For a solution to the bonus checkout the solution-more
branch or find it here on GitHub.
- What is CORS?