Now you can view the article I wrote titling “Introduction to PHP Data Services“. There I explain how you can design and implement Data Services in PHP using WSF/PHP Data Services Library.

This article covers,

  1. Designing your Data Service API.
  2. Writing the Data Service.
  3. Deploying and Testing Data Service.
  4. Make the Data Service available in both SOAP and RESTful form.
  5. Use of WS-* features in your Data Service.

If you are thinking of adapting SOA in to your database backed PHP applications, this article will be a good starting point.

PHP is one of the famous choice, when it comes to develop a web site. As the web evolve with the emerge of web service, REST (REpresentational State Transfer) concepts, the PHP language is also adapted to the new requirements specially with the availability of new SOA (Service Oriented Architecture), REST frameworks and libraries. Anyway there were hardly any guides, references or samples that properly describe the methodologies of developing REST applications using PHP.

The book “RESTful PHP Web Services‘ by Samisa Abeysinghe certainly fill this gap. It can be used as a step by step guideline for newbies to learn the concepts and write simple RESTful PHP applications and Mashups. And even experienced developers would find this a great reference to keep nearby while working with RESTful Web Services in PHP. And it has lot of code samples, utility functions that developers can use it in their applications.

RESTful PHP Web Services - Samisa Abeysinghe

About the Author

Samisa Abeysinghe is a well recognized name in the web services world. He lead the development of Apache Axis2/C and WSO2 WSF/PHP, two famous open source web service frameworks for ‘C’ and PHP. In addition to his deep knowledge in the subject, his experience in involving with the community and the enterprise for years and working as a lecturer in universities, should have influenced a lot in writing this book.

The Arrangement and the Content

The arrangement of the book is done really well to make sure the reader can go through it in the right sequence. All the content is bundled just within 200 pages. So you don’t need to allocate a lot of time to go through the whole book. It is organized into 7 chapters and two appendixes which are mostly independent from each other.

The first chapter is completely devoted to explain the concepts of RESTful web services. It basically explains what is RESTful web service and why it is needed. And it briefly mentions about the currently available REST Frameworks for PHP.

The second chapter introduce some PHP codes that do REST web service requests and handles the XML responses using both DOM and SimpleXML APIs. And in the third chapter it shows more code samples specially about consuming real world web services like BBC, Yahoo and an earthquakes information service. Theses codes are written as mashups mostly combining two services to produce more meaningful information.

The forth chapter is about  designing and writing web service providers. Its counterpart, writing web service consumers is described in the chapter five. There it demonstrate a library system that operate using RESTful webservices. You can map this example to any system that you may like to develop to run with RESTful web services. The chapter five of the book is available as a free download, RESTful PHP Web Services – Chapter 5.

The forth and fifth chapters are not using any framework to write the sample codes on consuming and providing web services. But in the sixth chapter it shows the use of Zend framework to do write them. There it rewrites the same example (The RESTful library system) in MVC (Model -View – Controller) approach using the functionalities of Zend framework. (In fact the View in the service is omitted).

The seventh chapter is about debugging web services. Debugging is a much needed step in any software development cycle. So if you are a newbie, you should read this chapter before start writing any of your own code. This introduces tools and methodologies to make your debugging easy and effective.

The book contains two appendixes. They are too really useful as the chapters of the book. In the first appendix it explains another REST web service framework, WSO2 Web Services Framework for PHP (WSF/PHP). To demonstrate it uses, some selected functionalities of the example library system (that is mentioned in chapters 4, 5, 6) is re-implemented using WSF/PHP. And it shows you how you can convert this RESTful system to a SOAP system in a minute. The second appendix provides you a code of a class (RESTClient), that you can use in consuming web services very effectively.

Recommended Readers

This book assume you have some knowledge in PHP. But it doesn’t require you to know anything related to web services, REST or XML. As you read the first few chapters, you will have a good understanding on the concepts and the basic applications of REST and XML using PHP. And the later chapters will guide to get deeper knowledge in writing complex and real world applications.

If you are a professional developer, you can skip the introduction chapters and jump directly to where you need to refer. For an example, if you use this book as a reference in designing and developing RESTful web service providers, you can directly read the chapter4 – Resource Oriented Services, chapter6- Resource Oriented Clients and Services with Zend Framework and probably the chapter 7 – Debugging Web Services.

This book contains the same example system (the library system) written in three different approaches, first without using any framework support, second using the Zend Framework, third using WSF/PHP. Each of them has its own pros and cons. So if you want to determine the approach more suitable to your requirements, or thinking of migrating from one to another, this book will be an ideal resource for you.

As you may have already noticed, this book contains lot of code samples. All the concepts are followed by simple code samples that explain the concept. In appendix it gives you a complete code for RESTClient class that you can use to call any REST service. Apart from the code of the example library system written using different frameworks, it has lot of codes for calling public web service APIs. And the explanation of the code is also done really well.

So it is clear this book is more targetting readers who like to implement PHP RESTful Systems in practice. And it covers enough concepts that you needed to know in writing practicle applications. So this book can take you from the zero knowlege to a deeper knowlege of RESTful PHP Web Services.

November 16th, 2008RESTful URL Mapping in WSF/PHP

In a RESTful design, choose of URLs for resources are really important. The URL uniquely represents a resource. Service consumers can change some parts in the URL to access different other resources. So it is clear that the URL consists of some constant parts which describe the resource group or catalog in general and some variable parts which have different and unique values for different resources.

As an example look at the following URL patterns

  • students/{name} – The constant ’students’ represent the students group in general and the variable ‘name’ is used to identify each student individually.
  • students/{name}/marks/{subject} – The constants ’students’ and ‘marks’ shows that this resource is a marks of some students, The two variables ‘name’ and ’subjects’ addresses which student and marks of which subject is presented in the URL.

You can have a look at some of the uses of such mappings from RESTful School demo.

WSF/PHP allows you to create RESTful Web Services and further more RESTful Data Services in PHP.

In a RESTful Data Service you expose a database query as a web service. There you can write a prepared statement and feed arguments for the statement through the variable parameters of the URL. For an example take the RESTfulSchool Demo Code.

To retrieve a particular student, we can use the following prepared statement and the URL pattern ( This URL Pattern+  HTTP ‘GET’ method is matched to execute this query. )

$sql = "SELECT * FROM Students where StudentName = ?"

$get_students_with_name_url = array("HTTPMethod" => "GET",
                 "RESTLocation" => "students/{name}");

So you can execute this prepared statement with the subject name ‘John’ using the following URL.

http://labs.wso2.org/wsf/php/solutions/RESTFulSchool/school_service.php/students/john

If your service is not exposing the database directly, then you have to choose the general web service API rather than the data service specific API. In there you will be able to write your business logic for publishing student information in a PHP function and expose it as a web service.

In such a cas,e your function is taking an argument which of type WSMessage. This structure hold an XML that contains values for all the variable parameters as in the users request URL. For an example for above REST Mapping, we can expect the following XML.

<getSubject>
    <name>Chemistry</name>
</getSubject>

And your function to expose as a service, would be look like this,

function getSubject($input) {
    /* retrieve the subject name from the
       $input xml using simple xml */

    $input_xml = new SimpleXMLElement($input->str);

    $subject_name = $input->name;

    /* write the logic to retrieve subject information
      for the $subject_name */

    ....
}

Samisa Abeysinghe who is the director of engineering at WSO2 and one of the key leaders of the WSF/PHP project has published a book titled RESTful PHP Web Services.

RESTful PHP Web Services - Samisa Abeysinghe

RESTful PHP Web Services - Samisa Abeysinghe

In Samisa’s Blog He describes the structure and the content of the book in his own words.

If you are developing RESTful web services in PHP, you will find this book will be a great reference.

October 18th, 2008Write RESTful Services in C

You can write REST as well as SOAP web services using Apache Axis2/C web services framework. There you can make existing Axis2/C web services RESTful just by providing the URL patterns and the HTTP methods to each operation in  the services.xml which act as a simple descriptor for an Axis2/C service.

So if we rewrite the RESTful Demo (Written in PHP) using Axis2/C, the services.xml would be something like following.

<service name="RESTfulSchool">
    <!-- mentioning the service library-->
    <parameter name="ServiceClass" locked="xsd:false">RESTfulSchool</parameter>

    <!-- some description -->
    <description>
        The RESTful School demo
    </description>

    <!-- list of operations -->
    <operation name="getSubjects">
            <parameter name="RESTMethod">GET</parameter>
            <parameter name="RESTLocation">subjects</parameter>
    </operation>
    <operation name="getSubjectInfoPerName">
            <parameter name="RESTMethod">GET</parameter>
            <parameter name="RESTLocation">subjects/{name}</parameter>
    </operation>
    <operation name="getStudents">
            <parameter name="RESTMethod">GET</parameter>
            <parameter name="RESTLocation">students</parameter>
    </operation>
    <operation name="getStudentInfoPerName">
            <parameter name="RESTMethod">GET</parameter>
            <parameter name="RESTLocation">students/{name}</parameter>
    </operation>
    <operation name="getMarksPerSubjectPerStudent">
            <parameter name="RESTMethod">GET</parameter>
            <parameter name="RESTLocation">students/{student}/marks/{subject}</parameter>
    </operation>
</service>

We will check how to write the service logic for a operation like “getMarksPerSubjectPerStudent”.

axiom_node_t *
RESTfulSchool_getMarksPerSubjectPerStudent(
    const axutil_env_t * env,
    axiom_node_t * request_payload)
{
    axiom_node_t *student_node = NULL;
    axiom_node_t *subject_node = NULL;

    /* Extracting out the child nodes from the request */
    student_node = axiom_node_get_first_child(request_payload, env);
    subject_node = axiom_node_get_next_sibling(student_node, env);

    /* now we can write the logic to retrieve the marks
       for the given student and subject and build and
       return the response payload */

    return response_payload;
}

As you can see the variables {student} and {subject} given in the services.xml can be easily accessed from your business logic, so we can build the response accordingly.

This way you can build a RESTful web services easily using C language.

WSF/PHP enables you to write both REST and SOAP services in PHP from a single script. I have written about how you can expose your Database as a REST and SOAP services in few of my previous posts using the Data Service capability of WSF/PHP. But there can be situations where your service is not based on a Database. For an example it can use results of some calculations, or a mashup calling other services. In that case you will prefer to write the service logic yourself. Here is how you can do it.

Lets think we have weather forecast data (may be from another service) and I want to make a web service using it and make it accessible via both REST and SOAP protocols.

In our demo service we give forecasts of temperature, humidity and some other parameters for a given date. So I expect

SOAP request payload as following.

<weatherReport>
  <date>{date}</date>
  <parameter>{parameter}</parameter>
</weatherReport>

And REST Request will be like

weatherReport/{date}/forecast/{parameter}

Note that here parameter can hold values like temperature, humidity or sunset-time.

First we declare our operation and the REST Request Mapping like this,

$operations = array("weatherReport" => "weather_report");
$restmap = array("weatherReport" =>
				array("HTTPMethod" =>"GET",
				      "RESTLocation" => "weatherReport/{date}/forecast/{parameter}"));

When you declare your rest mapping like above , in the service operation you will have the same request XML for both SOAP and REST form like this,

<weatherReport>
  <date>{date}</date>
  <parameter>{parameter}</parameter>
</weatherReport>

So in your service logic you just handling the request in only above format. You can easily extract out the request parameters using SimpleXML functions and return the corresponding result. So you service operation would be something like this,

function weather_report($in_message) {

	// create the simple xml element for the request xml
	$request_xml = new SimpleXMLElement($in_message->str);

	// extract out the parameter and the date
	$date = $request_xml->date;
	$parameter = $request_xml->parameter;

	// It is up to you to retrun the weather data ($result) for the requested date and parameter

	return "<response>$result</response>";
}

Finally you create the WSService object with the “operations” and “RESTMapping” and call its reply method which actually response to the requests.

$service = new WSService(array("operations" => $operations, "RESTMapping" => $restmap));
$service->reply();

You just created a web service which will handle both SOAP and REST requests.

The REST API for Twitter is very simple to learn and implement. And it has a comprehensive documentation.

Here is some selected operations to just to show its design. Note that here userid should be replaced with a valid twitter user id or user name and the format should be changed to the required output format (.xml, json, rss, atom are possible output formats)

Operation HTTP Verb URL Example HTTP Request (Setting username as ‘dimuthu’ and the output format as .xml)
Get public (all users) statuses GET http://twitter.com/statuses/public_timeline GET http://twitter.com/statuses/public_timeline
Get a user statuses GET http://twitter.com/statuses/user_timeline/userid.format GET http://twitter.com/statuses/user_timeline/dimuthu.xml
Get a particular status GET http://twitter.com/statuses/show/statusid.format GET http://twitter.com/statuses/show/938135815.xml
Create a new status POST http://twitter.com/statuses/update.format POST http://twitter.com/statuses/update.xml
Authorization: Basic xxxx
………..
<status>my status message</status>
Delete a particular status DELETE/ POST http://twitter.com/statuses/destroy/statusid.xml DELETE http://twitter.com/statuses/destroy/939390294.xml
Authorization: Basic xxxx
………..

After having look at this API, the first question I had was whether this API is actually RESTful. In RESTful design we expect to map a resource to a URL and do CRUD (Create, Read, Update and Delete) operations using request with different Http Verbs (POST, GET, PUT, DELETE) with that same URL. Look at my blog on RESTful CRUD Data Services Demo for more clarification.

So if ever the API is designed following the above theory it would have been like this.

Operation HTTP Request
Get all statuses GET http://twitter.com/statuses.xml
Get a particular user statuses GET http://twitter.com/users/{user_id}/statuses.xml
Get a particular statuses of a user GET http://twitter.com/users/{user_id}/statuses/{status_id}.xml
Crete a particular statuses of a user POST http://twitter.com/users/{user_id}/statuses.xml
Update a particular statuses of a user PUT http://twitter.com/users/{user_id}/statuses/{status_id}.xml
Delete a particular statuses of a user DELETE http://twitter.com/users/{user_id}/statuses/{status_id}.xml

So I think although Twitter API is really nice and easy, it is not really a RESTful API. If it was really RESTful, URLs might have been more organized so more easier to remember or predict. But still this API allows thousands of third party application to talk to the twitter, demonstrating the value of  providing web services over just providing some web pages in a website.

September 27th, 2008RESTful CRUD Data Services Demo

When you are developing Web Service for CRUD (Create, Read, Update, Delete) operations you may find it is easy to implement it as RESTful service. In this Demo on RESTful CRUD Service You can have an idea how you develop such a service with WSO2 WSF/PHP.

Here we take a scenario of submitting applications (say for a school).

In RESTful world we map a resource to a unique URL. In this demo, application is a resource. We use the URL “application/{id}” to represent a particular application with the id {id}.

You can  use  HTTP verb + Resource URL touples to manipulate the resource with CRUD operations.  Here is how it is done in this particular demonstration.

Request format (HTTP Verb + URL) Operation Semantic
POST applications/{id} Create an application
GET applications/{id} Get an application
PUT applications/{id} Change an application
DELETE applications/{id} Delete an application

Go for the wsf/php demo sitefor the live demo of this service. Visit the demo service source code to see how easy to implement it with WSF/PHP Data Services library.

I wrote a similar blog on Data Services last week to demonstrate how you design the mapping of url to different resources in a RESTful Service.

In RESTful paradigm we give a piece of data ( or in other word ‘Resource’) a unique URL. And in order to manipulate data we use HTTP verbs POST/PUT (create, update), GET (read), DELETE (delete). For an example
take the scenario of manipulating Students data in a high school. Here is how each operation is mapped to a http request (URL + HTTP verb)

HTTP request Operation
POST api/students/ben Create the resource (peice of data) called ben as a student. HTTP body or the url itself (e.g. api/students/ben?age=15&country=xx) may contain the required information about ben
GET api/students/ben Retrieve the information about ben.
PUT api/students/ben Update ben
DELETE api/student/ben Delete the student called ‘ben’.

With the addition of all these HTTP verbs WSO2 WSF/PHP 2.0.0 become a great tool for RESTful developers. Specially with the introducing Data Services library it was so easy to make your database a REST service. I m thinking of preparing a series of application to demonstrate the power of WSF/PHP with all these new features.

This demo -RESTful School- shows how you map a URL to a peice of data. Here we use only the http “GET” method (which is the most to used in practicle data service).

Here is some description of the operations you find in there. Just check the source code for RESTful School demo to see how this is done in code level.

Operation URL SQL Query Note
Get All subjects
subjects
SELECT subjectName, subjectTeacher FROM Subjects
With no parameters
Get subject information From Name
subjects/{name}
SELECT subjectName, subjectTeacher FROM Subjects where SubjectName = ?
The single parameter feed from prepared statement syntax
Get All students
students
SELECT * FROM Students
Again no parameters
Get students From Name
students/{name}
Inner Query:

SELECT subjectName, marks FROM Marks m, Subjects s ".
        " where m.studentId = ? and m.subjectID = s.subjectId

Outer Query

SELECT * FROM Students where StudentName = ?
Nested query, Inner query is called from outer query
Get Marks per Students per Subjects
students/{student}/marks/{subject}
SELECT marks FROM Marks, Subjects, Students where StudentName = ?".
        " and SubjectName = ? and Marks.subjectId = Subjects.subjectId".
        " and Marks.studentID = Students.StudentId;
Two parameters, and ‘?’ in the sql query..

September 12th, 2008WSO2 WSF/PHP 2.0.0 Just Released!

We have been waiting for a while to do the WSF/PHP 2.0.0 release with a bundle of new features. We took time to test all the features and to make sure they are working smoothly. And it is heavily tested for the interoperability specially with .NET for WS-Security and WS-Reliable Messaging scenarios. And the newly added Data Services library will be a great tool for the PHP community to bring their LAMP/WAMP applications to the SOA platform. WSF/PHP 2.0.0 is not just a SOAP library. It is ready for the RESTful applications as well with the improved support for HTTP verbs.

Here is the list of new features introduced in this release

  • Added PKCS12 Keystore Support
  • Added Secure Conversation Support
  • Added Replay Detection Support
  • Contract First Web Services support for MTOM
  • SWA ( Soap With Attachments ) Support added
  • MTOM Attachment caching support added
  • HTTP Chunking support added
  • REST API Improved to support HTTP verbs GET,DELETE,PUT and POST
  • New PHP Data Services Solution
  • WS-RM 1.1 added

Have look at the WSF/PHP 2.0.0 Official Release Note for the complete feature list


© 2007 Dimuthu’s Blog | iKon Wordpress Theme by Windows Vista Administration | Powered by Wordpress