There are multiple ways to call API from JS. But the primary are three ways.
Fetch method is available in all the new generation framework such as react js , Vue, Fast js and more.
// Function to make a GET request using fetch
function getData(url) {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
});
}
// Example usage
var apiUrl = "https://api.example.com/data";
getData(apiUrl)
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Error:", error);
});
Axios method is available in all the new generation framework such as react js , Vue, Fast js and more.
function getData(url) {
return axios.get(url)
.then(response => response.data)
.catch(error => {
throw new Error(`Axios error: ${error.message}`);
});
}
// Example usage
var apiUrl = "https://api.example.com/data";
getData(apiUrl)
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Error:", error);
});
Using Axios is considered more advanced as it simplifies the code significantly and provides built-in features for handling errors and processing responses. The choice of method depends on the developer’s preference and project requirements. The provided examples cover the GET request; for other HTTP methods, you would adjust the method and payload accordingly.
The advanced developer, having gained experience in web development, starts by understanding the fundamentals of RESTful APIs. They grasp concepts like HTTP methods (GET, POST, PUT, DELETE), status codes, request and response structures, and the significance of headers.
Rather than blindly copying code snippets, the advanced developer carefully selects the appropriate tool for making API calls. They might opt for the fetch API for its simplicity, or if the project requires broader compatibility, they might consider using a library like Axios.
To enhance code maintainability and reusability, the advanced developer builds a wrapper function around the API calls. This function abstracts away the complexity, making it easier to manage endpoints, headers, and error handling consistently throughout the application.
Understanding that not all API calls will be successful, the advanced developer implements robust error handling. They consider HTTP status codes, network errors, and unexpected responses, providing meaningful feedback to users and logging detailed information for debugging.
The advanced developer embraces the asynchronous nature of JavaScript by using Promises or async/await syntax. This allows them to handle multiple API calls concurrently without blocking the main thread, improving the application’s responsiveness.
Get to know whats happening with the API instantly in your inbox. No spam for sure.