Learning WordPress REST API

4.3 (3 reviews total)
By Sufyan bin Uzayr
  • Instant online access to over 8,000+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Getting Started with REST API

About this book

The WordPress REST API is a recent innovation that has the potential to unlock several new opportunities for WordPress developers. It can help you integrate with technologies outside of WordPress, as well as offer great flexibility when developing themes and plugins for WordPress. As such, the REST API can make developers’ lives easier.

The book begins by covering the basics of the REST API and how it can be used along with WordPress. Learn how the REST API interacts with WordPress, allowing you to copy posts and modify post metadata. Move on to get an understanding of taxonomies and user roles are in WordPress and how to use them with the WordPress REST API. Next, find out how to edit and process forms with AJAX and how to create custom routes and functions. You will create a fully-functional single page web app using a WordPress site and the REST API. Lastly, you will see how to deal with the REST API in future versions and will use it to interact it with third-party services.

By the end of the book, you will be able to work with the WordPress REST API to build web applications.

Publication date:
July 2016
Publisher
Packt
Pages
216
ISBN
9781786469243

 

Chapter 1.  Getting Started with REST API

Ever since the middle of 2015, the WordPress community has been busy talking about the advent of REST API to the WordPress core. This is definitely a groundbreaking development and will eventually lead to bigger and better things that we as developers can accomplish using WordPress.

The WordPress REST API has been included in WordPress in a two-phase cycle, split across two versions: WordPress 4.4 and WordPress 4.5; it is not completely there in the WordPress core, but it is being added partially in a phase-wise manner.

Quite obviously, WordPress REST API (also called JSON REST API by some users) will play a crucial role toward the future of WordPress development, and since WordPress is the world's most popular content management system (CMS), it will contribute toward the growth of web development in general.

That said, what is all the fuss about REST API? In fact, what is REST API and why should you, as a developer, be concerned about it? Before we actually get started with coding and development, in this chapter I will introduce you to REST API, its powers, and features and what it can do for WordPress development.

 

Introducing REST API


Before going any further, we first need to be aware of what REST API is, why it is called so, and so on. However, let us first try to understand the concept in a nontechnical manner and then delve into the technical details.

Defining API

Since we are capitalizing the term REST API, it is obvious that it is just an acronym. The three letters API stand for application programming interface.

In simple words, an application programming interface lets you establish a connection or link between two different types of software. For instance, your computer has a USB port, which is essentially meant for connecting USB storage devices such as flash drives or USB hard disks. However, you can connect virtually any type of USB hardware to the port-printers, smartphones, tablets, and so on. As such, think of the USB port as an API for letting you connect different types of devices to your computer and allowing your computer to interact with the concerned devices accordingly. Much like a USB port facilitates the exchange of data between two physical devices, an API facilitates the exchange of data between two different types of software.

APIs have been around for quite sometime and developers and programmers use them on a daily basis. Have you ever used a third-party app to post to your social networking feed? Say, using a plugin in WordPress to tweet about your new blog post as and when you publish it? Yes, that is possible by means of API. In fact, many games and apps that rely on social logins via Facebook or Google accounts use APIs to interact with the concerned social networking services.

Therefore, the lesson here is that APIs allow developers to use content and features from a different application, service, or platform in a service, platform, or application of their own, in a secure and limited manner.

Defining REST

Much like API, REST is also an acronym, and it is sometimes written as ReST. It stands for Representational State Transfer and refers to a given style of API-building. Almost all the major web services, such as Google, Facebook, and Twitter, rely on REST for their APIs simply because REST is based on HTTP (which happens to be the protocol that powers nearly all of the Internet connections). Plus, REST is lightweight and flexible and can handle large volumes of activity with ease.

Therefore, REST in itself is not a new trend and has been used on the web to power services for quite a long time. Thus, for WordPress users, harnessing the power of REST API means your applications can interact with a load of services right from within WordPress, with the help of REST API.

Thus, REST is an architectural paradigm for web services, and services that use such an architectural paradigm are known as RESTful services.

The underlying idea behind REST is that instead of relying on complex web services such as SOAP or XML-RPC, a simple HTTP protocol is used for making connections. Therefore, all RESTful applications make use of HTTP requests for handling all four CRUD operations, namely create, read, update, and delete. This makes REST extremely versatile, and anyone can roll out their own version of REST with standard library features using the programming language of their choice, such as Perl or PHP.

Even more, REST is fully platform-independent, so you can use it in scenarios where the server might be Linux but the client can be using Windows and so on. Since it is standard-based and language-independent, a RESTful request carries with it all the information that might be needed for its execution or completion.

However, such simplicity and versatility does not mean that RESTful applications are weak in any regard. REST is powerful and can handle virtually every genre of action or request that might be expected from any of its counterparts.

Lastly, it is worth noting that much like the other web services such as SOAP or RPC, REST too does not offer encryption or session management features of its own. However, you can build such features on top of HTTP within minutes. For example, for security, you can rely on usernames/passwords and authentication tokens, whereas for encryption, REST can be used on top of HTTPS (secure HTTP). RESTful applications can function in the presence of firewalls as well.

Speaking of RESTful applications, what are some of the most common uses of REST in practice?

Well, Twitter has had a REST API since the very beginning, and for all practical purposes, it is still the most common API, being used by developers creating apps and tools that work with Twitter. You can learn more about it at  https://dev.twitter.com/rest/public.

Similarly, Amazon's S3 Cloud storage solution too relies on REST API; for more information, refer to  http://docs.aws.amazon.com/AmazonS3/latest/API/APIRest.html.

Flickr's API for external developers supports REST integration as well; for more information, refer to  https://www.flickr.com/services/api/request.rest.html.

And finally, the Atom feed services, an alternative to the otherwise more popular RSS, is RESTful in its nature.

We will come back to REST later in this chapter, but first, let us familiarize ourselves with another important term, JSON.

Defining JSON

JSON is an acronym for JavaScript Object Notation. As the name suggests, it is a form of data exchange format that is based on JavaScript. With more and more JavaScript libraries and services coming up, JSON is rising in popularity on the web.

The best part about JSON is that it is both machine and human-friendly in terms of reading and comprehension. As a developer, you can read it and write it as much as you would work with any other programming language, whereas computers can easily parse and process it too. In fact, many popular programming languages offer their own interpreters that can parse the output to JSON and back. This makes JSON ideal for cross-platform interaction application A coded in one programming language and application B coded in another programming language can interact by converting their data structures into JSON and back, and so on.

This feature of JSON has made it a universal connector on the web. For WordPress users, JSON can also be used to replace the nearly outdated XML-RPC standard (more on this in detail in a subsequent chapter of this book).

Now that we are aware of what the terms API, REST, and JSON stand for, let us come back to REST API and start by first learning more about the REST API in itself. Thereafter, we will focus on what it can do for WordPress developers and then get started with is usage in WordPress.

So, what can REST API do or, in other words, how has it been proving to be useful?

 

Using REST API in real-world applications


REST API has become the talk of the town in the WordPress community only fairly recently. However, it has been around for quite a long while, and RESTful services are, in fact, as old as the Internet itself.

We are aware that the Internet is made up of different computers and servers, speaking different languages and running different services and processes. As such, a common protocol has been evolved to enable such different services and processes to communicate with each other. Such protocols can be described as a set of given standards that allow for Internet communication in a given manner.

Now, REST API, in itself, sits on top of such protocols, and enables us to facilitate communication between different services and machines and helps us interpret the data exchange that might be ongoing between two different services. There are many other such services that do the same job as REST, but with a difference of their own. For instance, JMS is a similar technique exclusive to Java applications, whereas XML-RPC is a capable, popular, but slightly dated and less secure methodology that can facilitate communication between services, much like REST.

Advantages of REST services

So, what makes REST better? In simplest of terms, REST helps in data exchange with a set of well-established mechanisms and protocols and focuses more on minimum workload, unlike many other similar methods that are heavier and bulkier in terms of operation. As such, REST focuses more on efficiency and speed and offers cross-platform data exchange. This is, by far, the biggest advantage of using RESTful services.

Now, as the Internet expands, so do the devices and technologies associated with it. With more and more mobile devices coming to the fore and coding standards being curated to adhere to specific norms, REST APIs too are evolving in order to meet purer standards of implementation. Thus, while the implementation of REST API remains more or less uniform, the modus operandi of RESTful services coded in different languages or platforms can have some minor differences. This is obvious to some extent because REST is an architectural style and not an architectural standard, and unlike HTML5, you cannot expect a W3C compliant guideline for REST API.

Now that we have covered the basic details about REST API and its major benefits, it is time to actually get started with REST in practice. In the next section, I will now talk a bit about how REST requests and responses work across different platforms and languages. Plus, the coming section will also be discussing the basic functioning of REST, including how simple and complex requests work. This, of course, is more of a practical consideration and less of a puritan one, and you can skip the coming section and move straight on to WordPress REST API if you want, but for the sake of information and for those who might be interested in learning more about REST API across different services and platforms, let us discuss REST properly before heading toward its relation with WordPress.

 

Key considerations when working with REST


Before we go any further ahead, let us discuss some key considerations that are useful to bear in mind when working with RESTful applications and services.

Note

Since REST is an architectural style and not a standard, the following are considerations and not totally mandatory rules.

When working with WordPress, the following key considerations are something you should bear in mind. The question is, why so?

It is because many times you will be using REST API to communicate with services that may not be running on WordPress (for example, a third-party social network that your plugin might interact with). As such, if you follow the following norms when working with REST API in WordPress, you won't have to face issues with uniformity.

Architectural components in REST

The architecture of RESTful services is pretty straightforward and we can briefly summarize its main components as follows:

  • Resources are the key components of RESTful services. They are identified by logical URLs and are universally accessible by other parts of the system.

  • Resources should contain links to other information, much like web pages. Thus, resources should be interconnected.

  • Resources can be cached.

Note

Since HTTP is what RESTful services used, the HTTP cache-control headers are sufficient for this task.

  • RESTful systems follow the client-server model.

  • Standard HTTP proxy servers can be used in RESTful architecture.

  • REST services can interact with non-REST services, and vice versa.

Design principles in REST

REST is more of a style and less of a standard, so there are not many design principles to consider. In general, this is what you should follow:

  • GET requests should not cause a change in state or alter data. If you wish to modify the state or data, use POST requests.

  • Pagination is always a good practice; if your GET query reads entries, let it read the first N number of entries (for example, 20) and then use links to read more entries.

  • Physical URLs are considered a bad practice, and logical URLs should be preferred.

  • If the REST response is in XML, consider using a schema.

Also, for documenting a REST service, you can use Web Services Description Language (WSDL) or Web Applications Description Language (WADL). Both are feature-rich, but WSDL offers more flexibility as it does not bind itself to Simple Mail Transfer Protocol (SMTP) servers, whereas WADL is easier to read and interpret. And if either of them does not appeal to you, a simple HTML document too can suffice.

 

Getting started with REST implementation


We are now familiar with REST API and JSON. Plus, we also know that REST API is indeed useful in many different ways. Let us now try to put it into practice.

Passing commands in SOAP versus REST

Say, we need to query a given database for user details of a user with ID 1191. Using web services and Simple Object Access Protocol (SOAP), we will be doing something such as the following:

<?xml version="1.1"?> 
<soap:Envelope 
xmlns:soap="http://www.w3.org/2001/12/soap-envelope" 
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> 
<soap:body pb="http://www.example.com/database"> 
<pb:GetUserDetails> 
<pb:UserID>1191</pb:UserID> 
</pb:GetUserDetails> 
</soap:Body> 
</soap:Envelope> 

The preceding code will give us an embedded XML file inside a SOAP response envelope.

And how will we do this using REST? The following way: http://www.example.com/database/UserDetails/1191.

Yes, that is all. It is a simple URL with GET request, and the response will give us the raw data, that is, the details of the user with ID 1191. While in SOAP, we needed multiple libraries to parse the response, in REST, we just need to pass the simple URL. We can even test the API directly right within the browser as a simple request.

Of course, the preceding example is a simplified case, and if need be, REST libraries do exist. However, as it becomes clear, REST is way simpler than web services and other counterparts.

Tip

Downloading the example code You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

  7. Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learning_WordPress_REST_API. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Handling data in REST

For complex operations, the methodology remains similar. Let us refine the preceding query and look for the user with first name Sample and last name User as follows: http://www.example.com/database/UserDetails?firstName=Sample&lastName=User.

As we can see, for longer parameters, we are including the parameters within the body of the HTTP POST request. At this point, it is useful to discuss REST requests in themselves.

For simpler queries of a read-only nature, GET is the de facto standard. However, for read-only queries that are complex in nature, POST requests can be used. Of course, POST requests are also used for queries that can change the state of the data and deal with creation, updating, and deletion of data.

If you are wondering how to distinguish a simple query from a complex one, consider this: when reading a blog, you send a GET request as a simple query to open the page, but if you decide to post a comment on the blog post or share it via any of the social networks, you send a POST request with additional and more complex details.

And in terms of server responses, RESTful services can handle XML, CSV, and JSON. Each of these formats has its own advantages: XML, for example, is pretty easy to expand, CSV is compact and lightweight, whereas JSON is easy to parse. As you might have guessed by now, for WordPress REST API, JSON is the way to go, all thanks to JavaScript.

Note

Unless the response needs to be read by humans, HTML is not the de facto choice for REST server responses. Of course, since almost everything on the World Wide Web needs to be read by humans, HTML is being used as a server response for RESTful services.

 

Using REST in different programming languages


As the final part of our discussion on REST and RESTful services, before we dive toward WordPress and start the next chapter, let us take a look at usage and implementation of REST in different programming languages. If you are an existing WordPress developer and are well-versed with PHP, you might wish to skip this section and move ahead. However, for the benefit of those who might have migrated to WordPress development or those who are familiar with some other popular web development language, I have provided the methods for sending GET and POST requests via HTTP in the programming languages that I know of.

Let us begin with Ruby.

Ruby

In Ruby, you can send HTTP requests using the Net::HTTP class. Thus, for GET requests, to look up the record number 1191 from the database of example.com, this is how you should do it:

require 'net/http' 
url = 'http://www.example.com/database/1191' 
resp = Net::HTTP.get_response(URI.parse(url)) 
resp_text = resp.body 

In the preceding example, we are using an object to handle the HTTP response code.

Similarly, for POST requests:

require 'net/http' 
url = 'http://www.example.com/database/user' 
params = { 
firstName =>'Sample', 
lastName =>'User' 
} 
resp = Net::HTTP.post_form(url, params) 
resp_text = resp.body 

Here again, we are using Net::HTTP class and using the post_form method for POSTing.

Python

In Python, we already have the urllib2 module, so for RESTful actions, we just need to pass the GET request and then handle the response.

For example:

import urllib2 
url = 'http://www.example.com/database/1191' 
response = urllib2.urlopen(url).read() 
And for POST requests, we will once again rely on the urllib2 module: 
import urllib 
import urllib2 
url = 'http://www.example.com/database/user' 
params = urllib.urlencode({ 
'firstName': 'Sample', 
'lastName': 'User' 
}) 
response = urllib2.urlopen(url, params).read() 

In the preceding code, we are passing the request data as an extra parameter.

Perl

Personally, I have always relied on LWP, the library for WWW in Perl, for REST requests via HTTP.

For example, a GET request would look something like the following:

use LWP::Simple;
my $url = 'http://www.example.com/database/1191';
# sample request
my $response = get $url;
die 'Error getting $url' unless defined $response;

The preceding code is sufficient for a GET request without additional headers. For something more complex, you should consider creating a browser object in Perl and then handling it accordingly as follows:

use LWP;
my $browser = LWP::UserAgent->new;
my $url = 'http://www.example.com/database/1191';
my $response = $browser->get $url;
die 'Error getting $url' unless $response->is_success;
print 'Content type is ', $response->content_type;
print 'Content is:';
print $response->content;

Now, if you need to issue a POST request, you can follow the preceding approach again, and create a browser object and then pass the POST request as follows:

my $browser = LWP::UserAgent->new;
my $url = 'http://www.example.com/database/1191';
my $response = $browser->post($url,
[
'firstName' =>'Sample',
'lastName' =>'User'
];
);
die 'Error getting $url' unless $response->is_success;
print 'Content type is ', $response->content_type;
print 'Content is:';
print $response->content;

In the preceding example, we are using the browser object for issuing the POST request and then mapping the field names directly to the values.

For working with complex REST operations in Perl, you should consider learning more about LWP (the library for www in Perl).

C#

C# as a programming language has structures and concepts of its own. For all practical purposes, you will need to use the .NET classes HttpWebRequest and HttpWebResponse for handling REST requests sent via HTTP.

For example, the following is what a typical GET request in C# would look like:

static string HttpGet(string url) { 
HttpWebRequest req = WebRequest.Create(url) 
as HttpWebRequest; 
string result = null; 
using (HttpWebResponse resp = req.GetResponse() 
as HttpWebResponse) 
{ 
StreamReader reader = 
new StreamReader(resp.GetResponseStream()); 
result = reader.ReadToEnd(); 
} 
return result; 
} 

What does the preceding code do? It simply passes a request and then returns the entire response as one long string. For backward compatibility, I would suggest that if you are passing parameters with your requests, it is advisable to properly encode them. You can use any of the native C# classes or methods for such encoding.

For passing POST requests, the method is similar to GETing, as shown in the following:

static string HttpPost(string url, 
string[] prName, string[] prVal) 
{ 
HttpWebRequest req = WebRequest.Create(new Uri(url)) 
as HttpWebRequest; 
req.Method = "POST";  
req.ContentType = "application/x-www-form-urlencoded"; 
 
// Creating a string, encoded and with all parameters 
// Assuming that the arrays prName and prVal are of equal length 
StringBuilder przz = new StringBuilder(); 
for (int i = 0; i < prName.Length; i++) { 
przz.Append(prName[i]); 
przz.Append("="); 
przz.Append(HttpUtility.UrlEncode(prVal[i])); 
przz.Append("&"); 
} 
 
// Encoding the parameters 
byte[] frDat = 
UTF8Encoding.UTF8.GetBytes(przz.ToString()); 
req.ContentLength = frDat.Length; 
 
// Sending the request 
using (Stream post = req.GetRequestStream())  
{  
post.Write(frDat, 0, frDat.Length);  
} 
 
// Getting the response 
string result = null; 
using (HttpWebResponse resp = req.GetResponse() 
as HttpWebResponse)  
{  
StreamReader reader = 
new StreamReader(resp.GetResponseStream()); 
result = reader.ReadToEnd(); 
} 
 
return result; 
} 

Once again, we have encoded the parameters in the preceding code and have accepted a request and returned the response.

Java

When using REST requests in Java, the concept is similar to that of C#, and an experience Java coder can easily pick up the ropes. Basically, you use the HttpURLConnection class and invoke its object type. Following is an example for a GET request:

public static String httpGet(String urlStr) throws IOException { 
URL url = new URL(urlStr); 
HttpURLConnection conn = 
(HttpURLConnection) url.openConnection(); 
if (conn.getResponseCode() != 200) { 
throw new IOException(conn.getResponseMessage()); 
} 
// Buffering the result into a string 
BufferedReader drdr = new BufferedReader( 
new InputStreamReader(conn.getInputStream())); 
StringBuilder sb = new StringBuilder(); 
String line; 
while ((line = drdr.readLine()) != null) { 
sb.append(line); 
} 
drdr.close(); 
conn.disconnect(); 
return sb.toString(); 
} 

In the preceding code, we are issuing a GET request and then accepting the response as one long string. If you wish to use it in your projects, you might wish to tweak it a bit, probably with the help of try or catch. Plus, note that for backward compatibility, it is advisable to encode the parameters that are passed with the request URL.

Now, for POST requests, this is how we will work:

public static String httpPost(String urlStr, String[] prName, 
String[] prVal) throws Exception { 
URL url = new URL(urlStr); 
HttpURLConnection conn = 
(HttpURLConnection) url.openConnection(); 
conn.setRequestMethod("POST"); 
conn.setDoOutput(true); 
conn.setDoInput(true); 
conn.setUseCaches(false); 
conn.setAllowUserInteraction(false); 
conn.setRequestProperty("Content-Type", 
"application/x-www-form-urlencoded"); 
 
// Creating form content 
OutputStream out = conn.getOutputStream(); 
Writer writer = new OutputStreamWriter(out, "UTF-8"); 
for (int i = 0; i < prName.length; i++) { 
writer.write(prName[i]); 
writer.write("="); 
writer.write(URLEncoder.encode(prVal[i], "UTF-8")); 
writer.write("&"); 
} 
writer.close(); 
out.close(); 
 
if (conn.getResponseCode() != 200) { 
throw new IOException(conn.getResponseMessage()); 
} 
 
// Buffering the result into a string 
BufferedReader drdr = new BufferedReader( 
new InputStreamReader(conn.getInputStream())); 
StringBuilder bsbs = new StringBuilder(); 
String line; 
while ((line = drdr.readLine()) != null) { 
bsbs.append(line); 
} 
drdr.close(); 
 
conn.disconnect(); 
return bsbs.toString(); 
} 

Once again, we are accepting a POST request with a parameter and then passing the response accordingly.

Note

You will need to supplement this code with try/catch structures before inserting it within your projects.

Also, an experienced Java coder will be aware that Java is not the most popular language for web development and that its support for handlers for web connections is not at the top of its league. It is, therefore, a good idea to make use of packages and handlers from the Apache library for this purpose. However, we will evade this discussion now since it is beyond the scope of this book, and Java code is of little merit for someone whose primary focus might be on using RESTful services with WordPress.

PHP

Now, finally, we come to the language in which WordPress has been coded. Using REST in PHP is very easy because even the most basic PHP functions with a file-access model can work seamlessly with HTTP requests and URLs.

Therefore, for GET requests, virtually any file-reading function of PHP can do the job, such as fopen, for example:

$url = "http://www.example.com/database/1191";
$response = file_get_contents($url);

echo $response;

If you are passing parameters with GET requests, it might be a good idea to encode them.

However, while GET requests are pretty easy to handle, POST requests require a bit of work because you need to open a connection to the target server and then send the HTTP header information. For example, consider the following code:

function httpRequest($host, $port, $method, $path, $prms){ 
// prms is to map from name to value 
$prmstr = ""; 
foreach ($prms as $name, $val){ 
$prmstr .= $name . "="; 
$prmstr .= urlencode($val); 
$prmstr .= "&"; 
} 
// Assign defaults to $method and $port 
if (empty($method)) { 
$method = 'GET'; 
} 
$method = strtoupper($method); 
if (empty($port)) { 
$port = 80; // Default HTTP port 
} 
 
// Create the connection 
$sock = fsockopen($host, $port); 
if ($method == "GET") { 
$path .= "?" . $prmstr; 
} 
fputs($sock, "$method $path HTTP/1.1\r\n"); 
fputs($sock, "Host: $host\r\n"); 
fputs($sock, "Content-type: " . 
"application/x-www-form-urlencoded\r\n"); 
if ($method == "POST") { 
fputs($sock, "Content-length: " . 
strlen($prmstr) . "\r\n"); 
} 
fputs($sock, "Connection: close\r\n\r\n"); 
if ($method == "POST") { 
fputs($sock, $prmstr); 
} 
// Buffer the result 
$result = ""; 
while (!feof($sock)) { 
$result .= fgets($sock,1024); 
} 
fclose($sock); 
return $result; 
} 

Now, using the preceding sample function, we can issue a POST request as follows:

$resp = httpRequest("www.example.com", 
80, "POST", "/Database", 
array("firstName" =>"Sample", "lastName" =>"User")); 

We can also use the client URL request library (cURL) when working with RESTful requests in PHP.

JavaScript

Having covered all of that, let us finally discuss REST implementation in JavaScript. We will be saving the JSON issue for detailed discussion during the course of this book, so let's just focus on the traditional route now.

REST requests can be sent from client-side or in-browser JavaScript. If you have ever worked with an AJAX application, you have followed the REST design principles to a great extent, with the response being in JSON.

HTTP requests in JavaScript require the XMLHttpRequest object. The following function is a simple way to create the object:

function createRequest() { 
var result = null; 
if (window.XMLHttpRequest) { 
result = new XMLHttpRequest(); 
if (typeof xmlhttp.overrideMimeType != 'undefined') { 
result.overrideMimeType('text/xml'); // Or anything else 
} 
} 
else if (window.ActiveXObject) { 
result = new ActiveXObject("Microsoft.XMLHTTP"); 
} 
return result; 
} 

Now that you have created the object, you are ready to send HTTP requests. However, the XMLHttpRequest object, while it can send requests, cannot return values by default. So it is better to have a callback function that can be invoked when your request is completed.

Thereafter, you are ready to send the request. For a GET request, the approach is fairly simple:

req.open("GET", url, true); 
req.send(); 
And for POST requests: 
req.open("POST", url, true); 
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
req.send(form-encoded request body); 

As you can see, sending HTTP requests in JavaScript is pretty easy and you just need to call the appropriate function.

 

REST API in WordPress


So, now that we have seen the benefits and features of REST API and also learned a bit about JSON, how exactly can it be useful for WordPress developers?

Well, there is a lot that REST API can do in WordPress.

To begin with, the WordPress REST API is revolutionary in the sense it can help us build new applications with WordPress. Specialized editors, site management tools, and more can be created and run even without a custom API and without a companion plugin being installed on the WordPress website. As such, a WordPress theme can use the REST API to load content dynamically, and practically speaking, WordPress in itself can function as a full-fledged architectural framework.

Let us see some of the major benefits that REST API brings to the world of WordPress.

Universality

WordPress has had an API of its own for quite a while, and as such, the API part is nothing new for WordPress developers. In fact, if you have ever coded a plugin for WordPress, you might already be aware that WordPress uses its API to interact with the plugin.

However, the old WordPress API is ideal for internal processes such as a plugin, but hardly useful for external services. REST API, on the other hand, is perfect for allowing WordPress to interact with services outside of WordPress.

In other words, with REST API on board, WordPress can interact with services and websites on the Internet, which may or may not use WordPress! Yes, WordPress REST API can interact and exchange information with any service on the web that might be coded in a different language, running a different code structure, or be of a different nature.

Similarly, you can also let external services interact with WordPress content with the help of REST API. Thus, any service or website making use of REST API can now interact with your WordPress website and its posts, pages, custom post types, taxonomies, users, and more with ease, as long as it runs on the HTTP protocol (which is supported by nearly all of the Internet nowadays).

In HTTP, the POST, GET, UPDATE, and DELETE requests will allow you to create, read, update, and delete content, respectively. We shall revisit these steps with code examples in later chapters of this book, as we progress through our journey with REST API in WordPress.

Remote management

WordPress REST API comes with safety measures of its own, such as cookie-based and OAuth authentication.

Cookie-based authentication is useful for plugins and themes, whereas OAuth authentication (relying on http :// oauth . net /) can be used to authenticate desktop, mobile, and web clients. This will allow WordPress REST API to define limited and clearly defined data exchange; the external service will be able to view and edit only that section of data that is made available to it, nothing else.

Note

Notice the terms desktop, mobile, and web clients in the preceding paragraph; REST API enables remote management for WordPress. You can manage your WordPress website from a desktop client installed on your computer or a mobile application, without actually having to visit the WordPress admin panel at all!

As such, you can build clients that let you create and publish a blog using WordPress, but offer a minimal and more interactive interface than the WordPress admin panel. Since JSON is natively supported by both Android and iOS, WordPress REST API is a special boon for mobile developers who can build mobile applications that make use of REST API for interacting with WordPress platforms while running on Android or iOS.

Third-party support

As already stated, REST API enables WordPress to interact with services and sites that might not be built on WordPress, and vice versa. However, what can we expect from such cross-platform and third-party support?

Well, this means we can now procure content and interact with data from any other platform as long as we follow the HTTP route. For example, we can now allow Ruby on Rails (RoR) applications to interact with WordPress websites, while WordPress too can interact with systems that are otherwise not coded in PHP.

This is especially useful for folks who are working with third-party tools and need to interact with WordPress regularly. Furthermore, frontend developers can now focus on the frontend of their website without having to worry about the backend, all thanks to WordPress REST API.

Even more so, REST API can be used by WordPress developers to take their plugin and themes to non-WordPress platforms and other CMSs.

 

Summary


It is obvious that REST API is a path breaking and revolutionary innovation that has the ability to transform how we code with WordPress. With better interaction and collaboration across multiple platforms and services, REST API can help us build better and more useful applications in WordPress and do more with our development workflow.

Over the course of the next chapters of this book, you will learn how to use REST API to interact with WordPress and create, read, edit, and delete data. Plus, you will also learn how to deal with taxonomies and users, as well as custom routes and create web apps using WordPress REST API. We will discuss the basics of working with and extending the default routes used by WordPress REST API, as well as creating our own endpoints.

I hope this book will prove useful in helping you learn more about and master WordPress REST API as well as tapping its potential to the fullest in order to benefit from the many new features that REST API brings to the table.

About the Author

  • Sufyan bin Uzayr

    Sufyan bin Uzayr is a writer, teacher, and developer with 10+ years' experience in the industry. He is an open source enthusiast and specializes in a wide variety of technologies. He holds four masters' degrees and has authored multiple books.

    Sufyan is an avid writer. He regularly writes about topics related to coding, tech, politics, and sports. He is a regular columnist for various publications and magazines.

    Sufyan is the CEO of Parakozm, a software development company catering to a global clientele. He is also the CTO at Samurai Servers, a web server management company focusing mainly on enterprise-scale audiences.

    In his spare time, Sufyan teaches coding and English to young students.

    Learn more about his works at sufyanism (dot) com.

    Browse publications by this author

Latest Reviews

(3 reviews total)
Good introduction to the subject
Excellent
Good book for an introduction to WordPress as a Web Application Framework.

Recommended For You

Book Title
Access this book, plus 8,000 other titles for FREE
Access now