SyntaxStudy
Sign Up
javascript

How to Fetch Data from an API

Use the Fetch API to make HTTP requests and handle responses.

The fetch() API is the modern way to make network requests in JavaScript. It returns a Promise.

Basic GET Request

Call fetch(url) and chain .then() to handle the response.

Error Handling

Note: fetch() only rejects on network errors, not HTTP errors (like 404). Always check response.ok.

Using Async/Await

The async/await syntax is cleaner and easier to read.

POST Request

Pass a second argument with method, headers, and body.

Example
// GET request with async/await
async function getData(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Fetch failed:', error);
  }
}

// POST request
async function postData(url, payload) {
  const response = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  });
  return response.json();
}