Blog>
Snippets

Integration with RESTful APIs using Fetch

Demonstrate how to use the Fetch API to connect to a RESTful service and handle responses, showing the need for backend integration proficiency.
// Fetch data from a GET endpoint
fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
        }
        return response.json();
    })
    .then(data => {
        console.log('Data retrieved:', data);
    })
    .catch(error => {
        console.error('There has been a problem with your fetch operation:', error);
    });
This code uses the Fetch API to make a GET request to a specified RESTful endpoint. It handles the response by first checking if the request was successful. If not, it throws an error. If the request was successful, it parses the response as JSON. Finally, it logs the data or catches any errors that may have occurred during the fetch operation.
// Post data to a REST endpoint
const postData = { key: 'value' };

fetch('https://api.example.com/submit', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(postData),
})
.then(response => {
    if (!response.ok) {
        throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.json();
})
.then(data => {
    console.log('Post successful:', data);
})
.catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
});
This code snippet demonstrates how to send a POST request to a RESTful API using Fetch. It includes setting the request method to POST, specifying the headers, and sending the data as a JSON string inside the request body. It handles the response similarly to a GET request by checking the status code, parsing the JSON response, logging the result, or catching errors.