Use axios with utility function
Easy to Use: Axios is easy to use and can be integrated with any JavaScript application or framework.
Promise Based: Axios uses promises to handle asynchronous requests, making it easier to manage the data flow.
Interceptor Support: Axios allows you to intercept requests or responses before they are handled by the application. This can be useful for adding authentication tokens, logging requests, or handling errors.
Cross-Platform: Axios can be used in both client-side and server-side applications, making it a versatile choice for developers.
Supports JSON: Axios automatically parses JSON responses, which makes it easy to work with APIs that return JSON data.
Browser Compatibility: Axios works with all modern browsers, including Chrome, Firefox, Safari, and Edge.
Lightweight: Axios is a lightweight library that doesn't require any external dependencies.
Error Handling: Axios provides robust error handling capabilities, including timeouts, network errors, and HTTP errors.
Configurable: Axios is highly configurable and allows you to customize settings such as headers, timeouts, and response types.
Overall, Axios is a reliable and versatile library that simplifies the process of making HTTP requests in JavaScript applications.
First we should create a utility function to make frequent calls using axios library.
const makeRequest = async function(method, endpoint, body, header) {
try {
let url = urls.API_URL + endpoint;
let res = null;
if(method === apiRequest.GET) {
res = await axios(
{
method:'get',
url:url,
data:body,
headers:header
}
).then((resp)=>{return resp})
return res;
}
else if(method === apiRequest.POST) {
res = await axios.post(url=url, data=body, {headers:header})
.then((resp)=>{return resp});
return res;
}
else if(method === apiRequest.PUT) {
res = axios.put(url=url, data=body, {headers:header})
.then((resp)=>{return resp});
return res;
}
else if(method === apiRequest.DELETE) {
res = axios.delete(url=url, data=body, {headers:header})
.then((resp)=>{return resp});
return res;
}
} catch (error) {
self.errorException(exceptionMessage.API_REQUEST_EXCEPTION.format(method,url), error);
}
};
Using the utility function, we can make GET request in a single line. The headers and body can be passed as json objects.
const apiEntpoint = 'https://api.example.com/api/v1/customer'
let response = await self.makeRequest(apiRequest.GET, apiEndpoint, body, headers);
console.log(response.data)
POSt request can be made using the same function.
const apiEntpoint = 'https://api.example.com/api/v1/customer'
let headers = {
Content-Type: "application/json",
apikey: "fjdsa9fu2398ujfdsfuslifys"
}
let response = await self.makeRequest(apiRequest.POST, apiEndpoint, body, headers);
console.log(response.data)