How to consume Restful API with Vanilla JavaScript
In this tutorial, we are going to look at how to use JavaScript to consume a Restful API. For better illustration of the concept, we are going to have a bit of HTML and CSS. We will use fetch API and async .. await
Photo by ThisIsEngineering from Pexels
1. Create index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch API</title>
<link rel="stylesheet" href="./main.css">
</head>
<body>
<h2>List of courses</h2>
<table id="course-table">
</table>
<script src="./app.js"></script>
</body>
</html>
2. Create app.js
const courseTable = document.getElementById('course-table');
const baseLink = 'https://www.smart-investment.club/ercapi';
//Get token from local storage
const token = localStorage.getItem('accessToken');
let myHeaders = new Headers();
myHeaders.append('Application-Key', 'YOUR-APP-KEY'); //replace YOUR-APP-KEY with the real key
myHeaders.append('Authorization', 'Bearer ' + token);
myHeaders.append('Content-Type', 'application/json');
let requestOptions = {
headers: myHeaders,
};
//Add table headers
courseTable.innerHTML = `<tr>
<th>Id</th>
<th>Name</th>
<th>#participants</th>
</tr>`;
//Get a list of courses
const getCourses = async () => {
if (!token) {
console.log('Login first');
}
requestOptions.method = 'GET';
const response = await fetch(baseLink + '/api/courses', requestOptions);
if (response.status === 200) {
const data = await response.json();
const courses = data.content;
//Add courses to the table
courses.forEach((course) => {
const tr = document.createElement('tr');
tr.innerHTML = `<td>${course.id}</td>
<td>${course.name}</td>
<td>${course.numParticipants}</td>`;
courseTable.appendChild(tr);
});
} else {
const div = document.createElement('div');
const message = `Something went wrong with your request (${response.status})`;
div.innerHTML = message;
document.body.appendChild(div);
}
};
getCourses();
3. Add Basic style: main.css
h2 {
font-weight: 500;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 50%;
}
th {
background-color: dodgerblue;
color: #f5f3f3;
}
td,
th {
border: 1px dotted #f5f3f3;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #f5f3f3;
}
td:nth-child(3) {
text-align: center;
}