Building Flexible Axios Clients
Published on by Paul Redmond
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.
client.js
to Make API Clients
Using 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.