Building Robust RESTful APIs with Javascript

This article is filled with examples how to implement REST API’s with the fetch api.

GET request to a REST API using JavaScript with the help of the Fetch API:

Let’s assume you want to fetch data from the “https://api.example.com/data” endpoint:

<!DOCTYPE html>
<html>
<head>
    <title>REST API GET Request Example</title>
</head>
<body>
    <h1>Data from REST API</h1>
    <div id="data-container"></div>

    <script>
        // Function to make the GET request
        function fetchDataFromAPI() {
            // Replace the URL with the actual API endpoint URL
            const apiUrl = 'https://api.example.com/data';

            // Fetch data using the Fetch API
            fetch(apiUrl)
                .then(response => {
                    // Check if the response status is OK (200)
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    // Parse the response data as JSON
                    return response.json();
                })
                .then(data => {
                    // Process the data and update the UI
                    updateUIWithData(data);
                })
                .catch(error => {
                    // Handle any errors that occurred during the fetch
                    console.error('Error fetching data:', error);
                });
        }

        // Function to update the UI with the fetched data
        function updateUIWithData(data) {
            const dataContainer = document.getElementById('data-container');
            // You can customize this part to display the data in your desired format
            dataContainer.innerHTML = JSON.stringify(data, null, 2);
        }

        // Call the function to initiate the GET request
        fetchDataFromAPI();
    </script>
</body>
</html>

This code snippet will make a GET request to the specified API endpoint and then display the fetched data in JSON format inside a div with the ID data-container. You can customize the updateUIWithData function to display the data in any format that suits your needs.

Remember to replace 'https://api.example.com/data' with the actual URL of the API you want to fetch data from. Additionally, you might need to handle API authentication (e.g., API keys, tokens) or other specific requirements based on the API you are working with.

Below is an example of making a POST request to a REST API using JavaScript with the Fetch API:

Let’s assume you want to send some data to the “https://api.example.com/create” endpoint:

<!DOCTYPE html>
<html>
<head>
    <title>REST API POST Request Example</title>
</head>
<body>
    <h1>Send Data to REST API</h1>
    <div>
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" />
    </div>
    <div>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" />
    </div>
    <button onclick="sendDataToAPI()">Send Data</button>

    <script>
        // Function to make the POST request
        function sendDataToAPI() {
            // Replace the URL with the actual API endpoint URL
            const apiUrl = 'https://api.example.com/create';

            // Data to be sent in the request body
            const data = {
                name: document.getElementById('name').value,
                email: document.getElementById('email').value,
            };

            // Fetch data using the Fetch API with POST method
            fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            })
                .then(response => {
                    // Check if the response status is OK (200)
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    // Parse the response data as JSON
                    return response.json();
                })
                .then(responseData => {
                    // Handle the response data as needed
                    console.log('Response from the API:', responseData);
                })
                .catch(error => {
                    // Handle any errors that occurred during the fetch
                    console.error('Error sending data:', error);
                });
        }
    </script>
</body>
</html>

This code snippet will make a POST request to the specified API endpoint with the data entered by the user (name and email). The data will be sent in JSON format in the request body. You can customize the sendDataToAPI function to include any additional data or modify the data being sent based on your specific use case.

Again, remember to replace 'https://api.example.com/create' with the actual URL of the API endpoint you want to send data to. Additionally, you might need to handle API authentication (e.g., API keys, tokens) or other specific requirements based on the API you are working with.

Here’s an example of making a POST request using the Fetch API in JavaScript:

<!DOCTYPE html>
<html>
<head>
    <title>REST API POST Request Example</title>
</head>
<body>
    <h1>Send Data to REST API</h1>
    <div>
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" />
    </div>
    <div>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" />
    </div>
    <button onclick="sendDataToAPI()">Send Data</button>

    <script>
        // Function to make the POST request
        function sendDataToAPI() {
            // Replace the URL with the actual API endpoint URL
            const apiUrl = 'https://api.example.com/create';

            // Data to be sent in the request body
            const data = {
                name: document.getElementById('name').value,
                email: document.getElementById('email').value,
            };

            // Fetch data using the Fetch API with POST method
            fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            })
                .then(response => {
                    // Check if the response status is OK (200)
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    // Parse the response data as JSON
                    return response.json();
                })
                .then(responseData => {
                    // Handle the response data as needed
                    console.log('Response from the API:', responseData);
                })
                .catch(error => {
                    // Handle any errors that occurred during the fetch
                    console.error('Error sending data:', error);
                });
        }
    </script>
</body>
</html>

This code snippet uses the Fetch API to make a POST request to the specified API endpoint with the data entered by the user (name and email). The data will be sent in JSON format in the request body. The server’s response will be logged to the console.

Again, remember to replace 'https://api.example.com/create' with the actual URL of the API endpoint you want to send data to. Additionally, you might need to handle API authentication (e.g., API keys, tokens) or other specific requirements based on the API you are working with.

Below is an example of making a PUT request to a REST API using the Fetch API in JavaScript:

<!DOCTYPE html>
<html>
<head>
    <title>REST API PUT Request Example</title>
</head>
<body>
    <h1>Update Data with REST API</h1>
    <div>
        <label for="userId">User ID:</label>
        <input type="text" id="userId" name="userId" />
    </div>
    <div>
        <label for="name">New Name:</label>
        <input type="text" id="name" name="name" />
    </div>
    <div>
        <label for="email">New Email:</label>
        <input type="email" id="email" name="email" />
    </div>
    <button onclick="updateDataWithAPI()">Update Data</button>

    <script>
        // Function to make the PUT request
        function updateDataWithAPI() {
            // Replace the URL with the actual API endpoint URL
            const apiUrl = 'https://api.example.com/users';

            // Data to be sent in the request body
            const data = {
                id: document.getElementById('userId').value,
                name: document.getElementById('name').value,
                email: document.getElementById('email').value,
            };

            // Fetch data using the Fetch API with PUT method
            fetch(`${apiUrl}/${data.id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            })
                .then(response => {
                    // Check if the response status is OK (200)
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    // Parse the response data as JSON
                    return response.json();
                })
                .then(responseData => {
                    // Handle the response data as needed
                    console.log('Response from the API:', responseData);
                })
                .catch(error => {
                    // Handle any errors that occurred during the fetch
                    console.error('Error updating data:', error);
                });
        }
    </script>
</body>
</html>

This code snippet uses the Fetch API to make a PUT request to the specified API endpoint with the data entered by the user (user ID, new name, and new email). The data will be sent in JSON format in the request body. The server’s response will be logged to the console.

Please note that in this example, the API endpoint for updating a user’s data is assumed to be 'https://api.example.com/users', and the user ID is taken from the input field with the ID userId. You may need to adjust the endpoint URL and the way you retrieve the user ID based on your specific API.

Additionally, ensure that the API you are working with supports the PUT method for updating resources. Some APIs might use different HTTP methods like PATCH for partial updates, so make sure to refer to the API documentation to understand the correct method to use for updating data.

Leave a Comment

Your email address will not be published. Required fields are marked *