We will be building a Single Page Application that uses the Nobel Prize API.
New concepts covered during this lecture:
- Creating a Single Page Application (SPA) (vs. a multi-page application)
- Calling a server-side web API with XMLHttpRequest.
- Using asynchronous callbacks in conjunction with XMLHttpRequest.
- Applying the DRY principle (Don't Repeat Yourself) by creating functions that replace repetitive code.
- Reducing the complexity of larger code blocks by extracting small code fragments into separate, appropriately named functions.
Google "what is an api":
API
noun
computing
a set of functions and procedures allowing the creation of applications that access the features or data of an operating system, application, or other service.
We will specifically be dealing with server-side web APIs:
A server-side web API is a programmatic interface consisting of one or more publicly exposed endpoints to a defined request–response message system, typically expressed in JSON or XML, which is exposed via the web—most commonly by means of an HTTP-based web server.
Source: Wikipedia - Web API
Watch this YouTube video [3.24 mins]: What is an API?
In this lecture we will be using the Nobel Prize API:
This API provides data that "contains information about who has been awarded the Nobel Prize, when, in what prize category and the motivation, as well as basic information about the Nobel Laureates such as birth data and the affiliation at the time of the award."
You can try out the API by clicking the link provided above. For instance, to get data about all the female Nobel Prize laureates, press the GET Laureate
button, scroll down on the resulting page and enter json
in the format field and female
in the gender field, as shown in the figure below. Then press the green Try it! button.
The JSON response will be as shown below.
Note the URL field: we will be using similar URLs in the code examples to fetch JSON data from the Nobel Prize API.
Folder | Description |
---|---|
1‑base | A bare bones example using XMLHttpPRequest. |
2‑function | Extracts reusable code into a function that takes a URL and a callback parameter. |
3‑json | Sets the response type from default (text) to json. |
4‑errors | Add error handling using a node-style callback. |
5‑render-pre | Render API data as JSON to the page using a <pre> tag. |
6‑render-ul | Use DOM manipulation to create a <ul> element and populate it with <li> elements using laureate data obtained from the Nobel Prize API. |
7‑dry | Apply the DRY principle by creating the createAndAppend() function to reduce repetitive code. |
8‑dryer | Enhance createAndAppend() to take an optional text parameter. |
9-input | Add <input> element for country code. |
10-dryest | Finalize createAndAppend functionality. |
11-select | Get country info from the API and render in a <select> element. |
12-combine | Combine <select> element with laureates data. |
13‑final | Render laureate details and add CSS styling. |