Fetch API

By Syncfusion®, Inc. · Last updated

Calling APIs with fetch(), reading status, headers and JSON, sending POST, PATCH and DELETE requests, handling HTTP and network errors, a real Hono server and client in the browser, and the most common async mistakes.

What Is the Fetch API?

API = a set of URLs a server offers to other programs, like /api/products. fetch(url) = the browser's function that sends a request and gives a promise for the response.

  • Every call has two waits: one for the response, one for its body (response.json()).
  • Every call can fail two ways: no answer at all, or an answer that says "error" (404, 500).
  • Requests have a method: GET reads, POST creates, PUT/PATCH change, DELETE removes.

Simple lesson: ask, wait for the answer, check it is OK, then read the data.

A Real-World Example

A shop page calls fetch("/api/products") and the server sends back the product list as JSON. When you press Place order, the page sends POST /api/orders with your order in the body. The server answers 201 (created) or 400 (bad input), and the page shows the right message.

Page client/main.js

Server server/index.js GET /api/products → ← 200 [ ...products ]

A request goes out; a response with a status and a body comes back.

Plain boxes have no internet, so they use data: URLs (the content is inside the URL) or a pretend server. The full-stack boxes below run a real Hono server in your browser, the same code a Cloudflare Worker runs, and fetch("/api/...") reaches it.

What You Will Learn

  1. Calling an API with fetch(), and reading status, headers and body.
  2. response.json(), and sending POST, PUT, PATCH and DELETE.
  3. Checking response.ok, network errors and cancelling with AbortController.
  4. Error handling with promises and with try...catch.
  5. The five most common async mistakes, and a real client and server.

Fetch and API calls

HTTP request = a message your code sends to a server. The response has a status code, headers and a body.

Calling APIs with fetch()

A real public API call (needs internet, so not runnable here):

const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
const user = await response.json();
console.log(user.name);

The same shape with a data: URL that runs here:

A fetch() call you can run, using a data URL

const response = await fetch('data:application/json,{"id":7,"name":"Asha","plan":"Premium"}');
const customer = await response.json();

console.log("Name:", customer.name);
console.log("Plan:", customer.plan);

Expected output:

Name: Asha
Plan: Premium

Reading response data

  • response.status: the code, like 200 (OK) or 404 (not found).
  • response.ok: true for 200–299.
  • response.headers: extra details, like the content type.

What a response tells you before you read its body

const response = await fetch('data:application/json,{"id":1042,"status":"shipped"}');

console.log("Status:", response.status);
console.log("OK?", response.ok);
console.log("Content type:", response.headers.get("Content-Type"));

Expected output:

Status: 200
OK? true
Content type: application/json

response.text() reads the body as plain text:

Reading a body as plain text

const response = await fetch("data:text/plain,Your table is ready, Ravi.");
const message = await response.text();

console.log(message);

Expected output:

Your table is ready, Ravi.

A body can be read once. Keep the result in a variable, or call response.clone() first.

Converting response to JSON

response.json() reads the body and turns JSON text into a real value. It returns a promise, so await it.

response.json() turns the body into an array you can use

const response = await fetch('data:application/json,[{"item":"Latte","price":4.5},{"item":"Bagel","price":3.25}]');
const menu = await response.json();

console.log("Items on the menu:", menu.length);
for (const entry of menu) {
  console.log(`${entry.item}: $${entry.price}`);
}

Expected output:

Items on the menu: 2
Latte: $4.5
Bagel: $3.25

Why two awaits? The status and headers arrive first; the body may still be on its way.

await fetch(url) for the response, then await response.json() for the data. Forget the second await, and you hold a promise.

Working with HTTP requests

MethodWhat it asks the server to doSends a body?
GETread some datano
POSTcreate something newyes
PUTreplace something completelyyes
PATCHchange part of somethingyes
DELETEremove somethingusually not

Choose a method with a second argument. Three options work together:

const response = await fetch("https://api.example.com/orders", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ customer: "Asha", item: "Latte", qty: 2 }),
});
const created = await response.json();
  • method: the action.
  • body: the data, as a string, so use JSON.stringify().
  • headers: "Content-Type": "application/json" tells the server it is JSON.

A small pretend server receives each Request and answers:

POST, PATCH and DELETE sent to a pretend server

const savedOrders = { 1042: { id: 1042, customer: "Asha", item: "Latte", qty: 1 } };
let nextId = 1043;

async function fakeServer(request) {
  const id = Number(request.url.split("/").pop());
  const json = (data, status) =>
    new Response(JSON.stringify(data), { status, headers: { "Content-Type": "application/json" } });

  if (request.method === "POST") {
    const order = { id: nextId++, ...(await request.json()) };
    savedOrders[order.id] = order;
    return json(order, 201);
  }
  if (request.method === "PATCH") {
    Object.assign(savedOrders[id], await request.json());
    return json(savedOrders[id], 200);
  }
  if (request.method === "DELETE") {
    delete savedOrders[id];
    return new Response(null, { status: 204 });
  }
  return json(savedOrders[id], 200);
}

// Works like fetch(), but sends the request to fakeServer instead of the internet.
const send = (url, options) => fakeServer(new Request(url, options));

const created = await send("https://api.example.com/orders", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ customer: "Ravi", item: "Mocha", qty: 2 }),
});
console.log("POST:", created.status, JSON.stringify(await created.json()));

const updated = await send("https://api.example.com/orders/1042", {
  method: "PATCH",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ qty: 3 }),
});
console.log("PATCH:", updated.status, JSON.stringify(await updated.json()));

const removed = await send("https://api.example.com/orders/1042", { method: "DELETE" });
console.log("DELETE:", removed.status, "| order 1042 still exists?", 1042 in savedOrders);

Expected output:

POST: 201 {"id":1043,"customer":"Ravi","item":"Mocha","qty":2}
PATCH: 200 {"id":1042,"customer":"Asha","item":"Latte","qty":3}
DELETE: 204 | order 1042 still exists? false

201 means "created"; 204 means "done, no body". A PUT sends the whole object and replaces everything.

Always JSON.stringify() an object body. Otherwise the server receives the text [object Object].

Handling errors in API calls

fetch() rejects only when no response arrives. A 404 or 500 is still a response:

A 404 response does not reject

// A hand-built response, the same kind fetch() gives you when a server says "not found".
const response = new Response('{"error":"Order 9999 not found"}', {
  status: 404,
  headers: { "Content-Type": "application/json" },
});

console.log("Status:", response.status);
console.log("OK?", response.ok);

Expected output:

Status: 404
OK? false

So check response.ok yourself, and throw on a bad status:

Checking response.ok and throwing on a bad status

async function readJson(response) {
  if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}`);
  }
  return response.json();
}

const good = new Response('{"id":1042,"item":"Latte"}', { status: 200 });
const missing = new Response('{"error":"not found"}', { status: 404 });

console.log("200:", await readJson(good));
try {
  await readJson(missing);
} catch (error) {
  console.log("404:", error.message);
}

Expected output:

200: {
  "id": 1042,
  "item": "Latte"
}
404: Request failed with status 404

Async error handling

A call can fail at the network, at the status, or at the JSON. Handle all of them in one place.

Promise error handling

One catch() at the end of a chain catches a failure from any step, including your own throw.

One catch() handles a failure from any step

function loadOrder(response) {
  return Promise.resolve(response)
    .then((res) => {
      if (!res.ok) throw new Error(`Status ${res.status}`);
      return res.json();
    })
    .then((order) => `Order ${order.id}: ${order.item}`)
    .catch((error) => `Could not load the order (${error.message})`);
}

console.log(await loadOrder(new Response('{"id":1042,"item":"Latte"}', { status: 200 })));
console.log(await loadOrder(new Response("Server error", { status: 500 })));

Expected output:

Order 1042: Latte
Could not load the order (Status 500)

Async/await error handling

Put every await that can fail inside try. Use finally to hide "Loading..." either way.

try...catch...finally around an API call

async function showProfile(url) {
  console.log("Loading...");
  try {
    const response = await fetch(url);
    if (!response.ok) throw new Error(`Status ${response.status}`);
    const user = await response.json();
    console.log("Hello,", user.name);
  } catch (error) {
    console.log("Something went wrong:", error.name);
  } finally {
    console.log("Hide the loading message");
  }
}

await showProfile('data:application/json,{"name":"Meera"}');
await showProfile('data:application/json,{"name":"Meera"');

Expected output:

Loading...
Hello, Meera
Hide the loading message
Loading...
Something went wrong: SyntaxError
Hide the loading message

Log error.name and error.message. The name tells the kind at a glance: TypeError for a network problem, SyntaxError for bad JSON.

Network error scenarios

Network error = no response at all: server off, wrong address, no connection. This is when fetch() rejects, with a TypeError:

A network failure is the case where fetch() rejects

try {
  await fetch("http://127.0.0.1:1/api/orders");
  console.log("A response arrived");
} catch (error) {
  console.log("fetch() rejected with a", error.name);
}

Expected output:

fetch() rejected with a TypeError
ScenarioDoes fetch() reject?How you notice it
No network, server down, wrong addressyes, with a TypeErrorcatch receives the error
Server answers 404 or 500noresponse.ok is false
The body is not valid JSONno, but response.json() rejectscatch receives a SyntaxError
You cancelled the requestyes, with an AbortErrorerror.name === "AbortError"

An AbortController cancels a request: pass its signal to fetch() and call abort().

A cancelled request rejects with an AbortError

const controller = new AbortController();
controller.abort();

try {
  await fetch('data:application/json,{"id":1}', { signal: controller.signal });
} catch (error) {
  console.log("Rejected with:", error.name);
}

Expected output:

Rejected with: AbortError

A Real API: Server and Client

These boxes have two files. server/index.js is a real Hono app; client/main.js is the page's code. Open both in the explorer.

GET /api/products and /api/products/:id with a real 404

// @file: server/index.js
import { Hono } from "hono";

const products = [
  { id: 1, name: "Notebook", price: 60 },
  { id: 2, name: "Lunch box", price: 349 },
  { id: 3, name: "Steel bottle", price: 299 },
];

const app = new Hono();

app.get("/api/products", (c) => c.json(products));

app.get("/api/products/:id", (c) => {
  const id = Number(c.req.param("id"));
  const product = products.find((p) => p.id === id);
  if (!product) return c.json({ error: `No product with id ${id}` }, 404);
  return c.json(product);
});

export default app;

// @file: client/main.js
const status = document.getElementById("status");
const list = document.getElementById("products");

async function getJson(url) {
  const response = await fetch(url);
  const data = await response.json();
  if (!response.ok) throw new Error(`${response.status}: ${data.error}`);
  return data;
}

status.textContent = "Loading…";
try {
  const products = await getJson("/api/products");
  for (const p of products) {
    const li = document.createElement("li");
    li.textContent = `${p.name} — ₹${p.price}`;
    list.append(li);
  }
  status.textContent = `${products.length} products`;

  const one = await getJson("/api/products/2");
  console.log("one product:", one.name);
  await getJson("/api/products/99");
} catch (error) {
  console.log("Caught:", error.message);
}

The Console shows each request as [network] GET ... -> 200, then the 404 turned into an error by getJson().

The next box sends a body. The server checks it and answers 201 or 400. Change the quantity in the Preview to 0 and press Place order.

POST /api/orders: the server checks the body

// @file: server/index.js
import { Hono } from "hono";

const orders = [];
const app = new Hono();

app.post("/api/orders", async (c) => {
  const body = await c.req.json();
  if (typeof body.productId !== "number" || !(body.qty >= 1)) {
    return c.json({ error: "Send a productId and a qty of 1 or more" }, 400);
  }
  const order = { id: `A${101 + orders.length}`, ...body, status: "pending" };
  orders.push(order);
  console.log(`Saved order ${order.id}. Orders so far: ${orders.length}`);
  return c.json(order, 201);
});

app.patch("/api/orders/:id", async (c) => {
  const order = orders.find((o) => o.id === c.req.param("id"));
  if (!order) return c.json({ error: "No such order" }, 404);
  Object.assign(order, await c.req.json());
  return c.json(order);
});

export default app;

// @file: client/main.js
const form = document.getElementById("order");
const qty = document.getElementById("qty");
const result = document.getElementById("result");

async function send(method, url, data) {
  const response = await fetch(url, {
    method,
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data),
  });
  const reply = await response.json();
  if (!response.ok) throw new Error(reply.error);
  return { status: response.status, reply };
}

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  result.textContent = "Sending…";
  try {
    const created = await send("POST", "/api/orders", { productId: 2, qty: Number(qty.value) });
    const changed = await send("PATCH", `/api/orders/${created.reply.id}`, { status: "shipped" });
    result.textContent = `Order ${created.reply.id}: ${created.status} created, now ${changed.reply.status}.`;
  } catch (error) {
    result.textContent = `Not saved: ${error.message}`;
  }
});

Download gives a Cloudflare Workers project (wrangler.jsonc, server/, client/, public/). Run npm install, then npm run dev.

Common async mistakes

Forgetting await

Without await, the variable holds a promise, and its "fields" are undefined. No error appears.

Symptom: the data is undefined, and no error appears

async function getOrder() {
  const response = await fetch('data:application/json,{"id":1042,"total":9.75}');
  return response.json();
}

const order = getOrder();
console.log("Is it a promise?", order instanceof Promise);
console.log("Total:", order.total);

Expected output:

Is it a promise? true
Total: undefined

Fix: await the call

async function getOrder() {
  const response = await fetch('data:application/json,{"id":1042,"total":9.75}');
  return response.json();
}

const order = await getOrder();
console.log("Total:", order.total);

Expected output:

Total: 9.75

Missing catch()

A rejection with nothing to handle it stops the program.

Symptom: a rejection with no catch() stops the program

function loadMenu() {
  return Promise.reject(new Error("Menu server is down"));
}

await loadMenu().then((menu) => console.log("Menu:", menu));
console.log("Show the rest of the page");

End every chain with catch():

Fix: end the chain with catch()

function loadMenu() {
  return Promise.reject(new Error("Menu server is down"));
}

await loadMenu()
  .then((menu) => console.log("Menu:", menu))
  .catch((error) => console.log("Could not load the menu:", error.message));
console.log("Show the rest of the page");

Expected output:

Could not load the menu: Menu server is down
Show the rest of the page

Callback hell

Each step nested inside the last:

Symptom: every step pushes the code further to the right

function getUser(id, done) {
  setTimeout(() => done(null, { id, name: "Asha" }), 5);
}
function getCart(user, done) {
  setTimeout(() => done(null, ["Latte", "Bagel"]), 5);
}
function getTotal(cart, done) {
  setTimeout(() => done(null, 7.75), 5);
}

getUser(7, (error, user) => {
  if (error) return console.log(error.message);
  getCart(user, (error, cart) => {
    if (error) return console.log(error.message);
    getTotal(cart, (error, total) => {
      if (error) return console.log(error.message);
      console.log(`${user.name} owes $${total} for ${cart.join(" and ")}`);
    });
  });
});

await new Promise((resolve) => setTimeout(resolve, 50));

Promise-returning steps and await keep it flat, with one try...catch:

Fix: promise-returning steps and await

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

const getUser = (id) => wait(5, { id, name: "Asha" });
const getCart = (user) => wait(5, ["Latte", "Bagel"]);
const getTotal = (cart) => wait(5, 7.75);

try {
  const user = await getUser(7);
  const cart = await getCart(user);
  const total = await getTotal(cart);
  console.log(`${user.name} owes $${total} for ${cart.join(" and ")}`);
} catch (error) {
  console.log(error.message);
}

Expected output:

Asha owes $7.75 for Latte and Bagel

Unhandled promise rejections

An async call with no await and no catch() hides its error. The try thinks all went well:

Symptom: try...catch reports no error, but the error exists

async function sendReceipt(email) {
  throw new Error(`Could not email ${email}`);
}

let receipt;
try {
  receipt = sendReceipt("asha@example.com");
  console.log("The try block finished without an error");
} catch (error) {
  console.log("Caught:", error.message);
}

// This page reads the hidden error so that you can see it.
console.log("Hidden inside the promise:", await receipt.catch((error) => error.message));

Expected output:

The try block finished without an error
Hidden inside the promise: Could not email asha@example.com

In a real program the browser warns:

Uncaught (in promise) Error: Could not email asha@example.com

Node.js stops the whole program. Await it inside try:

Fix: await the call inside the try block

async function sendReceipt(email) {
  throw new Error(`Could not email ${email}`);
}

try {
  await sendReceipt("asha@example.com");
  console.log("Receipt sent");
} catch (error) {
  console.log("Caught:", error.message);
}

Expected output:

Caught: Could not email asha@example.com

Incorrect execution order

Without await, the next line runs before the slow work finishes. Here the customer is told "saved" too early:

Symptom: the success message appears before the save

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const log = [];

async function saveOrder() {
  await wait(10);
  log.push("order written to the database");
}

saveOrder();
log.push("Show 'Order saved!' to the customer");

await wait(30);
console.log(log);

Expected output:

[
  "Show 'Order saved!' to the customer",
  "order written to the database"
]

Fix: await the work before the next step

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const log = [];

async function saveOrder() {
  await wait(10);
  log.push("order written to the database");
}

await saveOrder();
log.push("Show 'Order saved!' to the customer");

console.log(log);

Expected output:

[
  "order written to the database",
  "Show 'Order saved!' to the customer"
]

Easy way to remember: fetch → check ok → json → use. Wrap it in try, and await every step.

TL;DR

  • await fetch(url), check response.ok, then await response.json().
  • Send data with method, headers and body: JSON.stringify(data).
  • fetch() rejects only on network errors; 404/500 are normal responses.
  • Bodies are read once; 204 has no body; AbortController cancels.
  • Await every promise, end chains with catch(), and handle errors in one place.

Try this

In Checking response.ok, change the missing response's status from 404 to 201. Every status from 200 to 299 is ok, so readJson() returns the body instead of throwing.

Check Yourself

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
No await on response.json()One await is enoughTwo waitsYou get a promise
Reading JSON from a 404 pagefetch throws on errorsCheck response.ok firstSyntaxError on HTML
body: dataObjects are sent as JSONJSON.stringify(data)Server gets [object Object]
Reading the body twiceBodies can be re-readOnce only, or clone()The second read fails
response.json() on 204Every response has a body204 has noneA parse error
Logging an AbortError as a failureEvery rejection is a problemYou cancelled on purposeFalse alarms

Quick reference

SyntaxMeaning
const response = await fetch(url);send a GET request and wait for the response
response.oktrue for statuses 200 to 299
response.statusthe HTTP status code, such as 200 or 404
response.headers.get("Content-Type")read one header from the response
await response.json()read the body and convert JSON text into a value
await response.text()read the body as a plain string
fetch(url, { method: "POST", headers, body })send data with another HTTP method
body: JSON.stringify(data)turn an object into JSON text before sending it
if (!response.ok) throw new Error(...)turn an HTTP error status into a real error
promise.then(...).catch(error => ...)handle any failure in a chain
try { await fetch(url); } catch (error) { ... }handle any failure around await
new AbortController() with { signal }cancel a request that is still running

Exercises

What to Remember

  • Two waits, two kinds of failure.
  • Always check response.ok.
  • A real API is a server route plus a client fetch().

Next: Object-Oriented JavaScript. Objects, constructor functions and classes for organising bigger programs.