#javascript
#front end technology
#web development

Getting Data from an API Using Fetch API

Anonymous

AnonymousOct 13, 2023

Getting Data from an API Using Fetch API

You can fetch data from an API using the fetch API in JavaScript. Here's a basic example of how to do this:

fetch('https://api.example.com/data')
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

You can also use async/await with the fetch API to make the code more synchronous and easier to read. Here's how you can fetch data from an API using async/await:

async function fetchData() {
  // Define the API URL
  const apiUrl = 'https://api.example.com/data';

  try {
    // Make a GET request to the API
    const response = await fetch(apiUrl);

    // Check if the response status is OK (status code 200)
    if (!response.ok) {
      throw new Error(`Network response was not ok: ${response.status}`);
    }

    // Parse the response as JSON
    const data = await response.json();

    // Work with the data received from the API
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}
// Call the fetchData function to start the data retrieval
fetchData();

Happy Coding! ❤️