#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

Learn How to Fetch Data from External APIs

In modern JavaScript you fetch data from an external API with the built-in fetch() function, await the response, check that it succeeded, and parse the JSON. The rest of the work is handling errors, slow networks and secret keys properly.

Every example below runs in a browser console or in Node.js 18+, using the free JSONPlaceholder test API, with the output shown.

Learn How to Fetch Data from External APIs

Almost every real web app shows data that lives somewhere else: weather from a forecast service, prices from a payment provider, repositories from GitHub. Getting that data means sending an HTTP request to the provider's API and turning the response into something your page can show. If the idea of an API itself is new, read what APIs are and how they work in web apps first; this tutorial is the hands-on part.

All examples use https://jsonplaceholder.typicode.com, a free fake REST API for practice. It always returns the same sample data, so you can check your output against the output shown here.

1. A basic GET request

async function getUser(id) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
  const user = await response.json();
  console.log(user.name, '-', user.email);
}

getUser(1);

Output:

Leanne Graham - Sincere@april.biz

Two awaits are needed. The first waits for the response headers to arrive; the second waits for the body to download and be parsed as JSON. fetch returns a Promise, and async/await is simply a more readable way to work with it than chaining .then().

2. Handle errors properly

A detail that surprises many beginners: fetch does not throw for HTTP errors like 404 or 500. It only rejects when the request could not be made at all, for example when there is no network. You have to check response.ok (true for status 200–299) yourself:

async function getJSON(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`HTTP ${response.status} for ${url}`);
  }
  return response.json();
}

async function main() {
  try {
    const user = await getJSON('https://jsonplaceholder.typicode.com/users/9999');
    console.log(user.name);
  } catch (err) {
    console.log('Could not load user:', err.message);
  }
}

main();

Output:

Could not load user: HTTP 404 for https://jsonplaceholder.typicode.com/users/9999

Without the response.ok check, this code would print undefined, because the API returns an empty object {} with the 404. The small getJSON helper is worth reusing in every project.

3. Send query parameters

Build query strings with URLSearchParams instead of joining strings by hand. It encodes spaces and special characters for you:

async function postsByUser(userId) {
  const params = new URLSearchParams({ userId });
  const posts = await getJSON(`https://jsonplaceholder.typicode.com/posts?${params}`);
  console.log(`User ${userId} has ${posts.length} posts`);
  console.log('First title:', posts[0].title);
}

postsByUser(1);

Output:

User 1 has 10 posts
First title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit

(JSONPlaceholder's sample text is placeholder Latin.)

4. Send data with POST

async function createPost() {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ title: 'Hello API', body: 'My first post', userId: 1 }),
  });
  console.log('Status:', response.status);
  console.log(await response.json());
}

createPost();

Output:

Status: 201
{ title: 'Hello API', body: 'My first post', userId: 1, id: 101 }

Status 201 means "created". JSONPlaceholder pretends to save the post and returns it with a new id; nothing is really stored. The same pattern works for PUT, PATCH and DELETE by changing method. Forgetting the Content-Type header is a common reason real APIs reject a POST body.

5. Add a timeout

By default a fetch can wait a long time on a bad connection. AbortSignal.timeout(), supported in current browsers and Node.js, cancels the request after a set time:

async function getWithTimeout(url, ms = 5000) {
  try {
    const response = await fetch(url, { signal: AbortSignal.timeout(ms) });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  } catch (err) {
    if (err.name === 'TimeoutError') throw new Error(`Timed out after ${ms} ms`);
    throw err;
  }
}

For users on slow mobile data, a clear "taking too long, try again" message is far better than a spinner that never stops.

6. Make several requests at once

If requests do not depend on each other, run them in parallel. Promise.all waits for all of them and fails if any one fails; Promise.allSettled gives you every result, success or failure:

async function loadDashboard() {
  const base = 'https://jsonplaceholder.typicode.com';
  const [user, todos] = await Promise.all([
    getJSON(`${base}/users/1`),
    getJSON(`${base}/todos?userId=1`),
  ]);
  const done = todos.filter(t => t.completed).length;
  console.log(`${user.name}: ${done} of ${todos.length} todos completed`);
}

loadDashboard();

Output:

Leanne Graham: 11 of 20 todos completed

Running the two requests one after another would take roughly the sum of both times; in parallel it takes roughly the time of the slower one.

7. Show the data on the page safely

<ul id="posts"></ul>
<p id="status">Loading…</p>

<script>
async function render() {
  const list = document.getElementById('posts');
  const status = document.getElementById('status');
  try {
    const posts = await getJSON('https://jsonplaceholder.typicode.com/posts?userId=2');
    for (const p of posts) {
      const li = document.createElement('li');
      li.textContent = p.title;          // textContent, not innerHTML
      list.appendChild(li);
    }
    status.textContent = `${posts.length} posts loaded`;
  } catch (err) {
    status.textContent = 'Could not load posts. Please try again.';
  }
}
render();
</script>

Using textContent means that if an API ever returns text containing <script>, it is shown as text rather than run. Inserting API data with innerHTML is a common cause of cross-site scripting (XSS) bugs. (The getJSON helper from section 2 must be defined on the page too.)

8. CORS and API keys

CORS. Browsers only let a page read a response from another domain if that server allows it with an Access-Control-Allow-Origin header. JSONPlaceholder allows everyone; many APIs do not. If you see a CORS error in the console, the fix is on the server side or in a backend of your own, not in your fetch options. Setting mode: 'no-cors' does not solve it; it just gives you a response you cannot read.

API keys. Anything in front-end JavaScript can be read by anyone who opens developer tools. If an API needs a secret key (most paid APIs, payment gateways and AI APIs do), call it from your own server and let the browser call your server:

// server.js (Node.js 18+ with Express)
const express = require('express');
const app = express();

app.get('/api/weather', async (req, res) => {
  const params = new URLSearchParams({ q: req.query.city, appid: process.env.WEATHER_KEY });
  const r = await fetch(`https://api.openweathermap.org/data/2.5/weather?${params}`);
  res.status(r.status).json(await r.json());
});

app.listen(3000);

The key stays in an environment variable on the server, and the front end calls /api/weather?city=Pune with no key at all. The weather app tutorial builds a full project on this API.

9. Fetching in React

In React, fetch inside useEffect and cancel the request if the component unmounts or the input changes, so an old response cannot overwrite a newer one:

import { useEffect, useState } from 'react';

function UserCard({ id }) {
  const [user, setUser] = useState(null);
  const [error, setError] = useState('');

  useEffect(() => {
    const controller = new AbortController();
    fetch(`https://jsonplaceholder.typicode.com/users/${id}`, { signal: controller.signal })
      .then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); })
      .then(setUser)
      .catch(err => { if (err.name !== 'AbortError') setError(err.message); });
    return () => controller.abort();
  }, [id]);

  if (error) return <p>Error: {error}</p>;
  if (!user) return <p>Loading…</p>;
  return <p>{user.name} ({user.email})</p>;
}

In larger apps, libraries such as TanStack Query or SWR handle caching, retries and loading states for you, but they use the same fetch underneath.

A checklist for real APIs

  • Read the API's documentation for authentication, rate limits and pagination before writing code.
  • Check response.ok on every call and show a helpful message on failure.
  • On status 429 (too many requests) or 5xx errors, retry a couple of times with an increasing delay, not in a tight loop.
  • Keep secret keys on a server, never in front-end code or a public repository.
  • Test requests in a tool like Postman first, so you know what a correct response looks like; this Postman guide shows how.

To practise, pick an API from this list of free APIs for coding projects and build a small page with loading, error and empty states.

Placed Students

Our Clients

Partners

...