Main Content

Using web services to access you data - JSON and RESTful services

Archive - Originally posted on "The Horse's Mouth" - 2013-03-29 18:04:07 - Graham Ellis

Rather than build database access directly into your application, you can write much more portable and maintainable code using a service / web service in which you embed the database access - or whatever else you're using for your backend data.

Web services are typically accessed through HTTP or HTTPS requests, very often using Representational State Transfer (RESTful) principles, and are commonly programmed in Java. The data is sometimes transferred in XML or even in HTML, but more commonly (and becoming more popular) in JSON (JavaScript Object Notation). I'm very much aware that I'm dropping in lots of buzzwords here and perhaps drowning my readers... so let's see an example that I've been writing today for new course material for a major client.

Here's a client (customer) program that uses our service:

  <?php
  // Go get data (report of server accesses in the last minute)
  $stuff = file_get_contents("http://www.wellho.net/services/_.json");
  
  // Turn that data back into the structure that we've been served
  $info = json_decode($stuff);
  $reportat = date("r",$info->timestamp);
  $log = "";
  foreach ($info->records as $record) {
    $ago = $info->timestamp - $record->timedat;
    $log .= "$ago seconds ago loaded $record->what<br />\n";
    }
  $nr = count($info->records);
  
  ?>
  <html>
  <head><title>Presentation Layer</title></head>
  <body><h1>What's been read in the last minute?</h1>
  Report timed at <?= $reportat ?> with <?= $nr ?> requests made<br /><br />
  <?= $log ?>
  </body>
  </html>


You can see it's REALLY easy to pick up data from a service. The source code is [here] and you can run it now via [here]. You'll get different results almost every time as this is a really fast-changing service. Here are results I got in testing:



The service layer code can be quite short too - my example is [here]. It works in stages:
a) Interpret the request (make sure a known format is asked for!)
b) Read the data in from the database into a memory structure of some sort
c) Format to the requested standard
d) Output the results

As I'll be using my server in a lot of different client demonstrations, I've allowed it to return a number of different formats:
• .html - formatted as a table [try it]
• .txt - formatted as a variable dump [try it]
• .json - formatted in JavaScript Object notation [try it] - looks a bit horrid!
• .csv - formatted as comma separated values [try it]
• .tsv - formatted as tab separated values [try it]
• .xml - formatted in Extensible Markup Language [try it] - your browser will make this look a bit ugly.

This demonstration service provider happens to be in PHP (it lets me explain the concept without having to use two different languages), but Java would be a more common choice.