The WordPress REST API : Getting Started Guide

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.

 

WPOven – The Dedicated WordPress Hosting provides you with –

 

  1. FREE SSD Storage
  2. FREE SSL CERTIFICATE
  3. FREE Business Email
  4. FREE Over 100 premium themes and plugins
  5. FREE Daily Off-Site Backups
  6. FREE Malware Screening & Cleanup 
  7. FREE WordPress Dev & Server Support
  8. Dedicated Server

 

Our plans start at $66.63.  With dedicated VPS, dedicated resources, server stack, etc

 

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 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 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 the front end interface, and thus making it fast. Later it’s 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-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 the REST API in WordPress:

Applications for integrating REST API in WordPress

 

Zapier:

 

Zapier_logo

 

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:

 

google map logo

 

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-wp

 

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, 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 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 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 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 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 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 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 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, 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 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 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 an unauthenticated request.

 

Example if REST API authentication

 

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

 

 

This is then used in the base model:

   

 

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

   

 

The other way of REST API authentication is using a plugin, but it is only recommended to be used while 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 meta parameter adds a JavaScript callback function before the data.

Example:

 

  • _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 send 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:

  • _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 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 a 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 identifies and discover 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:

Javascript:

 

XML

 

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

 

Step 1 – Find RSD endpoint using Link Element :

 

Step 2 – Fetch RSD endpoint:

Identify API Capability:

 

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

Conclusion:

Representational State Transfer API holds immense potential for the 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 *