The Fetch API and JSON
What is an API?
An API (Application Programming Interface) is a set of rules that lets two pieces of software communicate with each other. On the web, APIs typically allow your frontend JavaScript to request data from a server, which responds with that data.
For example:
- Your app asks a weather API for today's forecast
- A jobs board asks an API for available listings
- Your profile page asks an API for your account information
What is JSON?
JSON (JavaScript Object Notation) is the most common format for sending and receiving data over the web. It looks like a JavaScript object but has some strict rules:
{
"id": 1,
"name": "Amara Okonkwo",
"role": "student",
"isActive": true,
"courses": ["HTML Basics", "CSS Fundamentals"]
}
Key differences from a JavaScript object:
- All keys must be double-quoted strings
- Trailing commas are not allowed
- Values can be strings, numbers, booleans, arrays, objects, or null
Converting Between JSON and JavaScript
// JavaScript object to JSON string (for sending)
const user = { name: "Amara", age: 24 };
const jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"Amara","age":24}'
// JSON string to JavaScript object (for reading)
const parsed = JSON.parse(jsonString);
console.log(parsed.name); // "Amara"
The Fetch API
The Fetch API is the modern browser API for making HTTP (Hypertext Transfer Protocol) requests. It returns a Promise.
Basic GET Request
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.json()) // Parse the JSON body
.then(data => {
console.log(data.name); // "Leanne Graham"
})
.catch(error => {
console.error("Request failed:", error);
});
The Same Request with Async/Await
async function getUser(id) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
console.log(data.name);
return data;
} catch (error) {
console.error("Failed to fetch user:", error.message);
}
}
getUser(1);
Important: A network error (e.g., no internet) rejects the Promise. But a server error (e.g., 404 Not Found or 500 Server Error) still resolves — you must check response.ok to detect HTTP errors.
Checking Response Status
const response = await fetch("/api/courses");
console.log(response.status); // e.g., 200, 404, 500
console.log(response.ok); // true if status is 200-299
console.log(response.statusText); // "OK", "Not Found", etc.
if (!response.ok) {
throw new Error(`Server error: ${response.status}`);
}
Displaying Fetched Data in the DOM
A common pattern — fetch data, then render it:
async function loadPosts() {
const container = document.querySelector("#posts-container");
container.innerHTML = "<p>Loading...</p>";
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5");
if (!response.ok) throw new Error("Could not fetch posts");
const posts = await response.json();
container.innerHTML = posts
.map(post => `
<div class="post-card">
<h3>${post.title}</h3>
<p>${post.body}</p>
</div>
`)
.join("");
} catch (error) {
container.innerHTML = `<p class="error">Error: ${error.message}</p>`;
}
}
loadPosts();
Key Takeaways
- An API (Application Programming Interface) lets your frontend request data from a server
- JSON (JavaScript Object Notation) is the standard format for web API data; keys must be double-quoted strings
- JSON.stringify() converts a JS object to a JSON string; JSON.parse() converts a JSON string back to an object
- fetch() returns a Promise; always await response.json() as a second step to parse the body
- A fetch() Promise only rejects on network failure; check response.ok to catch HTTP error status codes
- Always show loading and error states when fetching data so users understand what is happening
Practice Exercise
- Use
fetchto load the list of posts fromhttps://jsonplaceholder.typicode.com/posts?_limit=10 - Display the title of each post in an unordered list in the DOM
- Add a loading message before the fetch starts and replace it when data arrives
- Handle errors by displaying a friendly error message in the DOM if the fetch fails
Try it yourself
Key Takeaways
- An API (Application Programming Interface) enables your frontend to request data from a server over the network
- JSON (JavaScript Object Notation) is the standard web data format; keys must be double-quoted strings
- JSON.stringify() converts objects to JSON strings; JSON.parse() converts JSON strings back to objects
- fetch() returns a Promise; response.json() parses the response body as a second async step
- fetch() only rejects on network failure; always check response.ok to detect 4xx and 5xx HTTP errors
- Always show loading and error states in the UI so users know what is happening during async requests
Quick Quiz
1.Why must you call response.json() after fetch() — why doesn't fetch() return the data directly?
2.What does response.ok return in the Fetch API?
3.What is wrong with this JSON? { name: 'Amara', age: 24 }
4.Which method converts a JavaScript object into a JSON string?
Ready to go further?
CareerEx gives you structured 12-week training, live classes every Saturday and Sunday, real tutor feedback, and a certificate. Join the next cohort.
Join CareerEx