How To Use WordPress REST API

To create an attractive User Interface, you have to use Javascript. WordPress REST API is a powerful tool to retrieve data from the database (or modify them) in the front-end using AJAX.

Types of API calls

The most common types are:

  • GET (you get data according to URL params)
  • POST (you modify data according to the data you send – Authentication is required)
  • DELETE (you delete data according to the data you send – Authentication is required)

How to perform an API request

During testing:

  • using just the URL from the browser – see the example below
  • using the amazing tool Postman

In your plugin or theme:

  • using Curl (the old way) and of course
  • using Ajax calls from Javascript

Anatomy of the WordPress REST API call

A typical URL to call WordPress REST API looks like this:

https://domain.com/wp-json/wp/v2/posts
  • wp-json” part is fixed
  • wp” part is the API namespace
  • v2” part is the API version
  • the rest of the URL is the part where you define parameters

Find all the available “parameters” at Global Parameters and REST API Developer Endpoint Reference.

Example GET API request

Using the following URL you get a JSON response with the titles of the most recent posts on this site:

https://www.pontikis.net/wp-json/wp/v2/posts?_fields=title

If you format the JSON (using your IDE or an online tool) you get something like:

[
   {
      "title":{
         "rendered":"How To Create a Custom Database Query in WordPress"
      }
   },
   {
      "title":{
         "rendered":"How To Create a Custom Post Type in WordPress"
      }
   },
   {
      "title":{
         "rendered":"How To Add a Mobile Menu in any WordPress Theme"
      }
   },
   {
      "title":{
         "rendered":"The Need for Web Accessibility to Grow Small, Local Businesses"
      }
   },
   {
      "title":{
         "rendered":"How To Write JS and CSS in WordPress with Industry Standard Tools"
      }
   },
   {
      "title":{
         "rendered":"How To Build An App Thatu2019s Loved By The Users?"
      }
   },
   {
      "title":{
         "rendered":"Automation and Machine Learning’s Impact on Web Developers"
      }
   },
   {
      "title":{
         "rendered":"7 Rules for Improving Security in Mobile App Development Projects"
      }
   },
   {
      "title":{
         "rendered":"5 Ways to Develop Your Freelancing Business That Does Not Involve Your Web Specialty"
      }
   },
   {
      "title":{
         "rendered":"Technologies That Will Shape the Future of Dentistry"
      }
   }
]

So, it’s quite easy to display the results using Javascript.

Authentication – the WordPress nonce

GET requests do not need authentication (for public posts).

Of course, authentication is required for POST and DELETE requests. Otherwise, any website visitor would be able to modify or delete data!

According to the official documentation:

plugin and theme developers need only to have a logged-in user

However, for better security and to prevent CSRF attacks, WordPress requires additionally a “nonce” (number once) which is an arbitrary number that can be used just once in a cryptographic communication.

Pass this value from the backend in any request, using the Enqueue scripts in your function.php. Example:

function load_front_end_assets()
{
    wp_enqueue_style('load_google_font_ubuntu', '//fonts.googleapis.com/css2?family=Ubuntu:ital,wght@0,300;0,400;1,300&display=swap');
    wp_enqueue_script('load_main_js', get_theme_file_uri('/build/index.js'), ['jquery'], '1.0', true);
    wp_enqueue_style('load_main_css', get_theme_file_uri('/build/style-index.css'));
    wp_enqueue_style('load_extra_css', get_theme_file_uri('/build/index.css'));

    // optional (required in case you use API calls that need authentication)
    wp_localize_script('load_main_js', 'wpApiSettings', [
        'nonce' => wp_create_nonce('wp_rest')
    ]);
}

add_action('wp_enqueue_scripts', 'load_front_end_assets');

View the source and you will see something like:

<script type='text/javascript' id='load_main_js-js-extra'>
/* <![CDATA[ */
var wpApiSettings = {"nonce":"d3c862cd30"};
/* ]]> */
</script>

Pass the nonce to your Ajax call as X-WP-Nonce header.

Axios example

axios.defaults.headers.common["X-WP-Nonce"] = wpApiSettings.nonce

If you still use Jquery, use something like this:

$.ajax({
    url: foo,
    method: "POST",
    beforeSend: function(xhr) {
        xhr.setRequestHeader("X-WP-Nonce", wpApiSettings.nonce);
    },
    data: {
        "foo": bar
    }
}).done(function(response) {
    // your custom code
});

Create Custom Endpoints

See How to Create Custom Endpoints in WordPress REST API (with live example)

Reference