You mush have heard the term API if you work in a technical domain. It can be a little confusing, In this guide, we have tried to clear all your doubts so that you can easily talk about API with your team and colleagues.
What is API?
Web Applications are no more a standalone entity. They need to communicate with third-party entities for better outcomes 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 the 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. The 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 styles used in web programming. One of the other architectural styles is the Simple Object Access Protocol, but REST is more popular because it consumes less bandwidth and hence responds faster in case of the 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 the previous section when applications send a data request to various servers, the servers will respond accordingly to send the requested data in the 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 converts 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.
The most popular usage of REST APIs is 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. Like any other application development tool, it also needs an 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 the core WP update in 2015. It gained 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.
The 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 the front-end interface, thus making it fast. Later its JavaScript/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 developers don’t have to code the applications from scratch in PHP, they can get their WordPress program 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-users as WordPress REST API simplifies AJAX calls hence fetching the data faster than before.
Here are some popular applications that can be integrated using the REST API in WordPress:
Applications for integrating REST API in WordPress
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, the developer just needs 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?
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.
Simmer:
Simmer 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.
Social Media Feed:
Using a REST API you can now show your social media feed from networks like Facebook, YouTube, Instagram, and Twitter on your website.
WordPress Theme and Plugin use REST API for Maintenance, Support, and Update
If you are into WordPress development you surely might have come across inserting the 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 opt-in 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 on 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 communication in the form of getting 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 reaches 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 a 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 data is done within a defined structure. This structure is known as a schema. A well-defined schema has an index of input parameters it accepts and an index of all the data attributes it can return. The schema also acts as a security cover for API as it only validates the requests adhering to its structure.
Controller Classes:
The controller coordinates between all the above elements and manages the complete process to get the desired output and optimize the complete process.
How to create your first REST API functionality:
You have already learned 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, for example myxyzdomain.com, and is followed by one of the base routes mentioned in the above table.
REST API Authentication
There are two types of functions in API that 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 the same application |
OAuth | Integrate with 3rd party apps, for example – Mailchimp, Instagram, Twitter, etc. |
Basic Authentication (through a plugin) | For development and testing only |
Cookie authentication basically works well with the 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 from being exploited by external sources and interfering 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 the absence of noonce the API will consider it as an unauthenticated request.
For example if REST API authentication
As an example, this is how the built-in Javascript client creates the nonce:
1 2 3 4 5 |
<?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:
1 2 3 4 5 6 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
$.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 during development and not on a 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 metaparameter adds a JavaScript callback function before the data.
Example:
1 2 3 4 5 6 7 8 |
<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 types of servers and clients, even the ones that don’t process the HTTP methods correctly. - _envelope
An envelope parameter collates all the response data within a body and then sends it 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:
1 2 3 4 5 6 7 8 9 10 |
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 the 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 the GET parameter.
How REST API Initiates 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 a server that allows the communication. To initiate the communication and discover the client (in this case WordPress web application) send a request from HEADER using a route link.
This is a two-step process. In 1st step, the web application identifies and discovers the API. In the second step, the client or web application should identify what all functions and data can be processed through it.
Discovery of API
Example:
HTML:
1 |
<link rel='https://api.w.org/' href='http://example.com/wp-json/' /> |
Javascript:
1 2 3 4 5 6 7 8 9 |
// 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 :
1 |
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://example.com/xmlrpc.php?rsd" /> |
Step 2 – Fetch RSD endpoint:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?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 API Capability:
In this step, the web application checks the configuration and sees what functions can be performed using the provided API, for example, sync data, update theme files, identify plugin support subscriptions, etc.
1 2 3 4 5 6 7 |
{ "name": "Example WordPress Site", "namespaces": [ "wp/v2", "oembed/1.0/" ] } |
Conclusion:
Representational State Transfer API holds immense potential for the future, and it has forced 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 from 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.
I am a Co-Founder at WPOven INC currently living in Vancouver, Canada. My interests range from Web Development to Product development and Client projects. I am also interested in web development, WordPress, and entrepreneurship.