Using the Plurk API with PHP

      1 Comment on Using the Plurk API with PHP

Short and Sweet

Micro-blogging sites like Twitter and Tumblr are very popular these days, because they allow users to quickly and concisely post status updates, news and event streams without the time and effort needed to compose a regular blog post. Many of these sites also offer free Web APIs, allowing you to easily mash up their content with data from other services or wrap a custom user interface around their core functionality.

While it’s quite easy to connect a PHP application to Twitter (I’ve discussed it in detail in this Devzone article), there exist a number of other free micro-blogging sites that also expose open APIs. In this article, I’ll introduce you to Plurk, which includes a JSON-based service API and also comes with a PHP library to simplify integration with Web applications.

Start Me Up

Before diving into the code, a few notes and assumptions. I’ll assume throughout this article that you’re familiar with HTML and JSON, and that you have a working Apache/PHP development environment with cURL and JSON support. I’ll also assume that you know the basics of working with classes and objects in PHP, as the components used in this article are written using OOP principles.

The Plurk API is accessed by sending a GET request to the Plurk service endpoint, which is currently http://www.plurk.com/API/. The method name and arguments are encoded into the request URL and the method response is returned as a JSON document. The JSON document usually contains the requested data as a structured JSON object. Here’s an example of one such API request, which returns a list of plurks matching the query term “green lantern”:

Here’s an example of the JSON document returned by the API for the request above:

At this point, it’s worth pointing out a few important things:

  • Every request to the Plurk API must be accompanied by an API key, which uniquely identifies the calling application. Once you have an API key, you can make up to 50,000 requests per day to the API – a limit that should be suitable for most deployed applications. You can obtain an API key from here.
  • Most requests to the Plurk API require authentication. This means that you must first create a user account with Plurk, and then use those account credentials to log in to the API. Plurk doesn’t yet support OAuth, so login must be performed using the API’s login() method. Successful login creates a session cookie, which is used to authenticate subsequent requests.
  • Methods and method parameters are fully documented in the online API documentation. This documentation is your roadmap to working with the API – it contains detailed information on available API calls, input parameters, error codes and return values. Keep it at hand, as you’ll be referring to it frequently throughout this tutorial.

All clear? Let’s rock and roll.

Going Green

Since the Plurk API returns a JSON document, and PHP offers a json_decode() function that can be used to read a JSON document into a PHP variable, it’s quite easy to build a simple PHP script that produces a list of plurks matching a particular search term. Here’s how:

This script begins by defining the URI to the Plurk search API method, and then building an HTTP query string containing the API key and search term. The entire URL is then requested using PHP’s file_get_contents() method, and the JSON response is decoded and turned into a PHP object using the json_decode() function. This information can then be extracted into an HTML page, as shown below:

Ready To Roll

The previous example used PHP’s built-in functions to manually send a request and receive a response from the API. However, Plurk also offers a ready-made PHP library that simplifies the task of integrating a PHP application with the Plurk API. This library offers an object-oriented interface to the Plurk API, internally handling tasks such as authentication, URL formulation and JSON decoding.

To try it out, download it from here, uncompress the package contents to your PHP include path, and then create and execute the following script, which demonstrates it in action:

This script begins by loading the PHP class and initializing a new service object. The service object’s login() method is passed the API key, username and password, which are used to log in to the Plurk API. Next, the query term is passed to the object’s search_plurk() method, which internally sends a request to the /API/PlurkSearch/search API method and returns a list of search results as a JSON document. The JSON document returned by the API is internally converted into a PHP response object. It is now quite easy to iterate over this object with PHP, retrieving each plurk’s owner and content, and then present this information as an HTML page.

Notice that each plurk actually contains two components: a qualifier and a body. Qualifiers are verbs, such as “likes”, “wants” and “loves”, and they’re used to define the main idea or theme for a plurk. Plurk offers users a long list of available qualifiers to prefix plurk content. When displaying a plurk, the qualifier will usually appear before the body.

Asking Questions

You can create an interactive search tool, simply by wrapping the previous script around a Web form. Here’s an example:

This script is very similar to the previous one, except that the query string passed to the search_plurk() method is retrieved from the user input submitted by the user. Here’s what the result looks like:

A word here about avatars: every Plurk user has the ability to upload a profile picture, or avatar, to represent his or her account. Avatar information is included with each user’s profile data and the Plurk API documentation provides information on how to derive the image URL from the information provided. The script above demonstrates how to implement this in practice by dynamically generating the URL for each user’s avatar image from the search_plurk() method response.

Checking The Timeline

To retrieve all the plurks posted by the currently logged-in user, use the get_plurks() method, which maps to the /API/Timeline/getPlurks API call. Here’s an example of it in action, returning the most recent 20 plurks:

The get_plurks() method accepts a number of arguments: a timestamp limiter, the start offset, and a number of additional Boolean variables indicating whether to return user plurks, private plurks or favorite plurks. As before, the response is a JSON document that contains details of each plurk. Here’s what it looks like:

To return all plurks visible to this user, including plurks posted by users being followed by this user, simply call get_plurks() without the third argument, as shown in this revised example:

Here’s the revised output:

Cleaning Up The CRUD

To post a new plurk through the API, use the add_plurk() method, which requires at least three arguments: a language identifier indicating the language of the plurk, a valid qualifier, and the actual plurk content. Here’s a quick example:

The add_plurk() method maps to the API method /API/Timeline/plurkAdd and, if successful, returns an object representing the newly-created plurk.

In a similar vein, there’s an edit_plurk() method, which accepts a unique plurk identifier and revised content, and takes care of updating the plurk.

Note that when editing a plurk, only the body of the plurk can be updated; the qualifier remains as is. If this isn’t what you’re looking for, you can use the delete_plurk() method to remove an existing plurk and then add it back with a new qualifier. Here’s an example of the delete_plurk() method in use:

Point, Click, Submit

With all this information at hand, it’s possible to build a Web application that allows users to view, delete and add posts to their Plurk wall. Take a look at the next script, which demonstrates:

This script might look complicated, but it’s actually quite simple. It displays a list of the user’s most recent plurks, together with an option to delete each plurk, and a Web form which allows the user to add a new plurk.

The script begins by loading the class libraries, initializing a service object and logging in to the Plurk API. It then checks whether the user has submitted a new plurk or requested deletion of an existing plurk by checking for the $_POST['create'] and $_POST['remove'] variables, performs the necessary actions, and then uses the get_plurks() method to retrieve a list of current plurks. These plurks are then formatted and displayed as usual.

Each displayed plurk is wrapped in a form with a hidden field containing the plurk’s unique identifier, and a submit button. If the user selects a particular plurk for deletion, the corresponding form is submitted. The form processor now finds the $_POST['remove'] variable and passes the plurk’s identifier to the delete_plurk() method to remove the plurk from the system.

Finally, the form to add a new plurk is a very simple form containing just two fields: a drop-down list of qualifiers, and an input field which allows the user to enter the body of the plurk. When this form is submitted, the form processor finds the $_POST['create'] field and uses the add_plurk() method described earlier to create and submit the plurk to the API.

Here’s a screenshot showing how a new plurk can be submitted through the form, together with a screenshot of the Plurk Web site showing the newly-submitted plurk:

The Who’s Who

In addition to allowing users to view, add, edit, delete and search plurks, the API also includes additional methods to search for and retrieve user profiles. This is implemented in the PHP library through the search_user() method, which maps to the /API/UserSearch/search API method. Here’s an example, which creates a Web form for user input and returns a list of user profiles matching the selected query:

In this script, the user input entered into the form is passed to the search_user() method, which searches the Plurk directory for user names and descriptions matching the query string. The method returns an array of user profiles, which can then be formatted for display as shown below:

Fanning The Flames

Plurk makes a distinction between a user’s friends (those who have actively acknowledged a relationship with the user) and fans (those who follow a user but don’t have an active relationship). The Plurk API also includes utility methods to retrieve the friends and fans of a particular user, via the get_friends() and get_fans() methods. Both these methods accept a numeric user identifier, and return a list of the selected user’s friends and fans.

The following example demonstrates:

Here’s what the output looks like:

Home Improvement

As these examples demonstrates, the Plurk PHP library provides a convenient wrapper around common Plurk API methods. However, it’s not perfect, and there are a few drawbacks you might come across when using it:

  • In case a particular API method is unsuccessful, it logs the error text with error_log() but doesn’t raise an exception. A developer must therefore manually check the API response to discover if an error occurred.
  • A number of Plurk API methods are available without authentication (plurk search is one example). However, the PHP library defines content for key class members, such as the API key, only after a successful login. Therefore, attempts to use methods such as search_plurk() will fail, as these methods are unable to find the API key within the class properties.

It’s possible to fix these issues quite easily by extending the base class and overriding its methods. Here’s a quick illustration:

This script extends the base plurk_api() class and overrides the main plurk() method to throw an exception in case the server returns an error code. This makes it possible to wrap Plurk API calls in regular try-catch blocks and define consistent error handling throughout an application. The new child class also adds a standalone setter method for the Plurk API key, allowing methods that don’t require authentication to work without requiring a username and password.

The differences can be clearly seen in this next implementation, which recreates the very first example in this tutorial using the new class:

Of course, there’s a lot more to the Plurk API than just plurking, following and searching. This article has just covered the tip of the iceberg: you can also use the API to register new accounts; create, join and delete cliques; add or remove fans and friends; respond to plurks; and block or unblock users. For more information, take a look at the Plurk API documentatio and try it out for yourself. Happy coding!

Copyright Melonfire, 2011. All rights reserved.