How to Call API in JavaScript
-
Use the
Getuser()Function to Call and Get Response of the API in JavaScript -
Create Another API to Send a
POSTRequest in JavaScript
API stands for Application Programming Interface, which means it is a collection of protocols and definitions for developing & integrating different software applications.
An API is a way to send and fetch information between various interfaces and in real-time from the server or send data to the server.
Use the Getuser() Function to Call and Get Response of the API in JavaScript
We will use a public API and save the URL in the api_url variable. You can refer to more public APIs here.
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div class="content">
<div class="details">
<h2>Random User's Details</h2>
<table>
<tr>
<td>Full Name</td>
<td><span id="fullname"></span></td>
</tr>
<tr>
<td>Age</td>
<td><span id="age"></span></td>
</tr>
<tr>
<td>Gender</td>
<td><span id="gender"></span></td>
</tr>
<tr>
<td>Location</td>
<td><span id="location"></span></td>
</tr>
<tr>
<td>Country</td>
<td><span id="country"></span></td>
</tr>
</table>
</div>
</div>
</body>
</html>
.content {
text-align: center;
padding: 30px;
margin: 0px auto;
}
.details {
margin-left: auto;
margin-right: auto;
}
table,
td {
border-collapse: collapse;
margin-left: auto;
margin-right: auto;
text-align: center;
padding: 10px;
border: 1px solid black;
}
const api_url = 'https://randomuser.me/api/';
async function getUser() {
// making a call to API
const response = await fetch(api_url);
// converting it to JSON format
const data = await response.json();
// getting data/information from JSON
const user = data.results[0];
let {first, last} = user.name;
let {gender, email, phone} = user;
let age = user.dob.age;
let {city, state, country} = user.location;
let fullName = first + ' ' + last;
// getting access to the span container
document.querySelector('#fullname').textContent = fullName;
document.querySelector('#age').textContent = age;
document.querySelector('#gender').textContent = gender;
document.querySelector('#location').textContent = city + ', ' + state;
document.querySelector('#country').textContent = country;
}
// Calling the getUser() function
getUser();
To check the output, we can open the console window by pressing Ctrl+Shift+J in Google Chrome and Edge or by going to Right Click -> Inspect -> Console.
OUTPUT:

We can ensure that the information is visible even after the page is loaded fully by using async and await.
Async and await are used for asynchronous programming. The Async always makes sure that a Promise is returned because it always gives value back.
And, if it doesn’t, then the JavaScript immediately wraps it in a Promise that is solved with its value. We use the await function to wait for the Promise.
This can only be used within the async block. The await function makes the async block wait until the result is returned by a Promise.
The fetch() method takes the URL as a parameter and fetches the required resources asynchronously over the network.
Create Another API to Send a POST Request in JavaScript
const api_url = 'https://httpbin.org/post';
async function getUser() {
const response = await fetch(api_url, {
method: 'POST',
headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
body: JSON.stringify({
fullname: 'Thomas John',
age: 33,
gender: 'male',
location: 'Miam',
country: 'USA'
})
});
const data = await response.json();
console.log(data);
}
// Calling the function
getUser();
The result returned by this method is known as response. We parse this response into JSON using response.json().
We retrieve the data/information from the JSON and save it in different variables using Destructuring Assignment. After that, we get access to the <span> container and modify their textContent.
OUTPUT (JSON):
{
args: { ... },
data: "{\"fullname\":\"Thomas John\",\"age\":33,\"gender\":\"male\",\"location\":\"Miam\",\"country\":\"USA\"}",
files: { ... },
form: { ... },
headers: {
Accept: "application/json",
Accept-Encoding: "gzip, deflate, br",
Accept-Language: "en-GB,en-US;q=0.9,en;q=0.8,ur;q=0.7",
Content-Length: "85",
Content-Type: "application/json",
Host: "httpbin.org",
Origin: "https://fiddle.jshell.net",
Referer: "https://fiddle.jshell.net/",
Sec-Ch-Ua: "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"98\", \"Google Chrome\";v=\"98\"",
Sec-Ch-Ua-Mobile: "?0",
Sec-Ch-Ua-Platform: "\"Windows\"",
Sec-Fetch-Dest: "empty",
Sec-Fetch-Mode: "cors",
Sec-Fetch-Site: "cross-site",
User-Agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36",
X-Amzn-Trace-Id: "Root=1-6207e40f-1146923e2704c7e8542bf54e"
},
json: {
age: 33,
country: "USA",
fullname: "Thomas John",
gender: "male",
location: "Miam"
},
origin: "119.153.33.34",
url: "https://httpbin.org/post"
}
We are using JSON.stringify() to convert into a string because the value of body can only be the string or an object.
