Open In App

How to use JavaScript Fetch API to Get Data?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

An API (Application Programming Interface) is a set of rules, protocols, and tools that allows different software applications to communicate with each other.

One of the popular ways to perform API requests in JavaScript is by using Fetch API. Fetch API can make GET and POST requests, and in this article we will be covering how to get data using fetch API.

What is the JavaScript Fetch API?

The Fetch API provides an interface for fetching resources (like JSON data) across the web. It offers a more powerful and flexible alternative to traditional XMLHttpRequest.

Key features of the Fetch API:

  • Promise-based: Simplifies asynchronous operations with JavaScript promises.
  • Cleaner syntax: Uses the fetch() function for intuitive request handling.
  • Streamlined requests: Supports headers, methods, and body types for customization.
  • Modern features: Includes streaming responses and CORS support.
  • Browser compatibility: Widely supported across major browsers.

How to Use the JavaScript Fetch API

JavaScript fetch API uses the fetch() function at its core. The fetch method takes one mandatory argument- the URL of the resource that you want to get. It also accepts optional parameters like HTTP method, headers, body, and more.

Syntax:

fetch(url [, options])  
.then(response => { // Handle the response })
.catch(error => { // Handle any errors });

Learn more on how to use fetch API

Using Fetch API to Get Data

To Get data using the Fetch API in JavaScript, we use the fetch() function with the URL of the resource we want to fetch. By default, the fetch method makes the Get request.

Example: Get Data using Fetch API in JavaScript

The below examples show how to fetch data from a URL using JavaScript fetch API.

JavaScript
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log('Data received:', data);
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

Explanation:

  1. fetch() Function: Initiates an HTTP request to the specified URL (‘https://api.example.com/data’).
  2. Response Handling:
    • .then(response => {…}): Handles the response received from the server.
    • if (!response.ok) {…}: Checks if the response was successful (status code 200-299). If not, it throws an error.
    • return response.json(): Parses the response body as JSON and returns it.
  3. Data Processing:
    • .then(data => {…}): Handles the parsed JSON data received from the server.
    • console.log(‘Data received:’, data): Logs the received data to the console.
  4. Error Handling:
    • .catch(error => {…}): Catches any errors that occur during the fetch operation (e.g., network issues or failed requests).
    • console.error(‘There was a problem with the fetch operation:’, error): Logs the error message to the console.

Making a Post request

POST requests are used to send data to a server. This is commonly used when submitting forms or sending data to create a new resource. To use the JavaScript Fetch API to post data to a server, you can make a POST request with the desired data and handle the response.

Example: Post Data using Fetch API in JavaScript 

Here, let’s assume we want to create a new user by sending data to an API endpoint located at https://api.example.com/users. We specify this endpoint as the target URL for our POST request. 

Within the fetch options, we set the method property to ‘POST’ to indicate that this is a POST request. Additionally, we include the headers property to specify that we are sending JSON data in the request body. The body of the request contains the user data, which is converted to JSON format using JSON.stringify().

JavaScript
// Data to be sent in the POST request (in JSON format)
const postData = {
  username: 'exampleUser',
  email: 'user@example.com'
};

// POST request options
const requestOptions = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(postData)
};

// Make the POST request
fetch('https://api.example.com/users', requestOptions)
  .then(response => {
    // Check if the request was successful
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    // Parse the JSON response
    return response.json();
  })
  .then(data => {
    // Handle the data returned from the server
    console.log('Post request response:', data);
  })
  .catch(error => {
    // Handle any errors that occurred during the fetch
    console.error('There was a problem with the fetch operation:', error);
  });

Explanation:

  1. We define the data to be sent in the POST request, which is an object containing a username and email.
  2. We specify the options for the POST request, including the HTTP method (POST), request headers (Content-Type: application/json), and request body (the postData object converted to JSON using JSON.stringify()).
  3. We use the fetch() function to make a POST request to the specified URL (https://api.example.com/users) with the request options.
  4. We handle the response using .then() and check if it’s successful by accessing the response.ok property. If the response is okay, we parse the JSON response using response.json().
  5. Once the JSON data is retrieved, we can then handle it accordingly.
  6. Any errors that occur during the fetch operation are caught and handled using .catch().

Error Handling

When working with the Fetch API, a robust error-handling strategy is crucial, particularly for POST requests involving sensitive data. Utilize a try/catch block to encapsulate your code, with the catch() method to manage errors

Example: Error handling in Fetch API

Below is an example how how to handle errors while using fetch API.

JavaScript
try {
  const response = await fetch('https://api.example.com/data', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/json'
    }
  });
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  const result = await response.json();
  console.log('Response:', result);
} catch (error) {
  console.error('Error:', error);
}

Explanation:

The code uses a try/catch block to handle errors during a POST request using the Fetch API. It sends data to ‘https://api.example.com/data’, with JSON formatting. If the response is not successful, it throws an error. The catch block logs any errors encountered during the process.

Also Learn about Get and Post method using Fetch API

Conclusion:

In conclusion, the JavaScript Fetch API offers a modern and flexible approach to making network requests in web applications. With its promise-based design, Fetch simplifies data fetching, provides better error handling, and supports various request and response types. 

It has replaced the traditional XMLHttpRequest (XHR) and has become the preferred method for making HTTP requests in JavaScript applications. We have covered how to Get data from fetch API with examples.

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Last Updated : 14 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads