Book Image

Learning WordPress REST API

By : Sufyan bin Uzayr, Mathew Rooney
Book Image

Learning WordPress REST API

By: Sufyan bin Uzayr, Mathew Rooney

Overview of 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.
Table of Contents (16 chapters)
Learning WordPress REST API
Credits
About the Authors
Acknowledgments
About the Reviewer
www.PacktPub.com
Preface

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.