Building Flexible Axios Clients

Published on by

Building Flexible Axios Clients image

Recently I set out to improve how I work with APIs in my Vue applications by building a flexible Axios client that I can use in my Vuex actions and one-off components.

I prefer to build specific API JS modules that I can import into my components and Vuex modules instead of a baked-in Axios call from a component. Building API resource modules allows me to abstract working with HTTP resources, and provide convenience methods for common patterns. Let’s look at a couple of examples!

Getting Started

I’m going to define a few requirements that my API clients typically have:

  • Hook into Error reporting (i.e., Sentry)
  • Ability to pass HTTP Headers like the Authorization header
  • Ability to tap into my Vuex store if needed (i.e., to get a user’s JWT)
  • Resource-specific methods that simplify making common API calls (i.e., users.find(userId))

The API client code we write applies to any HTTP client you might build, but in this case, we’ll use Axios.

The Client

The client.js file is going to be the foundation module that our other HTTP clients use to create a new Axios instance. We will also set up what Axios calls “interceptors” for requests and responses.

The request interceptor takes a request configuration and an error callback. You could customize the configuration at this point, but for starters, we’ll return the same configuration. The error callback will capture the exception through Sentry’s Raven:

client.interceptors.request.use(
requestConfig => requestConfig,
(requestError) => {
Raven.captureException(requestError);
 
return Promise.reject(requestError);
},
);

The response interceptor takes two arguments, the first argument is a response callback, and the second one is the response error:

client.interceptors.response.use(
response => response,
(error) => {
if (error.response.status >= 500) {
Raven.captureException(error);
}
 
return Promise.reject(error);
},
);

Here’s a full example of how you might build out your own base Axios client which taps into Sentry, checks a Vuex store for a user access token, and provides an ApiClient class that you can use to build your clients.

import axios from 'axios';
import Raven from 'raven-js';
import store from '../store/index';
 
/**
* Create a new Axios client instance
* @see https://github.com/mzabriskie/axios#creating-an-instance
*/
const getClient = (baseUrl = null) => {
 
const options = {
baseURL: baseUrl
};
 
if (store.getters['users/isAuthenticated']) {
options.headers = {
Authorization: `Bearer ${store.getters['users/accessToken']}`,
};
}
 
const client = axios.create(options);
 
// Add a request interceptor
client.interceptors.request.use(
requestConfig => requestConfig,
(requestError) => {
Raven.captureException(requestError);
 
return Promise.reject(requestError);
},
);
 
// Add a response interceptor
client.interceptors.response.use(
response => response,
(error) => {
if (error.response.status >= 500) {
Raven.captureException(error);
}
 
return Promise.reject(error);
},
);
 
return client;
};
 
class ApiClient {
constructor(baseUrl = null) {
this.client = getClient(baseUrl);
}
 
get(url, conf = {}) {
return this.client.get(url, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
}
 
delete(url, conf = {}) {
return this.client.delete(url, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
}
 
head(url, conf = {}) {
return this.client.head(url, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
}
 
options(url, conf = {}) {
return this.client.options(url, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
}
 
post(url, data = {}, conf = {}) {
return this.client.post(url, data, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
}
 
put(url, data = {}, conf = {}) {
return this.client.put(url, data, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
}
 
patch(url, data = {}, conf = {}) {
return this.client.patch(url, data, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
}
}
 
export { ApiClient };
 
/**
* Base HTTP Client
*/
export default {
// Provide request methods with the default base_url
get(url, conf = {}) {
return getClient().get(url, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
},
 
delete(url, conf = {}) {
return getClient().delete(url, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
},
 
head(url, conf = {}) {
return getClient().head(url, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
},
 
options(url, conf = {}) {
return getClient().options(url, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
},
 
post(url, data = {}, conf = {}) {
return getClient().post(url, data, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
},
 
put(url, data = {}, conf = {}) {
return getClient().put(url, data, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
},
 
patch(url, data = {}, conf = {}) {
return getClient().patch(url, data, conf)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
},
};

The default export exposes all the HTTP methods you can use with Axios directly. A simple example for a one-off request would look like this:

import client from './client';
 
client.get('/users').then((response) => {
// do stuff
});

Now you have a simple client for one-off requests, or you can use it as a foundation to build more interesting HTTP clients.

Using client.js to Make API Clients

Using the above client, you can now build your own API-specific Axios clients.

For example, let’s say you have a /users resource, you can build out specific methods for managing users:

import { ApiClient } from '../client';
 
let client = new ApiClient();
 
export default {
 
all() {
return client.get('/users');
},
 
find(userId) {
return client.get(`/users/${userId}`);
},
 
update(userId, data) {
return client.put(`/users/${userId}`, data);
}
 
}

The above example is simple, but you could do further processing by chaining a promise call after getting the response back. For example, you could only sending along the relevant properties needed from the response, for example. Or perhaps you don’t have access to the backend, and you could use the response to build a custom object or add additional properties, for example, a fullName property if you only get back firstName and lastName. Vue also has computed properties, but I hope you get the idea that you can format the response data before sending it along to consumer code.

Vuex Usage

One reason I suggest that you build HTTP client modules is that we can pull them into components, and we can also use them in Vuex stores as well. The same benefits apply, including sending along the Authorization tokens and avoiding axios calls directly in Vuex modules.

Here’s an example of getting a user and setting their profile data in a Vuex store:

import usersClient from './api/users';
 
// ...
 
profile({ commit }, userId) {
usersClient.find(userId)
.then((response) => {
let {
firstName,
lastName,
} = response.data;
 
commit('PROFILE', { firstName, lastName });
});
},

Improvements

One noticeable improvement in my mind is allowing more flexible client configuration through callbacks when creating a new client. The way that I’ve shown using Vuex to send along a bearer token is baked into the module in a way that isn’t very flexible.

I hope you can at least catch the ideas that I am conveying. It’s helpful to build a base client JS module for low-level details that you probably want on any HTTP client. For example, we can focus on creating useful API clients to manage users and other resources, instead of having to worry about hooking in Sentry to our request and responses.

Do you have any more Axios or JavaScript API client tips? Sound off on Twitter @laravelnews.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Forge
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with Vue and Livewire stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Real Time Command Line Monitoring With Laravel Top image

Real Time Command Line Monitoring With Laravel Top

Read article
A New Validation Rule and the Ability to Manually Fail a Command in Laravel 11.8 image

A New Validation Rule and the Ability to Manually Fail a Command in Laravel 11.8

Read article
New Proposed Array Find Functions in PHP 8.4 image

New Proposed Array Find Functions in PHP 8.4

Read article
Laracon AU 2024 tickets are now on sale image

Laracon AU 2024 tickets are now on sale

Read article
Dash UI is a Laravel Blade Component Library Inspired by Shopify Polaris image

Dash UI is a Laravel Blade Component Library Inspired by Shopify Polaris

Read article
Is class instantiation without extra parenthesis coming to PHP 8.4? image

Is class instantiation without extra parenthesis coming to PHP 8.4?

Read article