Working with APIs in JavaScript allows web applications to fetch data from servers and display or use it dynamically. APIs make it possible for applications to exchange data between different systems and services.
- APIs can be used to fetch, send, update, or delete data.
- JavaScript commonly uses the Fetch API to make API requests.
- API responses are often returned in JSON format.
- The retrieved data can be accessed and displayed dynamically using DOM manipulation.
Approach: Fetching and Displaying API Data Using fetch()
The fetch() method sends a request to an API and returns a Promise containing the response.
The process involves the following steps:
- Send a request to the API using fetch().
- Wait for the response using async/await.
- Convert the response into JSON using response.json().
- Extract the required information from the JSON data.
- Display the retrieved information in HTML elements.
Example: In this example, JavaScript fetches random user data from an API and displays the user's name, email, phone number, age, gender, location, and profile image on the webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Working with APIs in JavaScript</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 40px;
}
#userCard {
width: 350px;
margin: auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
}
#userImage {
width: 150px;
border-radius: 50%;
}
p {
text-align: left;
}
</style>
</head>
<body>
<h1>Random User Information</h1>
<div id="userCard">
<img id="userImage"
src=""
alt="User Profile">
<h2 id="name">Loading...</h2>
<p>
<strong>Email:</strong>
<a id="email"></a>
</p>
<p>
<strong>Phone:</strong>
<a id="phone"></a>
</p>
<p>
<strong>Age:</strong>
<span id="age"></span>
</p>
<p>
<strong>Gender:</strong>
<span id="gender"></span>
</p>
<p>
<strong>Location:</strong>
<span id="location"></span>
</p>
<p>
<strong>Country:</strong>
<span id="country"></span>
</p>
</div>
<script>
const apiURL = "https://randomuser.me/api/";
async function getUser() {
try {
// Fetch data from the API
const response = await fetch(apiURL);
// Check whether the request was successful
if (!response.ok) {
throw new Error(
"Failed to fetch user data"
);
}
// Convert the response to JSON
const data = await response.json();
// Get the first user from the results array
const user = data.results[0];
// Extract user information
const { title, first, last } = user.name;
const {
gender,
email,
phone
} = user;
const age = user.dob.age;
const {
city,
state,
country
} = user.location;
const image = user.picture.large;
// Create the full name
const fullName =
`${title}. ${first} ${last}`;
// Display the user information
document.getElementById("name")
.textContent = fullName;
document.getElementById("email")
.textContent = email;
document.getElementById("email")
.href = `mailto:${email}`;
document.getElementById("phone")
.textContent = phone;
document.getElementById("phone")
.href = `tel:${phone}`;
document.getElementById("age")
.textContent = age;
document.getElementById("gender")
.textContent = gender;
document.getElementById("location")
.textContent = `${city}, ${state}`;
document.getElementById("country")
.textContent = country;
document.getElementById("userImage")
.src = image;
}
catch (error) {
document.getElementById("name")
.textContent =
"Unable to load user data.";
console.error(error);
}
}
// Call the function
getUser();
</script>
</body>
</html>
Output: