CS571 API Requests with Javascript

Prerequisites: Solid understanding to Javascript fundamentals
lecture video(web dev basic 2)

APIs and The DOM(Document Object Model) API

Application Programming Interfaces(APIs) is a bit like ADTs om data structures. Without knowing the underlying principles, we can use properties assigned to the ADT and carry out our implementation. API, on the other hand, allows us to use complex functionalities using simple syntax in our actual code.

Typically, there are many kinds of APIs, here we introduce the first kind:

  • Browser API

Browser API is a set of built-in tools that browsers provide to bridge JavaScript code and the browser’s internal features.

The most commonly used browser API is DOM

DOM

As you can see, the DOM abstracts the whole HTML file into a tree-like structured object document, where every element is a node. We use Javascript to read and change the tree.

  • Finding and selecting elements::
1
2
3
4
5
document.getElementById("id");
document.getElementsByClassName("class name");
document.getElementsByTagName("tag name")
document.querySelector("css selector") //returns the first match
document.querySelectorAll("css selector") //returns all the matches

Making API request with Javascript - The fetch API

syntax:

  • fetch(request): make the request to the url, and allows you to set the:
    • HTTP method: by default is GET, you can also set to POST, DELETE, PUT, etc.
    • header: custom request headers
    • body: the msg to send, usually JSON or HTML form data.
  • .then(response => response.json()): parse the body into JSON
  • .catch(): handle errors like no internet connection or unauthorised access. When the status code is not 200 OK, usually something is wrong.
1
2
3
4
5
6
7
8
fetch("https://official-joke-api.appspot.com/random_joke")
.then(response => response.json()) // parse JSON
.then(data => {
console.log(data);
// Example output: { setup: "Why did the...", punchline: "Because..." }
document.body.innerHTML += `<p>${data.setup} - ${data.punchline}</p>`;
})
.catch(error => console.error("Error:", error));

Tip: the fetch request happens asynchronously, which means that the request and respond happens in a new thread.
if I write:

1
2
3
fetch(url)
...
console.log("Asynchronously")

the massage “Asynchronously” is printed out before the fetch response.

Under the Hoods

If we only want to retrieve data use a simple get request, we only need to use fetch(url)

However, if we print out the result of the fetch, we get a new data, promise.

We can see promise as a placeholder for future data to fill, eventually we can receive a response from the requested url, then we can do something about the promise:

Usually, after the server returns a response, we need to parse the promise into JSON.

1
2
3
const response = fetch("https://api.thecatapi.com/v1/images/search");
response.then(this.json);
console.log(response);