APIs, Fetch & JSON
Duration: 30 min
APIs (Application Programming Interfaces) allow applications to communicate with each other. The Fetch API lets JavaScript request data from servers. JSON is the standard format for exchanging data. Together, they enable dynamic, data-driven web applications.
What is an API?
An API is a set of rules for how software components communicate. A REST API uses HTTP methods to perform operations:
- GET: Retrieve data
- POST: Create new data
- PUT: Update existing data
- DELETE: Remove data
Example API endpoints:
GET /api/users → Get all users
GET /api/users/123 → Get user with ID 123
POST /api/users → Create a new user
PUT /api/users/123 → Update user 123
DELETE /api/users/123 → Delete user 123JSON: Data Format
JSON (JavaScript Object Notation) is a lightweight data format:
{
"name": "Alice",
"age": 28,
"email": "alice@example.com",
"active": true,
"skills": ["JavaScript", "Python", "CSS"],
"address": {
"street": "123 Main St",
"city": "New York",
"zip": "10001"
}
}JSON supports:
- Strings:
"text" - Numbers:
42,3.14 - Booleans:
true,false - Null:
null - Arrays:
[1, 2, 3] - Objects:
{ key: value }
The Fetch API
Fetch makes HTTP requests from JavaScript:
// Basic GET request
fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
// GET with error handling
fetch("https://api.example.com/users/123")
.then(response => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
// POST request with data
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Bob",
email: "bob@example.com"
})
})
.then(response => response.json())
.then(data => console.log("Created:", data));
// PUT request to update
fetch("https://api.example.com/users/123", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Alice Updated",
age: 29
})
})
.then(response => response.json())
.then(data => console.log("Updated:", data));
// DELETE request
fetch("https://api.example.com/users/123", {
method: "DELETE"
})
.then(response => response.json())
.then(data => console.log("Deleted:", data));Promises and Async/Await
Promises handle asynchronous operations:
// Promise with .then()
let promise = fetch("https://api.example.com/users");
promise
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// Promise states
// Pending: operation hasn't completed
// Fulfilled: operation succeeded
// Rejected: operation failed
// Creating a promise
let myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Success!");
}, 1000);
});
myPromise.then(result => console.log(result));Async/Await
Modern syntax for handling promises:
// Async function
async function getUser(id) {
try {
let response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error("User not found");
}
let data = await response.json();
return data;
} catch (error) {
console.error("Error:", error);
}
}
// Call async function
getUser(123).then(user => console.log(user));
// Async function with POST
async function createUser(userData) {
try {
let response = await fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(userData)
});
let data = await response.json();
return data;
} catch (error) {
console.error("Error:", error);
}
}
// Multiple async operations
async function loadUserAndPosts(userId) {
try {
let userResponse = await fetch(`https://api.example.com/users/${userId}`);
let user = await userResponse.json();
let postsResponse = await fetch(`https://api.example.com/users/${userId}/posts`);
let posts = await postsResponse.json();
return { user, posts };
} catch (error) {
console.error("Error:", error);
}
}Displaying API Data
Fetch data and update the page:
// Fetch and display user list
async function displayUsers() {
try {
let response = await fetch("https://api.example.com/users");
let users = await response.json();
let list = document.querySelector("#user-list");
list.innerHTML = "";
users.forEach(user => {
let item = document.createElement("li");
item.textContent = `${user.name} (${user.email})`;
list.appendChild(item);
});
} catch (error) {
console.error("Error:", error);
}
}
// Call on page load
document.addEventListener("DOMContentLoaded", displayUsers);
// Search functionality
let searchInput = document.querySelector("#search");
searchInput.addEventListener("keyup", async (e) => {
let query = e.target.value;
try {
let response = await fetch(`https://api.example.com/users?search=${query}`);
let results = await response.json();
let list = document.querySelector("#results");
list.innerHTML = "";
results.forEach(user => {
let item = document.createElement("div");
item.innerHTML = `<h3>${user.name}</h3><p>${user.email}</p>`;
list.appendChild(item);
});
} catch (error) {
console.error("Error:", error);
}
});
// Form submission with API
let form = document.querySelector("form");
form.addEventListener("submit", async (e) => {
e.preventDefault();
let formData = new FormData(form);
let userData = Object.fromEntries(formData);
try {
let response = await fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(userData)
});
if (response.ok) {
alert("User created successfully!");
form.reset();
}
} catch (error) {
console.error("Error:", error);
}
});❓ What does REST API stand for?
❓ What does JSON stand for?
❓ Which HTTP method is used to create new data?
❓ What does response.json() do?
❓ What is async/await used for?