Outsource Laravel Development Partner - $3200/Month | Bacancy

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
Bacancy

Outsource a dedicated Laravel developer for $3,200/month. With over a decade of experience in Laravel development, we deliver fast, high-quality, and cost-effective solutions at affordable rates.

Visit Bacancy
Bacancy logo

Bacancy

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

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
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
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant 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

The latest

View all →
Generate Secure, Memorable Passphrases in PHP with PHP Passphrase image

Generate Secure, Memorable Passphrases in PHP with PHP Passphrase

Read article
FrankenPHP v1.11.2 Released With 30% Faster CGO, 40% Faster GC, and Security Patches image

FrankenPHP v1.11.2 Released With 30% Faster CGO, 40% Faster GC, and Security Patches

Read article
Capture Web Page Screenshots in Laravel with Spatie's Laravel Screenshot image

Capture Web Page Screenshots in Laravel with Spatie's Laravel Screenshot

Read article
Nimbus: An In-Browser API Testing Playground for Laravel image

Nimbus: An In-Browser API Testing Playground for Laravel

Read article
Laravel 12.51.0 Adds afterSending Callbacks, Validator whenFails, and MySQL Timeout image

Laravel 12.51.0 Adds afterSending Callbacks, Validator whenFails, and MySQL Timeout

Read article
Handling Large Datasets with Pagination and Cursors in Laravel MongoDB image

Handling Large Datasets with Pagination and Cursors in Laravel MongoDB

Read article