Making API Requests With Axios

in WordPress Theme

To make requests to the WordPress REST API we need to install another library to help us make these requests. We can use something like jQuery which has helpers for the different methods of GET, POST, PATCH, DELETE, but it may seem like overkill to import the entire jQuery library just to use the Ajax helpers. There are other libraries we can use which just provide helpers for HTTP requests such as vue-resource or axios.

VueJS recommends Axios so that's the library we're going to go with, to install Axios we can do so by using NPM.

npm install axios

To use Axios inside our components we need to first import in by using the following command.

import axios from 'axios'

Then we can use the GET request by simply using the .get() method with the URL we need to call. Inside the .then method is what we'll do on a successful request, inside the catch method will run if the HTTP request failed for whatever reason.

axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

For more information about how to use Axios please view the following link. Axios

To make an API call within our WordPress theme we need to setup the API for different environments then we're going to use this environment settings when making an HTTP request call to the WordPress API.

Inside the config folder of our project, there are files for the different environments, dev.env.js, prod.env.js and test.env.js. Inside these files, you need to add a new element for the API_URL.

My dev.env.js will now look like this

var merge = require('webpack-merge')
var prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API_URL: '"https://paulund.dev"'
})

And the prod.env.js will look like this

module.exports = {
  NODE_ENV: '"production"',
  API_URL: '"http://paulund.co.uk"',
  DEBUG: false
}

When we run the command

npm run dev

This will load in the dev.env.js file and use these variables for the environment. This means that inside our view components we can't hardcode the domain of the REST API we need to make it dynamic.

To make a GET request for all posts on the WordPress REST API we'll now need to use the following code.

axios.get(process.env.API_URL + '/wp-json/wp/v2/posts')
  .then(response => {
    this.posts = response.data
  })
  .catch(e => {
    console.log(e)
  })

This will now pick up the API_URL variable from the correct environment and use this base domain when making API requests.

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To Newsletter

Get weekly updates to your email