Showing posts with label Web Services. Show all posts
Showing posts with label Web Services. Show all posts

REST vs SOAP Web Services

I am seeing that a lot of new web services are implemented using RESTstyle architecture these days rather than a SOAP one. Lets step back a second and explain what REST is.What is a REST Web Service

The acronym REST stands for Representational State Transfer, this basically means that each unique URL is a representation of some object. You can get the contents of that object using an HTTP GET, to delete it, you then might use a POST, PUT, or DELETE to modify the object (in practice most of the services use a POST for this).

Who’s using REST?
All of Yahoo’s web services use REST, including Flickr, del.icio.us API uses it, pubsub, bloglines, technorati, and both eBay, and Amazon have web services for both REST and SOAP.

Who’s using SOAP?
Google seams to be consistent in implementing their web services to use SOAP, with the exception of Blogger, which uses XML-RPC. You will find SOAP web services in lots of enterprise software as well.

REST vs SOAP
As you may have noticed the companies I mentioned that are using REST api’s haven’t been around for very long, and their apis came out this year mostly. So REST is definitely the trendy way to create a web service, if creating web services could ever be trendy (lets face it you use soap to wash, and you rest when your tired).

The main advantages of REST web services are:
  • Lightweight – not a lot of extra xml markup
  • Human Readable Results
  • Easy to build – no toolkits required
SOAP also has some advantages:
  • Easy to consume – sometimes
  • Rigid – type checking, adheres to a contract
  • Development tools
For consuming web services, its sometimes a toss up between which is easier. For instance Google’s AdWords web service is really hard to consume (in CF anyways), it uses SOAP headers, and a number of other things that make it kind of difficult. On the converse, Amazon’s REST web service can sometimes be tricky to parse because it can be highly nested, and the result schema can vary quite a bit based on what you search for.

Note : Which ever architecture you choose make sure its easy for developers to access it, and well documented.

Create a Basic Web Service Using PHP

 Here's how to create a basic web service that provides an XML or JSON response using some PHP .

The PHP / MySQL

<?php
/* require the user as the parameter */
if(isset($_GET['user']) && intval($_GET['user'])) {

  /* soak in the passed variable or set our own */
  $number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
  $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
  $user_id = intval($_GET['user']); //no default

  /* connect to the db */
  $link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB');
  mysql_select_db('db_name',$link) or die('Cannot select the DB');

  /* grab the posts from the db */
  $query = "SELECT post_title, guid FROM wp_posts WHERE post_author = $user_id AND 
            post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
  $result = mysql_query($query,$link) or die('Errant query:  '.$query);

  /* create one master array of the records */
  $posts = array();
  if(mysql_num_rows($result)) {
    while($post = mysql_fetch_assoc($result)) {
      $posts[] = array('post'=>$post);
    }
  }

  /* output in necessary format */
  if($format == 'json') {
    header('Content-type: application/json');
    echo json_encode(array('posts'=>$posts));
  }
  else {
    header('Content-type: text/xml');
    echo '<posts>';
    foreach($posts as $index => $post) {
      if(is_array($post)) {
        foreach($post as $key => $value) {
          echo '<',$key,'>';
          if(is_array($value)) {
            foreach($value as $tag => $val) {
              echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
            }
          }
          echo '</',$key,'>';
        }
      }
    }
    echo '</posts>';
  }

  /* disconnect from the db */
  @mysql_close($link);
}

With the number of persons hitting your web service (hopefully), you'll need to do adequate validation before attempting to connect to the database to avoid injection attacks. Once we get the desired results from the database, we cycle through the results to populate our return results array. Depending upon the response type desired, we output the proper header and content in the desired format.
Take the following sample URL for example:

http://mydomain.com/web-service.php?user=2&num=10
Now, we can take a look at the possible results of the URL.

The XML Output

<posts>
  <post>
    <post_title>SSLmatic SSL Certificate Giveaway Winners</post_title>
    <guid>http://davidwalsh.name/?p=2304</guid>
  </post>
  <post>
    <post_title>MooTools FileManager</post_title>
    <guid>http://davidwalsh.name/?p=2288</guid>
  </post>
  <post>
    <post_title>PHPTVDB: Using PHP to Retrieve TV Show Information</post_title>
    <guid>http://davidwalsh.name/?p=2266</guid>
  </post>
  <post>
    <post_title>David Walsh: The Lost MooTools Plugins</post_title>
    <guid>http://davidwalsh.name/?p=2258</guid>
  </post>
  <post>
    <post_title>Create Short URLs Using U.Nu</post_title>
    <guid>http://davidwalsh.name/?p=2218</guid>
  </post>
  <post>
    <post_title>Create Bit.ly Short URLs Using PHP</post_title>
    <guid>http://davidwalsh.name/?p=2194</guid>
  </post>
  <post>
    <post_title>Represent Your Repositories Using the GitHub Badge!</post_title>
    <guid>http://davidwalsh.name/?p=2178</guid>
  </post>
  <post>
    <post_title>ZebraTable</post_title>
    <guid>http://davidwalsh.name/?page_id=2172</guid>
  </post>
  <post>
    <post_title>MooTools Zebra Table Plugin</post_title>
    <guid>http://davidwalsh.name/?p=2168</guid>
  </post>
  <post>
    <post_title>SSLmatic: Quality, Cheap SSL Certificates and Giveaway!</post_title>
    <guid>http://davidwalsh.name/?p=2158</guid>
  </post>
</posts>

Take this next sample URL for example:

http://mydomain.com/web-service.php?user=2&num=10&format=json
Now, we can take a look at the possible results of the URL.

The JSON Output

{"posts":[{"post":{"post_title":"SSLmatic SSL Certificate Giveaway Winners","guid" 
:"http:\/\/davidwalsh.name\/?p=2304"}},{"post":{"post_title":"MooTools FileManager" 
,"guid":"http:\/\/davidwalsh.name\/?p=2288"}},{"post":{"post_title":"PHPTVDB: Using
 PHP to Retrieve TV Show Information","guid":"http:\/\/davidwalsh.name\/?p=2266"}} 
,{"post":{"post_title":"David Walsh: The Lost MooTools Plugins","guid":"http:\/\/
davidwalsh.name\/?p=2258"}},{"post":{"post_title":"Create Short URLs Using U.Nu",
 "guid":"http:\/\/davidwalsh.name\/?p=2218"}},{"post":{"post_title":"Create Bit.ly
 Short URLs Using PHP","guid":"http:\/\/davidwalsh.name\/?p=2194"}},{"post":{ 
"post_title":"Represent Your Repositories Using the GitHub Badge!","guid":"
http:\/\/davidwalsh.name\/?p=2178"}},{"post":{"post_title":"ZebraTable","guid
":"http:\/\/davidwalsh.name\/?page_id=2172"}},{"post":{"post_title":"MooTools
 Zebra Table Plugin","guid":"http:\/\/davidwalsh.name\/?p=2168"}},{"post":{ 
"post_title":"SSLmatic: Quality, Cheap SSL Certificates and Giveaway!","guid
":"http:\/\/davidwalsh.name\/?p=2158"}}]}