Our Global Presence
Canada
57 Sherway St,
Stoney Creek, ON
L8J 0J3
India
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
USA
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
Making frontend applications is not as simple as it used to be. Frontend frameworks like React and Vue.js rely heavily on APIs. This adds complexity to our app because we need to manage how we call these APIs. One solution is to simplify the process by writing clean API calls.
But wait, what are “clean API calls”? To me, that means the proper structuring of API calls, making them easy to read and maintain. First, we do this by utilizing the single-responsibility principle. Each function must have a single responsibility, and with this principle in mind, we need to separate the logic for each endpoint.
The other thing we try to consider is the DRY principle (“Don’t Repeat Yourself”). This is very important – arguably more so in the case of frontend API providers – because it gives a sense of tidiness in the code, thus improving readability. we use Axios because it gives features such as interceptors, defaults, etc. It reduces the amount of boilerplate code you need to write for each API endpoint.
There are many ways to achieve this. You can either use the Fetch API or you can use a third-party library called Axios. By the title of this article, you can guess that we prefer Axios. Why? Let’s weigh in on the pros and cons.
What we like most about Axios is that it is very simple to use. The programming API is so easy to use that we have gotten really used to it. Well, this might be too personal of a preference, but you can try it yourself. we have used jQuery’s AJAX and the Fetch API, and we would rank Axios above all of them – although not by too large of a margin since all three of them are nice to work with.
Honesty, you wouldn’t think about this feature until you needed it. we mean, most people have modern browsers, but if some of your customers aren’t most people, they might not be able to use your app if it isn’t backward-compatible. The Fetch API is relatively new and old browsers aren’t capable of using it. Otherwise, libraries like Axios and jQuery’s AJAX are built on top of JavaScript’s XMLHttpRequest. For those of you who are wondering, XMLHttpRequest is an old version of JavaScript’s built-in HTTP calling mechanism.
You can do a lot with Axios – a whole lot. For example, as of the writing of this article, the Fetch API does not have built-in request/response interceptors. You have to use third parties. Compared to Fetch, writing clean APIs using Axios is very simple. Axios already has so many built-in conveniences. To name a few, you can set default headers and default base URLs using Axios.
we have used Axios for long enough to understand that this library can be overkill for small apps. If you only need to use its GET and POST-APIs, you probably are better off with the Fetch API anyway. Fetch is native to JavaScript, whereas Axios is not. This brings us to the next point.
This second point corresponds to the first one perfectly. One of the main reasons we avoid the use of Axios for small apps is the fact that it bloats your production build size. Sure, you might not notice a size spike for large apps like in e-commerce and such. But you will notice a huge increase if you are making a simple portfolio site. The lesson to be learned? Use the right tools for the right job.
Look, let me just start by saying that this third point is really subjective and some people might have opposite views. Axios is a third party. Yes, you read that right. Unlike Fetch, it is not native to the browser. You are depending on the community to maintain your precious app. Then again, most apps these days do use open-source products. So would it be a problem? Not really. Again, this is a preference. we are not advising you to reinvent the wheel. Just understand that you don’t own the wheel.
Axios is available in multiple JavaScript repositories. You can access it using yarn and NPM. If you are using regular HTML, you can import it from CDNs like jsDelivr, Unpkg, or Cloudflare.
Assuming you are using NPM, we need to install Axios using this command:
npm install -S axios
If there are no errors in the installation, you can continue to the next step. You can check alternative installation methods on GitHub.
What are Axios clients? Clients are how we set default parameters for each API call. We set our default values in the Axios clients, then we export the client using JavaScript’s export default. Afterward, we can just reference the client from the rest of our app.
First, make a new file preferably named apiClient.js and import Axios:
import axios from 'axios';
Then make a client using axios.create:
const axiosClient = axios.create({ baseURL: `https://api.example.com`, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } });
As you can see, we initiated the base URLs and default headers for all our HTTP calls.
When calling interacting APIs – especially when there is authentication involved – you will need to define conditions when your call is unauthorized and make your application react appropriately. Interceptors are perfect for this use case.
Let’s say that we need our application to redirect us to our home page when our cookies expire, and when our cookies expire, the API will return a 401 status code. This is how you would go about it:
axiosClient.interceptors.response.use( function (response) { return response; }, function (error) { let res = error.response; if (res.status == 401) { window.location.href = “https://example.com/login”; } console.error(“Looks like there was a problem. Status Code: “ + res.status); return Promise.reject(error); } );
Simple, right? After you’ve defined your client and attached an interceptor, you just need to export your client to be used on other pages.
After configuring your Axios client, you need to export it to make it available for the entire project. You can do this by using the export default feature:
export default { axiosClient );
Now we have made our Axios client available for the entire project. Next, we will be making API handlers for each endpoint.
Before we continue, we thought it would be useful to show you how to arrange your subfolders. Instead of writing a long comprehensive explanation, we think it would be better for me to give you an image of what we are talking about:
This assumes we will have admin, user, and product endpoints. We will home the apiClient.js file inside the root of the network folder. The naming of the folder or even the structure is just our personal preference.
The endpoints will be put inside a lib folder and separated by concerns in each file. For example, for authentication purposes, user endpoints would be put inside the user file. Product-related endpoints would be put inside the product file.
Now we will be writing the API handler. Each endpoint will have its asynchronous function with custom parameters. All endpoints will use the client we defined earlier. In the example below, we will write two API handlers to get new products and add new products:
import { axiosClient } from "../apiClient"; export function getProduct(){ return axiosClient.get('/product'); } export function addProduct(data){ return axiosClient.post('/product', JSON.stringify(data)); }
This pretty much sums up how we would write an API handler, and as you can see, each API call is clean and it all applies the single-responsibility principle. You can now reference these handlers on your main page.
Assuming that you are using an NPM project for all of this, you can easily reference your JavaScript API handlers using the import method. In this case, we will be using the getProduct endpoint:
import { getProduct } from "../network/lib/product"; getProduct() .then(function(response){ // Process response and // Do something with the UI; });
There you have it: a clean no-fuss API handler. You’ve successfully made your app much more readable and easier to maintain.
For more information and to develop your web app using front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“. To develop your custom website using JS, please visit our technology page.
Content Source:
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
© 2024 — HK Infosoft. All Rights Reserved.
© 2024 — HK Infosoft. All Rights Reserved.
T&C | Privacy Policy | Sitemap