Laravel Cloud is here! Zero-config managed infrastructure for Laravel apps. Deploy now.

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 Idea

Ultimate PhpStorm plugin for Laravel developers, delivering lightning-fast code completion, intelligent navigation, and powerful generation tools to supercharge productivity.

Visit Laravel Idea
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
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
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
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
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
Lucky Media logo

Lucky Media

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

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
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 →
Auto-translate Application Strings with Laratext image

Auto-translate Application Strings with Laratext

Read article
Simplify Factory Associations with Laravel's UseFactory Attribute image

Simplify Factory Associations with Laravel's UseFactory Attribute

Read article
Improved Installation and Frontend Hooks in Laravel Echo 2.1 image

Improved Installation and Frontend Hooks in Laravel Echo 2.1

Read article
Filter Model Attributes with Laravel's New except() Method image

Filter Model Attributes with Laravel's New except() Method

Read article
Arr::from() Method in Laravel 12.14 image

Arr::from() Method in Laravel 12.14

Read article
Streamline API Resources with Laravel's Fluent Methods image

Streamline API Resources with Laravel's Fluent Methods

Read article