Working with APIs in JavaScript
Last Updated :
18 Apr, 2025
An API is simply a medium to fetch or send data between interfaces. Let's say you want to make an application that provides the user with some real-time data fetched from the server or maybe even allows you to modify or add data to some other endpoint. This is made possible by the API or the Application Programming Interface.
We will use a simple public API that requires no authentication and allows you to fetch some data by querying the API with GET requests.
https://randomuser.me/ is a website that provides dummy data for random users that we can easily work with. We can get the response by requesting https://randomuser.me/api/. The JSON response that we receive is in the following format.
JavaScript
{
"results": [
{
"gender": "female",
"name": {
"title": "Miss",
"first": "Nina",
"last": "Simmmons"
},
"location": {
"street": {
"number": 970,
"name": "Eason Rd"
},
"city": "Fullerton",
"state": "Wyoming",
"country": "United States",
"postcode": 57089,
"coordinates": {
"latitude": "83.1807",
"longitude": "104.7170"
},
"timezone": {
"offset": "+8:00",
"description":
"Beijing, Perth, Singapore, Hong Kong"
}
},
"email": "[email protected]",
"login": {
"uuid": "bd0d135f-84df-4102-aa4f-5baaa41baf5c",
"username": "yellowfrog722",
"password": "dawg",
"salt": "q28gdiyN",
"md5": "291987daea22bb91775226574925b271",
"sha1": "a0463a26ea5c2ff4f3ad498fd01c5994926e5021",
"sha256":
"6583eb74ca08bfac50b3b29aa52c9f02ea5d9d017fef0e5a5a6fae4f5225f928"
},
"dob": {
"date": "1980-11-01T23:10:05.403Z",
"age": 40
},
"registered": {
"date": "2013-04-02T02:26:52.904Z",
"age": 7
},
"phone": "(216)-693-7015",
"cell": "(501)-534-9413",
"id": {
"name": "SSN",
"value": "847-09-2973"
},
"picture": {
"large":
"https://randomuser.me/api/portraits/women/60.jpg",
"medium":
"https://randomuser.me/api/portraits/med/women/60.jpg",
"thumbnail":
"https://randomuser.me/api/portraits/thumb/women/60.jpg"
},
"nat": "US"
}
],
"info": {
"seed": "82a8d8d4a996ba17",
"results": 1,
"page": 1,
"version": "1.3"
}
}
Next, you need to have an HTML file for the frontend where you want to display the retrieved data.
We can use either the "div" tag (block-level) or the "span" tag (inline-level), which will act as a placeholder for the information. Using the "id" attribute, we can get the required "div/span" container where we want to place the information.
HTML
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content=
"width=device-width, initial-scale=1.0" />
<link id="favicon" rel="icon"
href="" sizes="16x16" />
<!-- font-awesome library to make the
webpage more appealing -->
<link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>
<div class="content">
<div class="head">
<h1 id="head"></h1>
</div>
<div class="email">
<i class="fa fa-envelope" style=
"font-size: 15px; color: blue;"></i>
<a href="" id="email"> </a>
</div>
<div class="phone">
<i class="fa fa-phone" style=
"font-size: 15px; color: blue;"></i>
<a href="" id="phone"> </a>
</div>
<br />
<div id="user-img"></div>
<br />
<div class="details">
<table>
<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>
CSS
.content {
text-align: center;
padding: 30px;
margin: 0px auto;
}
.details {
margin-left: auto;
margin-right: auto;
}
img {
border-radius: 5px;
box-shadow: black;
}
table,
td {
border-collapse: collapse;
margin-left: auto;
margin-right: auto;
text-align: center;
padding: 10px;
border: 1px solid black;
}
JavaScript
<script>
const api_url = "https://randomuser.me/api/";
async function getUser() {
// Making an API call (request)
// and getting the response back
const response = await fetch(api_url);
// Parsing it to JSON format
const data = await response.json();
console.log(data.results);
// Retrieving data from JSON
const user = data.results[0];
let { title, first, last } = user.name;
let { gender, email, phone } = user;
let image = user.picture.large;
let image_icon = user.picture.thumbnail;
let age = user.dob.age;
let { city, state, country } = user.location;
let fullName = title + ". " + first + " " + last;
document.title = fullName;
// Accessing the div container and modify/add
// elements to the containers
document.getElementById("head").innerHTML = fullName;
document.getElementById("email").href = "mailto:" + email;
document.getElementById("email").innerHTML = email;
document.getElementById("phone").href = "tel:" + phone;
document.getElementById("phone").innerHTML = phone;
// accessing the span container
document.querySelector("#age").textContent = age;
document.querySelector("#gender").textContent = gender;
document.querySelector("#location").textContent
= city + ", " + state;
document.querySelector("#country").textContent = country;
// Creating a new element and appending it
// to previously created containers
let img = document.createElement("img");
let img_div = document.getElementById("user-img");
img.src = image;
img_div.append(img);
const favicon = document.getElementById("favicon");
favicon.setAttribute("href", image_icon);
}
// Calling the function
getUser();
</script>
The script tag will contain the code that will make the API request and handle the response. This needs to be placed within the body tag or as a separate file.
We use the async/await function that basically ensures that the data is displayed even after the page is loaded.
You can use the console.log(...) method to check if the user is retrieving the correct piece of information. The output for the same can be seen by opening the console window in your web browser (Right Click -> Inspect -> Console or Ctrl+Shift+J in Chrome/Edge).
Output:

Want to explore the APIs more and dive deeper into them, Refer to Public APIs which have a vast collection of publicly available APIs to fuel your API exploration journey.
To test an API for the type of response it gives Postman is an amazing application that will fulfill all your needs. You can use Postman API development article to get an insight into, how to use it. Another alternative is Postman APIs which will help you do the same task on the browser itself.
Similar Reads
Products/Apps Built Using JavaScript JavaScript, one of the most versatile programming languages, powers various products and applications across multiple industries. JavaScript has become the backbone of modern web development, from dynamic websites to full-scale applications. Below are some well-known products and apps built using Ja
3 min read
What is JavaScript? JavaScript is a powerful and flexible programming language for the web that is widely used to make websites interactive and dynamic. JavaScript can also able to change or update HTML and CSS dynamically. JavaScript can also run on servers using tools like Node.js, allowing developers to build entire
6 min read
Fetch API in JavaScript The Fetch API is a modern interface in JavaScript that allows you to make HTTP requests. It replaces the older XMLHttpRequest method and provides a cleaner and more flexible way to fetch resources asynchronously. The Fetch API uses Promises, making it easier to work with asynchronous data.Syntaxfetc
6 min read
How JavaScript Works? JavaScript is a dynamically typed, cross-platform threaded scripting and programming language, used to put functionality and interactivity at the client side as well as to write logic on the server side of a website. It can display content updates, interactive maps, control multimedia, interactive f
13 min read
How to connect to an API in JavaScript ? An API or Application Programming Interface is an intermediary which carries request/response data between the endpoints of a channel. We can visualize an analogy of API to that of a waiter in a restaurant. A typical waiter in a restaurant would welcome you and ask for your order. He/She confirms th
5 min read