agyanadda@gmail.com

Node.js Fetch and Calling APIs

Advanced Node.js 1 min read Updated Dec 3, 2026 Topic 25 of 30

Node.js includes fetch (the same API as browsers) for HTTP requests — no package needed in modern versions.

GET

const res = await fetch(url); const data = await res.json();

POST with JSON

Pass method, headers and body: JSON.stringify(data).

Check the status!

fetch only rejects on network failures. A 404 or 500 response still resolves — check res.ok (true for 200–299) or res.status and throw your own error.

Timeouts

fetch(url, { signal: AbortSignal.timeout(5000) }) cancels after 5 seconds, so a slow API cannot hang your server.

Other tips

  • Keep API keys in environment variables; send them in headers
  • Use Promise.all for parallel requests
  • Retry a few times on temporary errors (429, 503) with a delay
  • Cache results that don't change often

Popular alternatives: axios (automatic JSON, interceptors) and undici.

Example

Example — Reusable API helper JavaScript
async function api(url, { method = 'GET', body, timeout = 5000 } = {}) {
  const res = await fetch(url, {
    method,
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${process.env.API_TOKEN ?? ''}`,
    },
    body: body ? JSON.stringify(body) : undefined,
    signal: AbortSignal.timeout(timeout),
  });

  if (!res.ok) {
    throw new Error(`API ${method} ${url} failed with ${res.status}`);
  }
  return res.status === 204 ? null : res.json();
}

try {
  const todo = await api('https://jsonplaceholder.typicode.com/todos/1');
  console.log(todo.title);

  const created = await api('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    body: { title: 'Hello', body: 'From Node', userId: 1 },
  });
  console.log('Created post id:', created.id);   // 101
} catch (err) {
  console.error(err.name === 'TimeoutError' ? 'API too slow' : err.message);
}

Prints the title of todo 1 and "Created post id: 101" from the free test API. A 404, a 500 or a request taking more than 5 seconds is caught and reported.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Does fetch reject the promise on a 404 response?

Exercise 2 True / False

AbortSignal.timeout(5000) cancels a request after 5 seconds.

Exercise 3 Fill in the Blank

Read a JSON response with await res.___()

Frequently Asked Questions

fetch is built in and enough for most needs. axios adds conveniences such as automatic JSON, interceptors and errors on bad status codes. Both are fine; many new projects use fetch to avoid an extra dependency.