Fetching Data From an API

Modern web pages don't just display static content — they fetch fresh data from servers and update in real time. This dynamic behavior powers everything from social media feeds to weather widgets.

The Fetch API

JavaScript's built-in fetch() function makes network requests to APIs. You provide a URL, and fetch returns the data. It's how your frontend talks to backends, whether your own or public services like GitHub or weather APIs.

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data));

The fetch() function is asynchronous — it doesn't block your page while waiting for a response. This keeps your interface responsive even during slow network requests.

Handling Async Operations

Network requests take time. You have two main approaches to handle this: Promises with .then() chains, or the more readable async/await syntax.

async function getData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}

Both approaches work. AI-generated code often uses async/await because it reads more like synchronous code, making it easier to follow.

Loading States

Users need feedback while data loads. A loading spinner or "Loading..." message tells them something is happening. Without this, a blank section looks broken.

The pattern is straightforward: show loading indicator, make the request, hide indicator and show data (or error). This three-state approach — loading, success, error — appears in almost every data-fetching scenario.

Error Handling

Network requests fail. The server might be down, the user might be offline, or the API might return an error. Always wrap fetch calls in try/catch blocks and display meaningful error messages.

try {
  const response = await fetch(url);
  if (!response.ok) throw new Error('Request failed');
  const data = await response.json();
  displayData(data);
} catch (error) {
  showErrorMessage('Could not load data. Please try again.');
}

Prompting AI for Data Fetching

When asking AI to add data fetching, specify the API endpoint, what data you want to display, and how to handle loading and errors. For example: "Fetch my recent GitHub activity and display the 5 most recent events with repo name and date. Show a spinner while loading and an error message if it fails."

See More

Further Reading

Last updated December 13, 2025

You need to be signed in to leave a comment and join the discussion