API calls with axios.create() (Almost like having an SDK for any API!)

June 11, 2021 Coding, JavaScript

Just a quick blog on something I discovered in the docs for axios.

If you find yourself making many external API calls in your code via axios, you may find that you are repeating yourself with each API call, e.g. adding an Authorisation header each time you make a request, or for example:

export async function sendStuffToMyAPI(id: number, data: SendData): Promise<void> {
    const response: any = await axios.post(`${config.myAPIBaseUrl}/entity/${id}`, data, {
        headers: {
            Authorization: config.myToken,
        },
    });
}

export async function getStuffFromMyAPI(id: number): Promise<AxiosResponse> {
    const response: any = await axios.get(`${config.myAPIBaseUrl}/entity/${id}`, {
        headers: {
            Authorization: config.myToken,
        },
    });

    return response.data;
}

As seen above, we have to specify the headers and the Authorisation headers each time we make an API call. We can simplify this using axios.create(). To set up axios.create(), you give it some config, e.g. baseURL and headers and it returns an object that you can call the normal axios functions on, e.g. get, put, etc.

As seen in the example below, it is kind of like having an SDK object that you can make calls to! First set up the axios object:

const myAPI = axios.create({
    baseURL: config.myAPIBaseUrl,
    headers: { Authorization: config.myToken },
});

Then you could simply make calls on the new myAPI object:

export async function sendStuffToMyAPI(id: number, data: SendData): Promise<void> {
    const response: AxiosResponse = await myAPI.post(`/entity/${id}`, data);
}

export async function getStuffFromMyAPI(id: number): Promise<AxiosResponse> {
    const response: AxiosResponse = await myAPI.get(`/entity/${id}`);

    return response.data;
}

As you can see you can make api calls in your code a lot leaner with axios.create()! Note: I haven’t tested the above code so if there are syntax errors or other stuff please let me know!

See here for more details: https://github.com/axios/axios#creating-an-instance

Leave a Reply

Your email address will not be published.