How to get the data from an API in JavaScript
In this tutorial, we are going to learn about how to make an HTTP get request using JavaScript Fetch API to get the data and how to display that data into the webpage.
Getting started
First, let’s add an html markup that contains a div
element with the id
attribute.
<div id="app"></div>
Getting Data from API
We are making an HTTP get request to the Json Placeholder api using fetch method once the json data receives from the API, we are adding that data into the div
element we just created.
add the following code to your JavaScript file.
const div = document.querySelector("#app");
const url = "https://jsonplaceholder.typicode.com/posts/1";
// sending request
fetch(url).then((response)=>{ return response.json(); // converting byte data to json
}).then(data=>{
const {title, body} = data;
// creating h1 and p elements
const h1 = document.createElement('h1');
const p = document.createElement('p');
// adding content
h1.textContent = title;
p.textContent = body;
// appending to div element
div.appendChild(h1); div.appendChild(p);})
Let’s learn how does the above code work.
-
We accessed the div element using
document.querySelector()
method. -
We initialized a url (or api).
-
The Fetch method accepts the url endpoint as an argument so that we passed
url
, inside thethen()
method we are accessing theresponse
which comes from the api.
- We have used the
response.json()
method to read the response stream and converting that data into json.
- At final, we are creating the two new html elements (h1, p) and adding content to it, then appending to the
div
element.
Output:
Note: By default fetch sends an http get request.
Error handling
If an error occurs during the request, we need to display that error data into the page or logging the errors inside the browser console.
We can get the errors by chaining the fetch with a catch()
method.
const div = document.querySelector('#app');
const url = "https://jsonplaceholder.typicode.com/posts/1";
// sending request
fetch(url).then((response)=>{
return response.json(); // converting byte data to json
}).then(data=>{
const {title, body} = data;
// creating h1 and p elements
const h1 = document.createElement('h1');
const p = document.createElement('p');
// adding content
h1.textContent = title;
p.textContent = body;
// appending to div element
div.appendChild(h1);
div.appendChild(p);
}).catch(error=>{
// logging error
console.log(error);})