<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Theo's Medium Mirror]]></title><description><![CDATA[A mirror of my articles posted on Medium.]]></description><link>https://h.agustinustheodorus.com</link><generator>RSS for Node</generator><lastBuildDate>Wed, 22 Apr 2026 15:06:19 GMT</lastBuildDate><atom:link href="https://h.agustinustheodorus.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How To Write Clean API Calls With Axios]]></title><description><![CDATA[Making front-end 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...]]></description><link>https://h.agustinustheodorus.com/write-clean-api-calls-with-axios-ddbc7df4256c</link><guid isPermaLink="true">https://h.agustinustheodorus.com/write-clean-api-calls-with-axios-ddbc7df4256c</guid><category><![CDATA[axios]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[REST API]]></category><dc:creator><![CDATA[Agustinus Theodorus]]></dc:creator><pubDate>Mon, 22 Mar 2021 14:50:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1657037408710/CvzdGbIda.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Making front-end 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.</p>
<p>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, I 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.</p>
<p>The other thing I 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. I use <a target="_blank" href="https://www.npmjs.com/package/axios">Axios</a> because it gives features such as interceptors, defaults, etc. It reduces the amount of boilerplate code you need to write for each API endpoint.</p>
<h3 id="heading-pros-and-cons-of-using-axios">Pros and Cons of Using Axios</h3>
<p>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 I prefer Axios. Why? Let’s weigh in on the pros and cons.</p>
<h4 id="heading-pro-simplicity"><strong>Pro: Simplicity</strong></h4>
<p>What I like most about Axios is that it is very simple to use. The programming API is so easy to use that I have gotten really used to it. Well, this might be too personal of a preference, but you can try it yourself. I have used jQuery’s AJAX and the Fetch API, and I 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.</p>
<h4 id="heading-pro-backward-compatibility"><strong>Pro: Backward compatibility</strong></h4>
<p>Honesty, you wouldn’t think about this feature until you needed it. I 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.</p>
<h4 id="heading-pro-mature-library-with-lots-of-features"><strong>Pro: Mature library with lots of features</strong></h4>
<p>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.</p>
<h4 id="heading-con-too-sophisticated-for-small-apps"><strong>Con: Too sophisticated for small apps</strong></h4>
<p>I have used Axios for long enough to understand that this library can be <em>overkill</em> 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.</p>
<h4 id="heading-con-axios-bloats-your-bundle-size"><strong>Con: Axios bloats your bundle size</strong></h4>
<p>This second point corresponds to the first one perfectly. One of the main reasons I 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.</p>
<h4 id="heading-con-its-a-third-party"><strong>Con: It’s a third party</strong></h4>
<p>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. I am not advising you to reinvent the wheel. Just understand that you don’t <em>own</em> the wheel.</p>
<h3 id="heading-installing-axios">Installing Axios</h3>
<p>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.</p>
<p>Assuming you are using NPM, we need to install Axios using this command:</p>
<p>npm install -S axios</p>
<p>If there are no errors in the installation, you can continue to the next step. You can check alternative installation methods <a target="_blank" href="https://github.com/axios/axios#installing">on GitHub</a>.</p>
<h3 id="heading-making-separate-axios-clients">Making Separate Axios Clients</h3>
<p>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 <code>export default</code>. Afterward, we can just reference the client from the rest of our app.</p>
<p>First, make a new file preferably named <code>apiClient.js</code> and import Axios:</p>
<p>Import Axios.</p>
<p>Then make a client using <code>axios.create</code>:</p>
<p>Axios client JS example.</p>
<p>As you can see, we initiated the base URLs and default headers for all our HTTP calls.</p>
<h3 id="heading-using-interceptors-for-clean-redirects">Using Interceptors for Clean Redirects</h3>
<p>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.</p>
<p>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:</p>
<p>Example of using Axios interceptors.</p>
<p>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.</p>
<h3 id="heading-exporting-axios-client">Exporting Axios Client</h3>
<p>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 <code>export default</code> feature:</p>
<p>Export Axios Client.</p>
<p>Now we have made our Axios client available for the entire project. Next, we will be making API handlers for each endpoint.</p>
<h3 id="heading-folder-structure">Folder Structure</h3>
<p>Before we continue, I thought it would be useful to show you how to arrange your subfolders. Instead of writing a long comprehensive explanation, I think it would be better for me to give you an image of what I am talking about:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1657037406213/-QMEn6Gte.png" alt="Folder structure" /></p>
<p>How I would arrange my folders.</p>
<p>This assumes we will have admin, user, and product endpoints. We will home the <code>apiClient.js</code> file inside the root of the network folder. The naming of the folder or even the structure is just my personal preference.</p>
<p>The endpoints will be put inside a <code>lib</code> 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.</p>
<h3 id="heading-writing-an-api-handler">Writing an API Handler</h3>
<p>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, I will write two API handlers to get new products and add new products:</p>
<p>Example of product endpoint provider.</p>
<p>This pretty much sums up how I 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.</p>
<h3 id="heading-using-the-handlers-in-your-web-app">Using the Handlers in Your Web App</h3>
<p>Assuming that you are using an NPM project for all of this, you can easily reference your JavaScript API handlers using the <code>import</code> method. In this case, I will be using the <code>getProduct</code> endpoint:</p>
<p>Use get product endpoint.</p>
<p>There you have it: a clean no-fuss API handler. You’ve successfully made your app much more readable and easier to maintain.</p>
<h3 id="heading-final-words">Final Words</h3>
<p>Having an app that works is great. You got all the functionalities right and you are practically finished. However, people tend to forget that they need to maintain that app. So, sooner or later, you will have to read that code all over again. And wouldn’t it be better if it was all readable and easy to understand with great separation of concerns? I think we would all want that, and I would even say we would be very proud if we could read the code we wrote one year ago.</p>
<p>Being fast does not guarantee success, but being consistent and responsible does. Write better code and help your team grow! Thanks for reading.</p>
<p><em>Originally published at</em> <a target="_blank" href="https://daily.dev/blog/a-guide-to-writing-clean-api-calls-using-axios"><em>https://daily.dev</em></a> <em>on March 9, 2021.</em></p>
<p><em>Edit Note: I made a mistake and said the Fetch API is native to Javascript while actually,</em> <a target="_blank" href="https://stackoverflow.com/questions/44058726/is-the-fetch-api-an-ecmascript-feature"><em>it is not, it is native to the browser</em></a><em>, and old browsers do not support it. You can read about it more</em> <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API"><em>here</em></a><em>. Thanks for the comment</em> <a target="_blank" href="https://medium.com/u/52e936b1a62b"><em>Nick Howard</em></a><em>!</em></p>
]]></content:encoded></item></channel></rss>