JavaScript Fetch API: Get Data From an API and Show It

The Fetch API is the built-in way for JavaScript in a browser to request data from a server. You call fetch() with a URL, and it returns a promise that resolves to a response object. You then read the body of that response, usually as JSON, and use the resulting data to update the page.
A fetch request does not reload the page. That is what makes it useful for a list that updates on a button click, a search result that appears below a form, or a detail panel that loads only when a reader asks for it. This guide works through a basic request, reading JSON, handling errors, and showing the result with the DOM, in that order.
Make a basic request
A basic fetch call takes a URL string and returns a promise. The code below uses async and await to wait for the response, which reads more like a sequence of steps than nested callbacks. The URL in the example is a placeholder for your own API, and you should replace it with a real endpoint you are allowed to use.
The response object holds the status and headers, and it also holds methods for reading the body. Calling response.json() reads the body and parses it as JSON, and that call returns another promise. A common beginner error is to try to use the response object itself as data, before the body has been read.
async function loadPosts() {
const response = await fetch("https://example.com/api/posts");
const data = await response.json();
console.log(data);
}
loadPosts();
This version logs the data so you can inspect its shape in the console before building any display code. Checking the shape first saves time, because display code written against a guessed shape breaks as soon as the real shape differs. The guide to JavaScript basics: variables and functions covers the async function form used here, and the guide to JavaScript arrays and objects covers the list and record shapes that API data usually takes.
Check the response before using it
Fetch resolves its promise even when the server returns an error status, such as a missing page or a failed request. That behaviour surprises many beginners, because a failed request still reaches the next line of code. The fix is to check response.ok, which is true for a successful status and false for an error status, and to throw an error when it is false.
A network failure is different. If the browser cannot reach the server at all, the fetch promise rejects, and that rejection is caught by a try and catch block around the call. Handling both cases, error status and network failure, covers the two ways a request can fail in practice. Without both checks, a page can show a blank area with no clue about what went wrong.
async function loadPosts() {
try {
const response = await fetch("https://example.com/api/posts");
if (!response.ok) {
throw new Error("Request failed");
}
const data = await response.json();
return data;
} catch (error) {
console.error(error);
return [];
}
}
Returning an empty list on failure keeps the display code simple, because it can always loop over a list, even when that list is empty. The display code then shows a message when the list is empty, instead of crashing on missing data. That pattern also makes the error visible in the console during development, while the page stays usable.
Show the data on the page
Display code takes the data and turns it into elements on the page. The example below finds a list element by id, clears its old content, and adds one list item per post title. It uses textContent for the title, which treats the title as plain text and avoids inserting markup from the data into the page.
Show a loading message before the request starts, in the same element where the data will appear. Replace that message when the request finishes, either with the list or with an error message. A reader who sees a loading message knows the request is in progress, and a reader who sees an error message knows the request finished without usable data.
async function showPosts() {
const list = document.getElementById("post-list");
list.textContent = "Loading posts...";
const posts = await loadPosts();
list.textContent = "";
if (posts.length === 0) {
list.textContent = "No posts could be loaded.";
return;
}
for (const post of posts) {
const item = document.createElement("li");
item.textContent = post.title;
list.appendChild(item);
}
}
This display pattern follows the DOM work in the guide to JavaScript DOM manipulation, where elements are created and added with code instead of being written by hand. The guide to JavaScript events shows how to call a function like this from a button click, so the same fetch code can run on load or on demand.
Fetch request checklist
| Step | What to check |
|---|---|
| URL | The URL points to an endpoint you are allowed to use. |
| Response status | response.ok is checked before the body is used. |
| Body reading | response.json() is awaited, and the shape is inspected. |
| Network failure | A catch block handles a rejected promise. |
| Display | Loading, data and error states all have visible text. |
Work through this checklist for each new endpoint, because a request that works for one endpoint can fail for another with a different shape or a different status. The checklist keeps the failure visible, instead of letting a silent error leave a blank page behind.
Common mistakes
One common mistake is forgetting the second await for response.json(). Without it, the code holds a promise instead of the parsed data, and trying to loop over that promise fails in a confusing way. A second mistake is treating the response object as the data itself, which produces a similar confusion when the expected fields are missing.
Another mistake is building page markup by inserting data with innerHTML. Data from an API can contain characters that break markup, and it can contain markup that was never intended for the page. Using textContent and created elements keeps data as text, which is the safer default for titles and descriptions.
A third mistake is leaving out all error handling during early testing, on the grounds that the API works. APIs fail, networks drop, and endpoints change, so error handling belongs in the first version, not in a later cleanup pass. A page with a clear error message is easier to debug than a page that simply stays blank.
Limits of fetch on its own
Fetch handles the request and the response, and it does not solve every data problem on its own. It does not cache results by default, it does not retry a failed request, and it does not manage a login session beyond what the browser and the API already provide. Those needs call for extra code around fetch, or for a library built for that purpose.
Fetch also runs under the browser security rules for cross-origin requests. An API that does not allow requests from your page origin will be blocked by the browser, even when the same URL opens fine in a browser tab. That block is a property of the API setup, not a bug in fetch code, and it is fixed by the API owner or by routing the request through your own server.
Worked example: load a list of posts and show them
Fetch turns an API request into a promise, and the usual shape is a chain: fetch the address, check the response, convert it to JSON, and then use the data. A small example that loads a list of posts and renders their titles shows the whole chain in one place. The page starts with a loading message, the script replaces it with the list when the data arrives, and a failure replaces it with an error message instead of leaving the reader staring at a loading state that never ends.
const list = document.querySelector("#posts");
const status = document.querySelector("#status");
fetch("https://jsonplaceholder.typicode.com/posts?_limit=5")
.then(function (response) {
if (!response.ok) {
throw new Error("Request failed: " + response.status);
}
return response.json();
})
.then(function (posts) {
status.textContent = "";
posts.forEach(function (post) {
const item = document.createElement("li");
item.textContent = post.title;
list.appendChild(item);
});
})
.catch(function (error) {
status.textContent = "Could not load the posts. Please try again.";
console.error(error);
});
Checking response.ok matters, because fetch only rejects its promise on a network failure, not on an HTTP error status. A server that answers with a 404 still resolves the promise, and code that skips the check will try to parse an error page as data. The check turns that silent failure into an explicit error, which the catch handler can then present to the reader.
Rendering with textContent, rather than innerHTML, keeps the data safe when it comes from an outside source. API data is user-adjacent data: it was written by someone else, and it may contain markup characters. Treating it as plain text means it can never be interpreted as code, which is the same rule the DOM guide on this site gives for any text from outside your own markup.
Async and await: the same chain, written flat
Async and await rewrite a promise chain as code that reads from top to bottom. Mark the function async, await the fetch call, await the JSON conversion, and use the result directly. Error handling moves into a try and catch block, which reads like ordinary error handling in synchronous code. The behaviour is the same as the chained version; only the shape of the code changes.
async function loadPosts() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5");
if (!response.ok) {
throw new Error("Request failed: " + response.status);
}
const posts = await response.json();
console.log(posts.length + " posts loaded.");
} catch (error) {
console.error("Could not load the posts.", error);
}
}
loadPosts();
One detail trips beginners: an async function always returns a promise, even when its body returns a plain value. A caller that needs the loaded data must await the function or use then on the returned promise, because the value is not available the moment the function is called. Code that treats an async function as if it returned the data directly gets a promise object instead, and the resulting confusion shows up as data that looks present in a log but absent on the page.
Choose the style that reads better for the task. A short chain of two steps reads well in either form. A longer sequence with several dependent requests, where each request needs data from the previous one, usually reads better with await, because the nesting of chained handlers grows quickly while the awaited version stays flat.
Sending data: POST requests with a JSON body
Fetch sends data with a POST request by passing an options object as the second argument. The method, the headers, and the body all live in that object. The body must be a string, so an object is converted with JSON.stringify before sending, and the content type header tells the server the body is JSON. Forgetting either step is a common cause of a server rejecting a request that looks correct in the client code.
async function createPost(title) {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: title }),
});
if (!response.ok) {
throw new Error("Request failed: " + response.status);
}
return response.json();
}
Read the response of a POST request with the same care as a GET response. A successful creation often returns the created item, including an id assigned by the server, and that id is needed for later updates or display. A response that is ignored wastes information the server already supplied, and a later request may have to fetch the item again to learn what the creation response already said.
While a POST request is in flight, disable the submit button or show a progress state, so the reader cannot submit the same data twice by clicking again. Re-enable it when the request settles, whether it succeeded or failed, so a failed submission can be retried. That small state handling prevents duplicate records, which are harder to clean up than to prevent.
Errors, loading states and what fetch cannot do
A robust fetch implementation handles three states: loading, success and failure. Loading tells the reader something is happening. Success shows the data. Failure explains the problem and offers a way forward, such as a retry button. A page that only handles success leaves readers in the dark whenever anything else happens, and network failures happen often enough, on mobile connections and flaky networks, that the failure state is not an edge case.
| State | What the reader should see |
|---|---|
| Loading | A clear indicator that data is on its way. |
| Success | The data, rendered as plain text where possible. |
| HTTP error | A message that the request failed, with a retry option. |
| Network failure | A message that the connection failed, with a retry option. |
Fetch also has boundaries worth knowing. It cannot read a response from a server that does not allow cross-origin requests, because the browser enforces that policy for security. It cannot keep secrets, because any key or token in client-side code is visible to the reader. And it cannot replace server-side validation, because a request built in the browser can be rebuilt by anyone. The forms guide on this site covers the server-side half of that story.
Frequently asked questions
Why does fetch not fail when a page returns an error status?
Fetch only rejects its promise for a network failure, so an error status still arrives as a response. Check response.ok in your code and handle a false value as an error, instead of assuming every response holds usable data.
Should fetch code live inside a click handler or run on page load?
It depends on the task. Run fetch on page load when the data belongs on the page from the start, and run it from a click handler when the reader asks for fresh data or for a new item. Keep the fetch call and the display code in separate functions so either trigger can use them.
What should a page show while fetch is waiting?
Show a short loading message in the same area where the data will appear, and replace it with data or with an error message when the request finishes. Leaving the area blank leaves a reader unsure whether the request started at all.
Why does fetch not reject on a 404 response?
Fetch rejects only on a network failure, such as no connection. An HTTP error status still resolves the promise, so check response.ok yourself and throw an error when it is false, so your catch handler can deal with it.
Should I use then chains or async and await?
Both work, and they express the same behaviour. Chains suit short sequences, while await suits longer sequences with dependent steps, because the code stays flat instead of nesting. Pick one style per function and stay consistent within it.


