Codementor Events

Keeping Axios Where it Belongs

Published Oct 10, 2018
Keeping Axios Where it Belongs

When you are writing the front end for an application and making HTTP API calls, you may be tempted to put the API route you are calling to in the view. Dont do this. After all, by the time you are done with your app you will likely be making API calls in multiple components. When the API route changes, you will have to go back and change each reference to the API url.

Instead, think about making your own front end API using a JS config object like the following utilizing your own custom instance of Axios. This will allow us to utilize one configuration file that contains the routes for the back end API.

Here is an example.

In a JS file, lets call it 'eventService.js' we can create the following:

//here we are importing our Axios dependency
import axios from 'axios'

//here is where we are defining our custom axios instance.
//if all of your API routes come from the same location, or you are using a web proxy to hit the server, you can provide a base url
//you can also attach axios interceptors to custom axios instances as well
const apiClient = axios.create({
    baseURL: 'v1/'
})

//Now set up the routes.  We are going to export a default object with keys that keep our API routes organized.  For example, all of the auth routes live in the Auth object

export default {
    auth: {
        userLogin(payload) {
            return apiClient.post('/auth/login/', payload)
        },
        userAliveAndActive() {
            return apiClient.post('/auth/check/')
        },
        userLogout() {
            return apiClient.post('/auth/logout/')
        },
        generateResetToken(payload) {
            return apiClient.post('/auth/generate_reset_token/', payload)
        },
        resetPassword(payload) {
            return apiClient.post('/auth/reset_password/', payload)
        }
    }
}

So to access these API routes in the front end of your application you can do the following:

import eventService from '../pathToFile/eventService'

//even without knowing the back end API, I can tell that this API call is making a request to auth to log the user in. Its clear, clean, and easy to understand what is happening.
eventService.auth.userLogin({
  username: 'JohnSmith',
    password: 'abc123'
})
.then((rsp) => {
    // if you want to have one result across the app for an action, you can handle the result of this promise inside of the eventService.js file.  This will allow you to provide repeatable functioanlity across your app for events that will be used often.
    //if the event will need custom functionality, simply return the promise from the eventService.js file and handle it in the component
})
.catch((err) => {
  // handle your error here
})

So now no matter where you are in your app, you can reference your own front end API that maps to the back end API. This will allow you to make changes in one place if the back end API route changes and it will allow you to access any new API routes added by simply adding the route to the exported default object.

Full diclosure, I am writing this as a Vue developer so this may not work well with your app but for most component based JS architechtures it should be repeatable.

Discover and read more posts from Carter Capocaccia
get started
post commentsBe the first to share your opinion
Andy Thirtyacre
2 years ago

Thank you for the full example and excellent explanation. This was a tremendous help.

Victor Osas Ighalo
6 years ago

Your article is simple and very useful. I will immediately effect this is a current project I’m working on using VueJS. Thanks.

Show more replies