JS Evening

Ajax and APIs

Ajax

AJAX stands for Asynchronous JavaScript and XML.

Let's break that down:

As you can probably tell, the definition doesn't paint the whole picture. This happens pretty frequently with buzzwords in technology.

AJAX is a buzzword that arose during the web 2.0 revolution describing techniques used to allow web pages to interact with a server, doing work on the user's behalf without the web browser navigating to a new page.

AJAX incorporates:

Usage

We'll explore the basics of ajax with the demo here, but two very simple examples are below.

You can use the built in XMLHttpRequest object like this:

var request = new XMLHttpRequest();
request.onload = function() {
    console.log(this.responseText);
};
request.open("get", "https://google.com");
request.send();

Or you can use a jQuery method like this:

var request = $.ajax("https://google.com");
request.done(function(response) {
    console.log(response)
})

Exercise

Use jQuery's ajax methods to retrieve your own profile from Treehouse. The URL for a user is https://teamtreehouse.com/username.json for some username.

You'll need to store the resulting object somewhere and eventually assimiliate it into a data structure with multiple users. For now, just put in in a global variable so that you can inspect the object in your browser console.

REST

Reading a definition of what Representation State Transfer (REST) is will make your head spin. It's wordy and technical and all that jazz. In fact, you'll probably find multiple definitions.

REST was originally meant something slightly different. Some programmers started using it to describe APIs they were creating, and it caught on. Now we have many RESTful services, and the differences are overlooked. In general, though, these are the properties of a RESTful API:

Here are a few examples of RESTful requests:

POST   /api/photos
GET    /api/photos/23
PUT    /api/photos/23
DELETE /api/photos/23

For now the important thing to realize is that you may need to change the verb you're using to get an API to work.

Eventually, you'll build your own APIs and you'll need to distinguish different requests as you define how users will interact with your API.

APIs

Many services these days are offering REST APIs. The quality of documentation will vary. Also, there will be certain APIs that require API keys in order to use them. API keys just allow the service to track/limit your usage of the API according to their rules.

Challenge

Play around with the Foursquare API demo in the ajax demo repo.

Build some simple display of a set of results -- for example, display one photo from each venue with a caption that includes the venue's name and a URL if available.

Hint: Notice that the Foursquare demo uses JSONP instead of JSON.