JAVASCRIPT

Consuming REST APIs with JavaScript Fetch (GET & POST)

Learn to make asynchronous GET and POST requests to RESTful APIs using JavaScript's native `fetch` API for robust web integrations and data handling.

async function fetchData(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log('GET Data:', data);
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
    throw error;
  }
}

async function postData(url, payload) {
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(payload)
    });
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const result = await response.json();
    console.log('POST Result:', result);
    return result;
  } catch (error) {
    console.error('Error posting data:', error);
    throw error;
  }
}

// Example Usage:
// fetchData('https://api.example.com/items');
// postData('https://api.example.com/items', { name: 'New Item', value: 123 });
How it works: This snippet provides two asynchronous functions, `fetchData` for GET requests and `postData` for POST requests, demonstrating how to consume a REST API using JavaScript's native `fetch` API. It includes error handling for network issues and non-OK HTTP responses, and correctly parses JSON responses. The `postData` function also sets appropriate headers for sending JSON payloads.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs