CodeChefs
Guide

How to Use the Fetch API in JavaScript to Retrieve Data

Learn how to fetch API in JavaScript with Fetch API syntax, methods, error handling, async/await, headers, and practical examples.

By Editorial TeamJune 21, 20266 min read
How to Use the Fetch API in JavaScript to Retrieve Data

Introduction to the Fetch API

If you want to fetch data from outside your app, Fetch API is the modern tool to use. It lets you make HTTP requests from JavaScript and handle the results as Promises. In most cases, it replaces XMLHttpRequest with a cleaner API.

When people ask “how to fetch api in javascript,” they usually mean “how do I call an API endpoint and read the data.” Fetch answers that directly. You call fetch(url, options), then transform the response into data like JSON.

The core mental model is simple. A request starts immediately, and you wait for the response asynchronously. This is why Fetch fits naturally with async code and modern JavaScript patterns.

  • Fetch returns a Promise for a Response object.
  • You typically check the response, then parse JSON with response.json().
  • Errors can happen in two places: network failures and HTTP error status codes.
Code-centric desk scene representing Fetch API request flow
Fetch API request flow

Basic syntax and common usage

The basic form is fetch(url, options). The url is the endpoint you call. The optional options controls method, headers, and (for some methods) the request body.

Here is a minimal pattern for fetching JSON data. This shows the “make request, then parse JSON” flow that powers most “fetch data in javascript” examples.

Example:

const res = await fetch("https://example.com/api/items");
const data = await res.json();

In real code, you should add a status check before parsing. Parsing error pages as JSON is a common bug. Even when the server returns a 404, response.json() will try anyway.

Part What it does
url The API endpoint you call
options.method The HTTP verb like GET or POST
options.headers Metadata like content type and auth
options.body The payload for POST, PUT, or PATCH
Keyboard and tablet scene representing fetch(url, options) usage
Syntax and options

Handling HTTP request methods (GET, POST, PUT, DELETE)

Most API work uses a small set of HTTP request methods. For reading data, GET is the usual choice. For sending new data, POST is common. For updating existing resources, PUT is typical. For removing resources, DELETE is used.

With Fetch, you set the method in options. That is how you control “what kind of action” the request represents. The same endpoint base URL can support multiple methods depending on the server.

GET example:

const res = await fetch("https://example.com/api/items");
const items = await res.json();

POST example (send JSON):

const payload = { name: "New item" };
const res = await fetch("https://example.com/api/items", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(payload)
});

PUT and DELETE follow the same structure. Use PUT when replacing or updating fields. Use DELETE when the server removes the resource. For DELETE, you often omit body unless the API spec requires it.

  • GET: retrieve data from an API endpoint
  • POST: create a new resource
  • PUT: update an existing resource
  • DELETE: remove a resource
Light trails converging into a hub symbolizing HTTP methods
GET, POST, PUT, DELETE

Error handling in Fetch

Error handling is crucial when you do how to fetch data from api work. Fetch has a subtle behavior: it only rejects the Promise on network errors. If the server responds with a 404 or 500, the Promise usually resolves.

That means you must check the status yourself. The simplest approach is to use response.ok. It is true for 200–299 responses. If it is false, you should stop and handle the failure.

Practical pattern:

try {
  const res = await fetch(url);
  if (!res.ok) {
    throw new Error(`HTTP ${res.status}`);
  }
  const data = await res.json();
  return data;
} catch (err) {
  // handle network error or parsing issues
}

For better messages, you can read the error body too. Many APIs include JSON like { message: "Not found" }. If that is available, you can log it for debugging.

Be careful with JSON parsing on error responses. Some services return HTML errors. In that case, res.json() will throw. You can handle this by parsing only when you expect JSON.

Failure type What you see What to do
Network outage Fetch Promise rejects Catch it in try/catch
HTTP error like 404 Promise resolves, res.ok is false Check response.ok first
Bad JSON res.json() throws Catch parsing errors and inspect Content-Type
Notebook and glow lights representing error handling for Fetch responses
Response checks and try/catch

Using async/await with Fetch

Fetch returns Promises, so you can use .then() chains. However, async/await is usually easier to read. It turns asynchronous code into a top-down flow that feels like synchronous logic.

When you learn how to fetch data from api in javascript, async/await is the fastest way to get clean code. You wrap your calls in an async function and use await for both the request and the response parsing.

Example function:

async function loadItems() {
  const res = await fetch("https://example.com/api/items");
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return await res.json();
}

Then you call it like this. This keeps UI logic separate from request logic.

loadItems()
  .then(items => { /* render items */ })
  .catch(err => { /* show error state */ });

For more control, you can also use AbortController to cancel a request. That is helpful when users navigate away. It prevents wasted work and reduces confusing “late” updates.

  1. Make the request with await fetch(...)
  2. Check res.ok before parsing
  3. Parse data with await res.json()

Sending custom headers

Custom headers are how clients send metadata to the server. In Fetch, you pass headers inside the options object. A common use is authentication, like sending a bearer token.

Another common use is the Content-Type header. When you send JSON, you typically set it to application/json. Without it, some APIs cannot parse your body correctly.

Example with headers:

const token = "your-token";
const payload = { name: "New item" };
const res = await fetch("https://example.com/api/items", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${token}`
  },
  body: JSON.stringify(payload)
});

For file uploads or form data, headers can differ. If you use FormData, you usually should not manually set Content-Type. The browser can generate the right boundary for you.

  • Use Content-Type when sending JSON
  • Use Authorization for tokens when required
  • Let the browser set boundaries for form uploads

Common use cases and examples

Fetch shows up in dashboards, autocomplete widgets, and admin panels. In all those cases, you repeatedly “fetch data in javascript,” render it, and handle errors. The details depend on your API endpoints and response formats.

Use case 1: Load a list with GET
Call your items endpoint and render the returned array. This is the default pattern for read-only screens.

Use case 2: Create data with POST
Collect form input, validate it, then send a JSON payload. Use response.ok and parse the returned created object.

Use case 3: Update with PUT
Send the new representation of a resource. Some APIs accept partial updates, but that is usually handled by PATCH.

Use case 4: Delete with DELETE
Request deletion for a specific resource id. Many APIs return a success message or the deleted object. Treat both as possible JSON.

Below is a small “fetch data from api in javascript” example that includes headers and error checks. You can adapt it for most API endpoints.

async function updateUser(userId, token, updates) {
  const res = await fetch(`https://example.com/api/users/${userId}`, {
    method: "PUT",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${token}`
    },
    body: JSON.stringify(updates)
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return await res.json();
}

People sometimes also search for how to fetch data from api in python. The concepts carry over: you call an endpoint, check errors, and parse JSON. In Python, you would use a library like requests, but the flow stays the same.

FAQ

How do I fetch data from an API using the Fetch API in JavaScript?
Call fetch with the endpoint URL, then parse the response with res.json(). Check res.ok first so you handle HTTP errors safely.
Does Fetch throw an error when the API returns a 404 or 500?
Usually it does not. Fetch resolves the Promise for HTTP error statuses, so you must check response.ok or response.status.
What is the difference between response.json() and response.ok?
response.ok checks the HTTP status range. response.json() parses the body as JSON, and it can fail if the body is not JSON.
How do I send JSON with POST using Fetch?
Set method to POST, add a Content-Type: application/json header, then send body: JSON.stringify(yourData).
When should I use async/await with Fetch?
Use async/await for readable code, especially when you must check status and parse JSON. It keeps the flow easy to debug.
How do custom headers work with Fetch?
Pass headers in the options object. Common examples include Authorization for tokens and Content-Type for JSON payloads.
#how to fetch api in javascript#how to fetch data from api javascript#fetch data in javascript#error handling in fetch#custom headers in fetch#using async await with fetch
ShareXFacebookLinkedInWhatsAppTelegram