{"id":312657,"date":"2020-06-18T08:02:25","date_gmt":"2020-06-18T15:02:25","guid":{"rendered":"https:\/\/css-tricks.com\/?p=312657"},"modified":"2020-06-22T07:47:15","modified_gmt":"2020-06-22T14:47:15","slug":"stay-dry-using-axios-for-api-requests","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/stay-dry-using-axios-for-api-requests\/","title":{"rendered":"Stay DRY Using axios for API Requests"},"content":{"rendered":"\n

HTTP requests are a crucial part of any web application that\u2019s communicating with a back-end server. The front end needs some data, so it asks for it via a network HTTP request (or Ajax, as it tends to be called), and the server returns an answer. Almost every website these days does this in some fashion.<\/p>\n\n\n\n

With a larger site, we can expect to see more of this. More data, more APIs, and more special circumstances. As sites grow like this, it is important to stay organized. One classic concept is DRY (short for Don\u2019t Repeat Yourself), which is the process of abstracting code to prevent repeating it over and over. This is ideal because it often allows us to write something once, use it in multiple places, and update in a single place rather than each instance.<\/p>\n\n\n\n

We might also reach for libraries to help us. For Ajax, axios<\/a> is a popular choice. You might already be familiar with it, and even use it for things like independent POST and GET requests while developing. <\/p>\n\n\n

Installation and the basics<\/h3>\n\n\n

It can be installed using npm (or yarn):<\/p>\n\n\n\n

npm install axios<\/code><\/pre>\n\n\n\n

An independent POST request using Axios looks like this:<\/p>\n\n\n\n

axios.post('https:\/\/axios-app.firebaseio.com\/users.json', formData)\n\u00a0 .then(res => console.log(res))\n\u00a0 .catch(error => console.log(error))<\/code><\/pre>\n\n\n\n

Native JavaScript has multiple ways of doing JavaScript too. Notably, fetch()<\/code><\/a>. So why use a library at all? Well, for one, error handling in fetch is pretty wonky. You\u2019ll have a better time with axios right out of the gate with that. If you\u2019d like to see a comparison, we have an article that covers both<\/a> and an article that talks about the value of abstraction<\/a> with stuff like this.<\/p>\n\n\n\n

Another reason to reach for axios? It gives us more opportunities for DRYness, so let\u2019s look into that. <\/p>\n\n\n

Global config<\/h3>\n\n\n

We can set up a global configuration (e.g. in our main.js<\/code> file) that handles all application requests using a standard configuration<\/strong> that is set through a default object that ships with axios. <\/p>\n\n\n\n

This object contains:<\/p>\n\n\n\n