The Fetch API is how JavaScript talks to the internet. One function, fetch(), sends a request and returns a promise — and with it you can load data from any public API without a library. It is the first API skill every front-end developer needs.
The simplest fetch loads JSON and does something with it:
async function getBooks() {
const response = await fetch(
"https://openlibrary.org/search.json?q=psychology&limit=5"
);
const data = await response.json();
console.log(data.docs.map((book) => book.title));
}
getBooks();
Three steps, every time: fetch the URL, await response.json() to parse the body, then use the data. fetch does not throw on a 404 or 500 — it only throws on network failure — so check response.ok yourself:
async function getBooks() {
try {
const response = await fetch(
"https://openlibrary.org/search.json?q=psychology&limit=5"
);
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const data = await response.json();
return data.docs;
} catch (error) {
console.error("Could not load books:", error);
return [];
}
}
Rendering the results is plain DOM work. Show a loading state first, then replace it with the data — users should never stare at a blank page wondering if anything is happening:
async function renderBooks() {
const list = document.getElementById("book-list");
list.textContent = "Loading books...";
const books = await getBooks();
list.innerHTML = books
.map((book) => `<li>${book.title} — ${book.author_name?.[0] || "Unknown"}</li>`)
.join("");
}
If you want a ready-made reading list instead of searching yourself, here are the best psychology books for beginners in India — a good starting point before you build your own book app around them.
Posting data is the same function with an options object. The method, headers, and a JSON body are all you need:
async function addBook(book) {
const response = await fetch("https://api.example.com/books", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(book),
});
return response.json();
}
Two mistakes beginners make: first, forgetting that fetch is asynchronous — logging the result outside the await gives you a pending promise, not data. Second, calling response.json() twice, which fails because the body stream can only be read once.
Ways to extend it: add an AbortController to cancel a request when the user types a new search, cache responses so repeat searches are instant, and handle pagination by reading the API's page or offset parameter. Once fetch clicks, every "load data from the internet" feature is the same pattern.
Top comments (0)