INTRODUCTION
API consumption or API fetching refers to the process of accessing and using data or services provided by an Application Programming Interface (API). Almost all websites use APIs to communicate with their backends or servers. APIs contain important information that you may want to show in the front-end of your website, such as a weather forecast or current crypto prices. In this tutorial, we will show you how to consume an API using JavaScript.
Requirements
- Basic knowledge of HTML, CSS and Javascript
- an IDE (example: VScode)
Step 1: Creating the HTML template
Before we start writing JavaScript code, we need to create the HTML template. Here is a sample template that you can use as a reference. You can also use an image as a placeholder until you get your API up and running.
Step 2: Finding an API
We will use 2 API links in this tutorial
https://xsgames.co/randomusers/avatar.php?g=male
This is for the profile image
https://randomuser.me/api/
This is for the user details.
We are using different links because the image in the second API isn't working, so we had to find another API that provides only images.
Step 3: Fetching data from the API
Now that we have the necessary API links, we can start consuming them. Let's start with the image. We will simply put the link for the image API inside the src attribute of the img tag in our HTML template.
<div class="imghold">
<img src="https://xsgames.co/randomusers/avatar.php?g=male" alt="">
</div>
This should generate a random image every time you reload the page.
STEP 4
In your javascript file, we will assign the API link to a constant variable so that we can reuse it throughout our code.
const url = "https://randomuser.me/api/"
Doing this will make our link reuseable so if you want to use your link anywhere else on your code, you can just call the url variable.
NOTE: Its a constant so you wont be able to change its value anywhere eles in your code
Lets use an in-built Javascript function called fetch. fetch() is a built-in function in JavaScript that is used to make network requests and retrieve resources from a server using the Fetch API.
fetch(url)
This will return a promise, which either resolves or rejects. If you are not familiar with promises, think of them as sending someone on an errand to go and get something. The person either comes back with what you sent them to get (resolved) or comes back without it (rejected).
When we log out fetch(url) to the console, we get a pending promise because the data has not yet been returned from the API.
This is because at the time this promise fetch url was logged out, it didnt come back with the information from the API yet, so we get pending promise instead of the actual data.
To handle this issue, we can use the then() method to register a callback function that will be called when the Promise is resolved successfully. Within the callback function, we can then extract the JSON data using the json() method and use it in our code.
.then(resolve => resolve.json())
This attaches a callback function to the Promise object returned by fetch(). The callback function takes the resolved Response object as its argument and calls the json() method on it to extract the JSON data from the response. The json() method also returns a Promise object that resolves to the parsed JSON data.
Since it returns another promise, we have to use a then function again so we can get the json data
.then(data => {console.log(data)})
if you console.log data, it will give you an object containing all the information you want
This is a complex object containing arrays and other objects inside, so you have to navigate through to get what you want. If you dont know how, just know that you use dot nothation (.) to navigate an object, by calling the key (example: object.key, this will give you the value of that key) or if you want to navigat an array, you use box notation ([]) by inputting the index, Note that the index of an array starts from 0, so the first item in the array has an index of 0 (example: myArr[1], this will get the second item in myArr). This is how mine looks.
const url = "https://randomuser.me/api/"
fetch(url)
.then(resolve => resolve.json())
.then(data => {
let name = `${data.results[0].name.title} ${data.results[0].name.first} ${data.results[0].name.last}`
document.querySelector("#name").innerHTML = name
document.querySelector("#email").innerHTML = data.results[0].email
document.querySelector("#phone").innerHTML = data.results[0].phone
document.querySelector("#age").innerHTML = data.results[0].dob.age
document.querySelector("#gender").innerHTML = data.results[0].gender
})
.catch((err) => {
console.log(err);
})
We also add a catch() method to catch any errors that may occur during the fetch() request, which can help us debug any issues and handle them appropriately.
This is my final result
To conclude, consuming APIs is an essential part of modern web development, and with the Fetch API, it has become easier than ever to interact with web services and retrieve data. We learned that fetch() is a Promise-based function that returns a Promise object, which resolves to the Response object representing the response to our request. We also learned that the Response object provides a set of methods to extract the data we need, and that we can chain these methods together using the then() method.
In addition, we explored the json() method, which is used to extract JSON data from a Response object, and how we can use dot and box notation to navigate complex objects and arrays. Finally, we saw an example of how to use fetch() to consume an API and update a web page with the retrieved data.
Overall, fetch() is a powerful and flexible tool that can be used to interact with a wide variety of APIs, and with some practice, you can leverage it to create dynamic and engaging web applications.
Top comments (1)
Thank you so much, very useful and explaining in simple terms with no further complexity. Thank you