Open In App
Related Articles

How to Use the JavaScript Fetch API to Get Data ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
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 request in JavaScript is by using Fetch API.

How the Fetch API Works

The Fetch API in JavaScript offers a modern approach to making HTTP requests. To initiate a request, developers utilize the fetch() function, providing the URL of the desired resource. This function returns a Promise, representing the asynchronous operation of fetching data from the server. Upon resolution, the Promise yields a Response object encapsulating the response received from the server.

Syntax:

fetch(url [, options])
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle any errors
  });
  1. url: The URL of the resource you want to fetch. This can be a relative or absolute URL.
  2. options (optional): An object containing optional parameters for the fetch operation, such as request method, headers, body, etc. It allows you to customize the request according to your requirements. Here are some common options:
    • method: The HTTP method for the request (e.g., ‘GET’, ‘POST’, ‘PUT’, ‘DELETE’).
    • headers: An object containing HTTP headers for the request.
    • body: The request body, used for methods like ‘POST’ or ‘PUT’ to send data to the server.
    • mode: The mode for the request (e.g., ‘cors’, ‘no-cors’, ‘same-origin’).
    • credentials: Indicates whether to include credentials in cross-origin requests (e.g., ‘same-origin’, ‘include’, ‘omit’).

How to Use the JavaScript Fetch API to Get Data?

JavaScript Get request is used to retrieve Data from a server. To use the Fetch API in JavaScript to get data from a server, you can make a GET request to the desired URL and handle the response.

Fetch API JavaScript Get Example:

Here, let’s assume we want to fetch user data from an API endpoint located at https://api.example.com/users/123. We use the Fetch API to make a GET request to this endpoint. Upon receiving the response, we first check if it’s successful by accessing the response.ok property. If the response is okay, indicating a status code in the range 200-299, we proceed to parse the response body as JSON using the response.json() method. Once the JSON data is retrieved, we can then process the user data accordingly.

Javascript

  .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(data);
  })
  .catch(error => {
    // Handle any errors that occurred during the fetch
    console.error('There was a problem with the fetch operation:', error);
  });

                    

Fetch API JavaScript Get Example Explanation:

  1. We use the fetch() function to make a GET request to the specified URL (https://api.example.com/data).
  2. The fetch() function returns a Promise that resolves to a Response object representing the HTTP response from the server.
  3. We chain a .then() method to the promise to handle the response. Inside the callback function, we check if the response was successful using the ok property of the Response object. If the response was successful, we parse the JSON response using the .json() method, which returns a promise that resolves to the parsed JSON data.
  4. We chain another .then() method to handle the parsed data returned from the server.
  5. If any errors occur during the fetch operation, they are caught and handled using the .catch() method, which also returns a promise.

How to Use the JavaScript Fetch API to Post Data?

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.

Fetch API JavaScript Post Example:

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);
  });

                    

Fetch API JavaScript Post Example 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 requestOptions.
  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().

How to use the JavaScript fetch api to get json data

To use the Fetch API to get JSON data, you can make a GET request to the desired URL and parse the JSON response.

JavaScript Fetch API to get JSON Data Example

Here, we use the Fetch API to retrieve JSON data from a specified URL (https://api.example.com/data). We make a GET request with fetch(), handling the response asynchronously using .then() and .catch() methods. If the response is successful (status code 200-299), we parse the JSON response using .json(). The parsed JSON data is then processed in another .then() callback. Any errors during the fetch operation are caught and handled in the .catch() block.

Javascript

// Make a GET request to the URL
  .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 JSON data
    console.log('JSON data:', data);
  })
  .catch(error => {
    // Handle any errors
    console.error('There was a problem with the fetch operation:', error);
  });

                    

JavaScript Fetch API to get JSON Data Example Explanation:

  1. We use the fetch() function to make a GET request to the specified URL (https://api.example.com/data).
  2. The fetch() function returns a Promise that resolves to a Response object representing the HTTP response from the server.
  3. We chain a .then() method to the promise to handle the response. Inside the callback function, we check if the response was successful using the ok property of the Response object. If the response is okay, we parse the JSON response using the .json() method, which returns a promise that resolves to the parsed JSON data.
  4. We chain another .then() method to handle the parsed JSON data returned from the server.
  5. If any errors occur during the fetch operation, they are caught and handled using the .catch() method.


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 : 20 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads