For APIs in the REST (Representational State Transfer) format (which is probably the easiest format to use because of its simplicity), data is fetched via URLs, called API endpoints, and we can access and manipulate the data using standard HTTP methods such as GET, POST, PUT, and DELETE.
For this example, we’ll simply be using the GET Request (as you will for probably most of your API purposes) As an aside, you can pass additional options, called ‘Parameters,’ along with your request after the URL in what’s called a ‘query string.’
Many APIs require a special password for authentication, so the API knows its data isn’t being abused or used for spam. This is called an ‘API Key.’ Most APIs offer free API keys. Some APIs offer payment options (usually a ‘premium’ or ‘pro’ option in addition to the free one, coming with more perks i.e. allows for more GET requests per day).
For our purposes, let’s try this with the Wunderground Weather API.
1. Visit http://www.wunderground.com/weather/api
2. Sign up and log in.
3. Click on the “Pricing” section.
4. Choose the free Default option and click on “Purchase Key.”
5. Fill out the API form and upon completion you will see your Key ID.
jQuery has a method ‘$.ajax()’ to handle our AJAX requests. If we look at the documentation, we see that the method requires us to specify the URL (i.e. API endpoint) that we’re requesting the data from, as well as an optional settings object. The settings object is to specify the data you want to receive from the API, but you can simply pass everything in the settings object to get, well, everything (We’ll go with this second syntax for the tutorial as it’s easier).
With our Wunderground API example:
In this test example, the DOM should print out “It worked!” if the request was successful. Too bad it wasn’t. We get an error here because of the aforementioned cross-website communication browser restriction. The action is blocked when making a simultaneous HTTP request to a different domain than the one the browser is currently viewing, because it could be a potential security threat.
Simply change dataType in the method above and you should see “It worked!” printed on your browser’s console. That means the requested data was fetched. Pretty sweet, right? So we have our data, we’re just not doing anything with it. Note that in our method’s ‘success’ function, we simply ask the console to log the phrase “It worked!” Change this to:
For example, `response.current_observation` would give you the nested current observation object.
You can keep going, accessing the feels like temperateure with ‘response.current_observation.feelslike_c’.
var forRealsiesTemp = response.current_observation.feelslike_c;
and update the DOM:
$(‘p.real-temp’).html(forRealsiesTemp + “C”);