The WordPress REST API : Getting started Guide

WordPress API

What is an API

Web Applications are no more a standalone entity. They need to communicate with third party entities for better outcome and instant real time data. In order to communicate with third party components they need a medium and protocol to do that.

Such defined protocols are known as API, or Application Programming Interface. Through this interface two independent entities communicate with each other and deliver the desired outcome.

Let us understand this with an example from travel domain. There are hundreds of independent airline websites allowing their customers to book tickets in real time. But there are websites like Skyscanner where results from all the different websites are collected, compared and displayed to the user. In this case Skyscanner collects data from these hundreds or thousands of websites using a defined component, which is knowns as its Application Programming Interface or API.

Similarly, there are weather apps on a smartphone that gets the data from local servers from various cities across the world. Whole of this process is handled by one or the other API.

It acts as a strong tool for application developers to interact with another software program.

What is REST API

Representational State Transfer API is also popularly known as REST API. It is one of the architectural style used in web programming. One of the other architectural style is Simple Object Access Protocol, but REST is more popular because it consumes less bandwidth and hence responds faster in case of web application. It is compatible with ASP, PHP, Java, Ruby, Android, etc.

All the popular browsers use REST and that makes it suitable for Cloud based web applications. REST API breaks down the whole process into various transactional modules making it easy for developers.

As discussed with the weather app example in previous section when an applications send a data request to various servers, the servers will respond accordingly to send the requested data in prescribed format (XML or JSON). But processing and sending XML or JSON files is time consuming and not as real time as it should be.

To overcome this server creates an object and convert that object into a representational state, and the state is being transferred to the client (application) in the form of data.

There are 4 stages of resource processing that any web application goes through (also known as CRUD operations). Create, Read, Update and Delete, or there HTTP equivalents like POST, GET, PUT AND DELETE.

The two popular methods of implementing RESTful APIs are Jersey and Sparing.

Most popular usage of REST APIs are in Mobile / cloud applications, social networking websites, and automated business process applications. The APIs are cache friendly so they are more mobile friendly owing to speed and efficiency.

 

REST API in WordPress

WordPress has evolved from a simple blogging platform to a complete Web Application Development platform. And like any other application development tool it also needs several Application Programming Interface (API) to deliver desired results.

WordPress Representational State Transfer (REST) API was started as a separate plugin. It was first developed in June 2013 by Ryan McCue and Rachel Baker, and was included in core WP update in 2015. It gains huge popularity and hundreds of developers came forward to improve it further, and that is when it completely became part of the core WordPress since version 4.7 (in 2016). This development  supported the aim of WordPress to become a complete framework package for web developers.

Inclusion of REST API within the core framework enabled WordPress to communicate, integrate and exchange data with other external applications and servers, while keeping the data processing operations separate from front end interface, and thus making it fast. Later it’s Java Script/JSON (JavaScript Object Notation) compatible version was also developed and it is known as JSON REST API, which makes it even easier to communicate with applications built in other languages.

The core advantage of WordPress REST API is that developer’s don’t have to code the applications from scratch in PHP, they can get their WordPress programm to interact with any other program that can make HTTP requests and interpret JSON. The other advantage is making the programs more fast and responsive for end user as WordPress REST API simplifies AJAX calls hence fetching the data faster than before.

 

Here are some popular applications that can be integrated using REST API in WordPress:

  1. Zapier: Zapier in itself is a platform that interacts with hundreds of applications using Rest API that includes, Google Docs, MailChimp, Evernote, Buffer, Slack, Trello, Twitter, Facebook, Salesforce and almost any other popularly used web application. Using this you can power up your simple WordPress website to interact and exchange data with any of the listed apps, developer just need to define the triggers and actions. For example, if you want data from a form to be directly added to one of your Google Spreadsheets, you can do it by simply adding API key from Zapier into your WordPress and defining the process in Zapier and all your data from a simple contact form will be stored in the selected spreadsheet. How cool is that?
  2. Google Maps: Using an API key from Google you can get to show the map on your website frontend. Previously it was done by embedding an iframe code into your pages.
  3. Simmer: It is a recipe and cookbook platform. Using this developers can source the recipes from it and display it within their desired UI on their own website and mobile websites.
  4. Social Media Feed: Using a REST API you can now show your social media feed from networks like facebook, YouTube, Instagram, Twitter on your website.

 

WordPress Theme and Plugin uses REST API for Maintenance, Support and Update

If you are into WordPress development you surely might have come across inserting API Key option in theme options and plugin settings. Once an API key is inserted and saved the WordPress installation will now be able to communicate with the original developer server. Once API key is authenticated by the developer server it will send the update theme or plugin files to the WordPress installation.

 

Data Sharing through Plugins using REST API

If it is a plugin, the API will sync the data between your WordPress website and the third party application.

For example, if you use a Mailchimp Plugin and insert an authenticated API key you can directly send the optin emails to Mailchimp and it will store it in the selected Mailchimp list in your account.

 

How REST API works in WordPress

Like other REST APIs, in WordPress too it works in four core HTML operations of GET, POST, PUT and DELETE along with an additional command to instruct the API what data is required and what to do with that data. You can understand this by going through the sections below.

 

Components of WordPress REST API:

The Representational State Transfer (REST) API in WordPress comprises of 5 key components:

  • Requests
  • Routes/Endpoints
  • Responses
  • Schema
  • Controller Classes

 

Understanding Requests:

Requests are the communication in form of GET operations between a client and the server implemented using the class WP_REST_Request submitted via HTTP. The requests are done to the registered routes.

 

Understanding Routes and Endpoints:

Each client server request follows a certain route and reach to various endpoints within the route to get the desired output. In this case Routes are effectively the URLs. When a request is made

 

When a request is made, API shows the available routes and each of the endpoints available within that route. It will then compare the GET request with the available endpoints and return the response accordingly.

 

Responses:

As it is self explanatory response is desired data that API returns against the request made. The response class is defined by WP_REST_Response.

 

Schema:

As web developers already understand that fetching a data is done within a defined structure. This structure is known as schema. A well defined schema has an index of input parameters it accepts and an index of all the data attributes it can return. Schema also acts as a security cover for API as it only validates the requests adhering to its structure.

 

Controller Classes:

Controller coordinates between all the above elements and manage the complete process to get the desired output and optimize the complete the process.

 

How to create your first REST API functionality:

You have already learnt about the 5 components of WordPress REST API, so the next step is how to implement these APIs in your project. To start with you must learn about the most popular Endpoints in a WP REST API.

 

They are as follows:

RESOURCES BASE ROUTE
Posts /wp/v2/posts
Post Revisions /wp/v2/revisions
Categories /wp/v2/categories
Tags /wp/v2/tags
Pages /wp/v2/pages
Comments /wp/v2/comments
Taxonomies /wp/v2/taxonomies
Media /wp/v2/media
Users /wp/v2/users
Post Types /wp/v2/types
Post Statuses /wp/v2/statuses
Settings /wp/v2/settings

You are familiar with the endpoints, now you need to understand how to create an HTTP call, which always starts with your domain URL, example: myxyzdomain.com and is followed by one of the base routes mentioned in above table.

 

REST API Authentication

There are two type of functions in API which can be done without authentication, while others need authentication.

In WordPress REST API authentication can be done through any of the three methods depending on the purpose.

The 3 methods are:

Method of Authentication Purpose
Cookie Authentication Plugins/themes running on same application
OAuth Integrate with 3rd party apps, example – mailchimp, instagram, twitter, etc.
Basic Authentication (through a plugin) For development and testing only

 

Cookie authentication basically works well with default login functionality of WordPress. The REST API works on this technique called “number used once” or “noonce” which simply is a WordPress security token with a limited lifetime and is specific to the user. It is used to protect your application to be exploited by external sources and interfere with your program. This type of interference is commonly known as Cross-site request forgery (CSRF) or one-click attack or session riding.

 

For REST API Authentication inbuilt and automatic javascript API can be used, or alternatively manual AJAX authentication can also be used. If using Ajax, a noonce authentication request will have to be sent along with every request. In absence of noonce the API will consider it as unauthenticated request.

 

Example if REST API authentication

As an example, this is how the built-in Javascript client creates the nonce:

 

<?php
wp_localize_script( 'wp-api', 'wpApiSettings', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' )
) );

 

This is then used in the base model:

   

options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
if (beforeSend) {
    return beforeSend.apply(this, arguments);
}
};

 

Here is an example of editing the title of a post, using jQuery AJAX:

   

$.ajax( {
url: wpApiSettings.root + 'wp/v2/posts/1',
method: 'POST',
beforeSend: function ( xhr ) {
    xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
    'title' : 'Hello Moon'
}
} ).done( function ( response ) {
console.log( response );
} );

The other way of REST API authentication is using a plugin, but it is only recommended to be used while development and not on live application.

 

REST API Global Parameters

WordPress Representational State Transfer API has some pre defined parameters, also known as meta parameters. They are as follows:

  • _jsonp:
    This meta parameter adds a JavaScript callback function before the data.

Example:

<script>
function receiveData( data ) {
 // Do something with the data here.
 // For demonstration purposes, we'll simply log it.
 console.log( data );
}
</script>
<script src="https://demo.wp-api.org/wp-json/?_jsonp=receiveData"></script>

 

  • _method (or X-HTTP-Method-Override header)
    A method override parameter is used to make the API function compatible with all type of servers and clients, even the ones that don’t process the HTTP methods correctly.
  • _envelope
    An envelope parameter collate all the response data within a body and then send to the requesting client. An added advantage of using this parameter is that it provides access to data to servers and clients that do not support accessing the full response data..
    Example:

    HTTP/1.1 200 OK
    {
     "status": 302,
     "headers": {
    "Location": "http://example.com/wp-json/wp/v2/users/42"
     },
     "body": {
    "id": 42
     }
    }
  • _embed
    In WordPress or any other development environment any resource never works in isolation, it  is always linked to other related resources. For example, an ecommerce product is linked to one or more categories, a featured image, product reviews, etc. Using an embed meta parameter the API directs server to send all the parameters embedded in its response. It will minimize the number of HTTP requests made by the client. An embed parameter is passed within GET parameter.

 

How REST API Initiate Communication between Client and Server

To start the communication between two entities (server and client) it is important for the client to know whether a compatible API exists on server that allows the communication. To initiate the communication and discover the client (in this case WordPress web application) sends a request from HEADER using a route link.

This is a two step process. In 1st step the web application identify and discover the API. In second step the client or web application should identify what all functions and data can be processed through it.

Discovery of API

Example:

HTML:

<link rel='https://api.w.org/' href='http://example.com/wp-json/' />

 

Javascript:

// jQuery method
var $link = jQuery( 'link[rel="https://api.w.org/"]' );
var api_root = $link.attr( 'href' );
// Native method
var links = document.getElementsByTagName( 'link' );
var link = Array.prototype.filter.call( links, function ( item ) {
return ( item.rel === 'https://api.w.org/' );
} );
var api_root = link[0].href;

 

XML

XML uses Really Simple Discovery method. It comprises of a 2 step process:

Step 1 – Find RSD endpoint using Link Element :

<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://example.com/xmlrpc.php?rsd" />

 

Step 2 – Fetch RSD endpoint:

<?xml version="1.0" encoding="utf-8"?>
<rsd version="1.0" xmlns="http://archipelago.phrasewise.com/rsd">
 <service>
<engineName>WordPress</engineName>
<engineLink>https://wordpress.org/</engineLink>
<homePageLink>http://example.com/</homePageLink>
<apis>
  <api name="WordPress" blogID="1" preferred="true" apiLink="http://example.com/xmlrpc.php" />
  <!-- ... -->
  <api name="WP-API" blogID="1" preferred="false" apiLink="http://example.com/wp-json/" />
</apis>
 </service>
</rsd>

 

Identify the API Capability:

In this step web application checks the configuration and see what all functions can be performed using the provided API, example sync data, update theme files, identify plugin support subscriptions, etc.

 

{
"name": "Example WordPress Site",
"namespaces": [
    "wp/v2",
    "oembed/1.0/"
]
}

 

Conclusion:

Representational State Transfer API holds immense potential for future, and it has forced the WordPress Stakeholders to start using it. REST API is already being included in the WordPress Core, and now Theme and Plugin developers have started to use API for theme and plugin maintenance, data integration and other application requests.

The REST API has transformed WordPress form a simple CMS to a fully equipped web application development platform. It is still in its nascent stage but the dedicated development community is surely going to harness its full potential. It is a vast concept and you need to practice it to understand it completely, and what you can do with it solely depends on your imagination.

 

Leave a Reply

Your email address will not be published. Required fields are marked *