Develop Web API

It is quite common now a days for a website to make a way for other sites to post information from their site. Especially e-commerce sites that have many products. How does the other site get up to date information from their site? That is where Web APIs come into play. A Web API is a set of site addresses that will return information to be displayed somewhere else. For an example, a site that shows the current exchange rates for foreign currency would allow other sites to query their API to display that information as well. It becomes another way to provide information or services that other web sites can use.

The usual approach to doing a Web API is to create a PHP script that is separate from their website that will provide the needed information. The question comes to my mind, why? Why not just use the current framework you use for your website to generate the information for your Web API? That is exactly what I want to show you in this tutorial.

We will create this new API using a custom post type and some extra PHP logic inside of a WordPress Action to act upon the request.

Things you need:

The API Post Type

In Script Manager, create a new WPPHP script with the name ‘WebAPI’ and place the following code:

//
// Reference global variables that we will use.
//
global $wpdb;

//
// This is for registering the API post type.
//
$result = register_post_type('API',array(
   'public'=> true,
   'supports' => array(
      'title',
      'editor',
      'page-attributes'         // This is required to get hierachical to work!
   ),
   'hierarchical' => true,
   'query_var' => 'APIs',
   'rewrite' => array(
      'slug' => 'API',
      'with_front' => false
   ),
   'labels' => array(
      'name' => 'APIs',
      'singular_name' => 'API',
      'add_new' => 'Add New API',
      'add_new_item' => 'Add New API',
      'edit_item' => 'Edit API',
      'new_item' => 'New API',
      'view_item' => 'View API',
      'search_items' => 'Search APIs',
      'not_found' => 'API not found',
      'not_found_in_trash' => 'No APIs are in the Trash'
   ),
   'menu_icon' => 'http://www.customct.com/wp-content/uploads/2012/03/API.png'
));

//
// Now, we need to see if we are currently serving an API request.
//
$slug = $_SERVER["REQUEST_URI"];
$apistr = preg_split('/API/',$slug);

//
// If the preg_split array is larger than one, then it is an API page.
//
if(count($apistr) > 1) {
   //
   // Split out the parts of the address line.
   //
   $page = explode('/',$apistr[1]);

   //
   // Get the post for the API page.
   //
   $query = new WP_Query( array( 'post_type' => 'API', 'name' => $page[1] ) );

   //
   // If found, evaluate it and give it to the user.
   //
   if ( $query->have_posts() ) {
      //
      // Get the post information into the helper functions.
      //
      $query->the_post();

      //
      // The the body of the post that has the PHP script.
      //
      $script = do_shortcode(get_the_content());

      //
      // Evaluate the script and echo the results.
      //
      echo eval($script);
   }

   //
   // Exit. We do not want the normal page stuff.
   //
   exit();
}

In lines 1-33, we once again create a new post type. We have used new post types for several of our other tutorials:

Please read these tutorial to understand this section of code. Since I am not using anything new from the other tutorial, I will leave them to speak for themselves.

There is one exception to the above. I decided I would like to make the Web API hierarchical for grouping many common functions together, but I could not figure out how to get a custom post type to have a parent. Finally, I have solved it! Lines 14 and 16 are necessary to get hierarchical custom post types. I looked everywhere, but finally came across this by trail and error. Therefore, if you want a custom post type with hierarchical order, make sure you have these two lines!

The majority of uniqueness of this script is the last part of the script. In lines 35-79, the script will check for the current page being served to see if it is an API post type. All urls for the API post type has the keyword “API” (All capitals) in it. So, just searching for those letters in a case-sensitive search is enough to determine that this is an API post type. You will just have to make sure you do not use “API” in all capitals on any url on your site. This can easily be changed to some other letter/number sequence. If you want something else to designate these type of posts, just change the value of “rewrite->slug”.

Once it is determined that it is an API post, the next thing done is to get the script to be executed from the database. This is done by the WP_Query function on line 53. This line will look for all post with the “API” type and the name retrieved from the url. The name is the last part of the url after “API” and with the “/” characters removed.

If a post was found matching this description, then the contents of the post is evaluated as a PHP script and the results returned to the requester. Notice the use of the WordPress function “do_shortcode()”. This function will process any shortcodes in the HTML parts of the script. Therefore, if you want to include any WordPress shortcodes, then close out PHP processing with the "?>" PHP closure tag and then insert the shortcode you want.

Once we have executed the code or not find any code, we simply exit. Therefore, the requester will get absolutely nothing if the API code is not there.

That is it! Not much code, but a whole lot of functionality! To put this to work, we have to embed this in a WordPress Action just before the header information is generated. I chose to use the “wp_loaded” action for just that purpose. Create a new WordPress Action called “wp_loaded” and embed this code (assuming you are naming your scripts as I have in this tutorial):

[CodeInsert lang='WPPHP' name='WebAPI' param='']



This shortcode will embed our WebAPI script above into the “wp_loaded” Action. Once there, you will see the icon for the API post type in the admin menu to the left on the admin screen on the next refresh (see picture to the left). Here, you can view your different API posts for editing, or create new API posts.

Now, let’s test out what we have done. Create a new API post page and put the following inside:

echo "

This is PHP hello!

"; ?>

This is HTML hello!

When you view this page, all you see is:

This is PHP hello!

This is HTML hello!

If you look at the source for the page, you will see:

This is PHP hello!

This is HTML hello!

No theme stuff (The numbering is my CodeHighlighter shortcode and has nothing to do with the output of the API page). Just some plain text. But, that is exactly what you want when you are serving out an API. You want to be able to just send the raw data that the user needs. The program that requests it can then format it any way they want. You could use this to serve pages that have a unique look and feel, but does not affect the rest of the site. Or, it can return a JSON list of data (ie: Current items on sale, Most viewed articles, …) that the requesting program will read in and display in a format that matches their theme or need. Since we are stopping WordPress from producing any output to the requester, we have complete control over what is sent.

Also, notice the code in the API page: it starts as PHP, then the PHP closure code, then HTML. The script is executed as a PHP script, but you can then go down to HTML, and then back into PHP. This gives you complete flexibility to use both to make the request. In the PHP, you have full access to all WordPress functions as well. Therefore, you can easily query for articles, sales items, or what ever you have on your site to send to the requester.

Since you have all of the PHP information, you can also process information sent to you from the requester. Just get it from the $_COOKIE, $_GET, $_POST or $_REQUEST global variables. Just remember to do proper validation on all input from the requester so you do not get your site hacked! With flexibility and power comes more areas for attack as well. Just keep that in mind!

Note: You will want to stop WordPress from formatting your posts. Please see the tutorial Stopping WordPress from auto formating for details on how to do that. Otherwise, WordPress will automatically add paragraph markup pairs to your API contents when you query from the database. In side of a PHP script, this would cause errors in running the code.

Examples

For an example, create an API post called “comments” and place this code in the post:

?>

Hi , here are the top 5 posts ordered by number of comments:

  • ()
  • Sorry, no posts were found.

Once you have saved the post, click “View API” at the top of the page. You will see this:

Hi there, here are the top 5 posts ordered by number of comments:

New Theme Configuration Problems (1)
A new tutorial: The Tutorial Post Type (0)
New Tutorial: Color Wheel App (0)
New Tutorial: Smoothly Scrolling Sidebar (0)
Screen Cast first pass is on the site! (0)

But, it is not showing the name, but the word “there”! In the address bar of your browser, add this to the end of the current address:

?name=richard

When you press enter again, the name will show up in the first sentence.

Hi richard, here are the top 5 posts ordered by number of comments:

New Theme Configuration Problems (1)
A new tutorial: The Tutorial Post Type (0)
New Tutorial: Color Wheel App (0)
New Tutorial: Smoothly Scrolling Sidebar (0)
Screen Cast first pass is on the site! (0)

(Note: The post name and stats is taken from this website. There is not many comments right now!) You can see this yourself from this website. Click this anchor (Not currently working) and you will see the same page. If you add a comment on a post somewhere in this site, the number count will also increase. Give it a try!

Notice, the code will not print the name received from the requester if it has anything other than letters. This is to protect from possible code injection. Remember, never trust requester given data! Always check it out well!

Example using Shortcodes

Let’s move our PHP code to a Script Manager WPPHP script. First, create a WPPHP script called “comments” and place this code there:

if(ctype_alpha($_GET['name']))
   echo $_GET['name'];
else
   echo "there";
?>, here are the top 5 posts ordered by number of comments:

  • ()
  • Sorry, no posts were found.

This is mostly the exact same code. We left a little of the beginning line out. Now change the code in the comments API page to:

?> 

Hi [CodeInsert lang='WPPHP' name='comments' param='']

The first thing on the line tells the PHP interpreter that the rest of the line is HTML. The “do_shortcode()” function in the API script will evaluate the shortcode for embedding the WPPHP into the code for the comments API page. Doing your API this way, you can edit your API code in the Script Manager code editor. Any number of shortcodes can be used in an API page.

Conclusion

I hope you have enjoyed this tutorial. It has been fun making it. Try it out for yourself and let us know what you are able to do. You can share some of your favorite code in the forum as well.

comments powered by Disqus