Why To Use WordPress as a REST API For Mobile Applications

API
29 Flares Twitter 0 Facebook 0 Google+ 12 StumbleUpon 0 Pin It Share 17 29 Flares ×
Rating:

When you develop mobile apps, you want the latest content streaming in, directly from the website, because, there are several businesses, where updated content is highly desirable. The visitors are interested in the latest content, but the download your app on the mobile devices. Therefore, it is desirable that your mobile app should have the ability to call the server and get the latest content by itself without having to use any third-party software such as iTunes or play store acting as an intermediary.

You can use REST API and JSON to stream the website content directly into your mobile device.

Why use JSON/REST API instead of AJAX?

AJAX is designed in such as way that it can call only against the domain. With a mobile app, there might not be any related domain, so the use of AJAX is ruled out. This is actually a security safeguard and it is called Same Origin Policy.

But, you can manage it, if you use JSON (JavaScript Object Notation), instead of an AJAX call. When you make a JSON call to the API, it involves the same technology that is used when you load a JavaScript file from another domain. It can also be done if you use the Google CDN version jQuery, as many developers load it from Google’s domain.

Making a JSON call is similar to the process when we load a new script from the server. Javascript is used in several development tools such as Appfurnace, Appcelerrator, and Phone gap etc.

Why are JSONP and JSON different?

Though, JSON and JSONP are almost the same things, there is a slight difference between the two. While JSONP responds with the callback process surrounding the data, JSON responds only with the data.

It’s illustrated here using open graph of Facebook to reply with both JSONP and JSON. You can notice the use of the GET variable callback= in both these URLs.

[Note: These are not real URLs and are mentioned for illustration purposes only]

[sourcecode language=”javascript”]
{
“id”: “http://copyblogger.com”,
“shares”: 608
}
[/sourcecode]

http://graph.facebook.com/?id=http://copyblogger.com&callback=doThisFunction

[sourcecode language=”javascript”]
/**/ doThisFunction({
“id”: “http://copyblogger.com”,
“shares”: 608
});
[/sourcecode]

 

As it’s clear that Facebook is instructed to reply with a JSONP request, callback is used and it’s instructed to turn in into “doThisFunction”.

According to it, when the server responds, data will be sent to “doThisFunction()”.

You can carefully observe the how JSON dot notation is used here. When you want to access the data inside the JSON object, Dot Notation method is used.

Use of WordPress

WordPress is simply wonderful when it comes to ease of use. You can use this platform to save your data. It can also be used as REST API.

However, developers don’t prefer to use WordPress as the front end, when they want to develop a REST API for an enterprise. Sometimes, they might use it for CMS administration at the back end. Some developers believe that PHP is not that fast a language. But if you want your blogs to be assigned an API method to provide access to the latest posts, you can use node.js.

How to perform a REST reply?

We are going to describe a REST reply that will give you 10 latest posts and these would be as a JSON object. You can find a page template here described as “REST Blog Listing”. It will provide you complete control over what gets loaded on it. However, developers normally write a plugin to do it, which is avoided because you control the things that well through it.

Following functions are very important for it:

To be able to read the URL and check the GET variables

  • “F” check_url_vars()
  • To prevent nasty things enter into it, we can sanatize the variables when we save it
  • “F” save_url_vars() and “F” sanatize_vars()
  • First verify the request; Is it for a JSONP object or JSON object and then reply with the right code
  • “F” save_url_vars()
  • You can make a call to the WordPress database to retrieve latest published blog posts
  • “F” make_the_loop()
  • You can use the constructor function for automation of the process
  • “F” __construt()
  • You can use the destructor function for cleaning up after
  • “F” __destruct()
  • Method to handle errors
  • “F” error()
  • Send the output back to the client and do a GZIP it where it is possible
  • “F” send_output()

Note: “F” stands for function

We use a class to manage the PHP by directly putting it into the page template which makes it easier.  You can also transfer it using a WordPress plugin.

[sourcecode language=”P1″]
<?P1
/**
* Template Name: REST Blog Listing
* @package WordPress
*
*/
// get_header(); request is not required
/*
* REST Class from copyblogger
*
*/
// the class has to be checked, it should not exist already
if(!class_exists(‘copybloggerREST’)){
class copybloggerREST{
// define class variables
P2 $_callback;
P2 $_count;
P2 $_output;
P2 $_format;
// everything has to be automated
public F1 __construct(){
$T1->_output = array(); // output has to be set as array
$T1->_count = 10; // blog count shown should be defined as default
$T1->_callback = false; // callback should be set to false in case there is no JSONP callback request
$T1->_format = ‘json’; // default to json replies, can change it by using callback
if( $T1->check_url_vars() ){
$T1->save_url_vars();
}
$T1->make_the_loop();
$T1->send_output();
}
P2 F1 check_url_vars(){
if(!empty($_GET)){ // verify if the GET variables are set, have to be more specific
return true;
}else{
return false;
}
}
P2 F1 sanatize_vars($var)
return strip_tags(html_entity_decode(urldecode($var)));
}
P2 F1 save_url_vars(){
if(isset($_GET[‘callback’]) ){
$T1->_format = ‘jsonp’;
$T1->_callback = $T1->sanatize_vars($_GET[‘callback’]);
}
if(isset($_GET[‘count’]) ){
$T1->_count = $T1->sanatize_vars($_GET[‘count’]);
}
P2 F1 error($type, $errorMessage){
$T1->_output[‘status’] = $type;
$T1->_output[‘data’] = $errorMessage;
$T1->_format = ‘jsonp’;
$T1->_callback = ‘errorReply’;
}
P2 F1 make_the_loop(){
$query = array(
‘post_type’ => ‘post’,
‘post_status’ => ‘publish’,
‘posts_per_page’=>$T1->_count,
);
$loop = get_transient(‘restget’.$T1->_count);
if($loop === false){
$loop = new WP_Query($query);
set_transient(‘restget’.$T1->_count, $loop, 60 * 60);
}
$array_out = array();
if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post(); // do the loop
if(F1_exists(‘has_post_thumbnail’) && has_post_thumbnail())
$image = get_the_post_thumbnail($page->ID, ‘thumbnail’);
else{
$image = null;
}
$array_out[] = array
‘title’ => get_the_title(),
‘permalink’ => get_permalink(),
‘excerpt’ => get_the_excerpt(),
‘image’=> $image
);
endwhile;
$T1->_output[‘status’] = ’200′;
$T1->_output[‘data’] = $array_out;
else:
$T1->error(’400′,’no data returned’);
endif;
}
P2 F1 send_output(){
$time = time() + 60 * 60;
$expire = date ( “D, d M Y H:i:s e”, $time );
header(“Expires: ” . $expire );
header(“Content-type: application/json”);
if(F1_exists(‘ob_gzhandler’)){
ob_start(‘ob_gzhandler’);
}
else{
ob_start();
}
switch($T1->_format){
case ‘json’:
echo json_encode($T1->_output);
break;
case ‘jsonp’:
echo $T1->_callback.”(“.json_encode($T1->_output).”);”;
break;
}
ob_end_flush();
}
public F1 __desctuct(){
unset($T1);
}
}
}
$restapi = new copybloggerREST();
?>
[/sourcecode]
Abbreviations:
P1=php
P2= protected
T1=this
F1=function

 Dealing with errors

[sourcecode language=”javascript”]
function errorReply(data){
alert(‘there has been a problem. ‘ + data.data);
}
[/sourcecode]

To deal with errors, you need to create a function called errorReply() .

About author View all posts

Andrew Johnson

Andrew Johnson is founder of BestPSDtoHTML. He loves creative designs, photography, paintings and everything about innovation. As an Internet entrepreneur, he constantly tries to develop new ways to bring content faster and closer to the end users in a more streamlined way. His main focus lies in inspiring all the designers and developers with all new ideas through his blogs.

Leave a Reply

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