Sunday, May 24, 2015

Simple Restful Web Services

I was trying to use PHP CURL library to access a web services. In the process I found a useful library that makes using CURL very easy. It is called Httpful (https://github.com/nategood/httpful). The library is useful if you don't mind the many duplicate functionality.

In the process of testing, I was wondering whether CURL actually posts the XML. Since I did not want to access any real time web services, I decided to use PHP to get the posting. Naturally it failed. The standard global variables $_POST[] does not contain any content neither does $_RESPONSE[]. I search the internet and discovered that the post is more like posting a file rather than posting a form. There is a PHP function to get this kind of content.

After successfully retrieving the content, I was wondering whether I can make this functionality work like a very simple restful web services. I began to write a proper PHP page to simulate the web service. The following are the scripts for posting and the restful web services page. The XML request and response are dummy values which is stored as a simple variable, It is not in the scope of this blog to show how to create XML in PHP.

The posting page :-

include "httpful.phar";
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
$url="http://localhost/sampleresponse.php";
$authenticate = "jonathan@mail.commypassword";

$response = \Httpful\Request::Post($url)
    ->body($authenticate)
    ->mime("XML")
    ->autoParse(false)
    ->expectsType("XML")
    ->send();
$xml= new SimpleXMLElement($response);
$sessionid=$xml->xpath("//userSessionId")[0];
if ($sessionid==""){
    die("Error User does not exist or password is wrong.");
}

The restful response :-

include "httpful.phar";
$postText = file_get_contents('php://input');
$xml= new SimpleXMLElement($postText);
$auth=$xml->xpath("//AuthenticateRequest")[0];
if ($auth){
$user=$xml->xpath("//userId")[0];
.
.
.
if ($verified) {
    die("
             Sdt7tXp2XytTEVwHBeDx6lHTXI3w9s+M
       
");}};

Well, it is simple straightforward PHP turned into restful web services. Obviously CURL could post user credentials itself while posting the request. This is a simple example.

Not everyone have a web server. In the case of user just want to access the restful web services via the browser, they could simply write a Javascript AJAX function to do the posting. There are plenty of examples in the internet that shows you how to do posting in AJAX. It will not show it here.

For more security, it is best to use HTTPS for the web services.



No comments:

Post a Comment