Sunday, March 15

Particularily Happy Place - REST apis part 2

Okay, if you want to start querying, you'll need a server to run your PHP code. I recommend giving XAMPP a look - you'll get Apache, MySQL and PHP support all ready to go out of the box (okay, almost - I think all I had to do was initialise openssl in apache/bin/ini.php - google it) for free!

Ready to go? I'm a big fan of PHP for it's pretty open typing - I hate having to declare everything, I find this language makes it relatively easy to juggle resources without actively having to keep track of everything and worrying about type conversions etc. Let's just jump in.

The first thing to do is define your source. Most apis will have a token system to stop malicious users abusing the system, so I'm going to add that string in here too. Something like this:

<?php
$call = "http://example.com/api/weather?token=v5onv689g35";

creates a variable called "$call" and inserts your resource address as the value. Note the dollar sign denotes a variable. You'll then want to insert some other query strings:

$call = $call."&country=uk";
$call = $call."&city=london";

Note we could have lumped all three of these together in one declaration, but we'll want to come back later to change these, as it'd be useful to actually change their values. I'll come back to this.

$xml = simplexml_load_file($call);

Keeping this really simple, in one line we've: contacted the server ( here, at example.com), retrived the response and loaded it into a simplexml object called "$xml". If you look back to the last post, we had a response which contained one level of hierarchy - so we need to drill inside the "response" tag to get to the tags we want e.g. "temp"...

We can do this easily using a foreach statement, which looks at each child of the $xml variable (calling it $xmlchild). We then call the name of the tag $xmlname - and the print $xmlname and $xmlchild, with a hyphen between them, and a break at the end.

foreach($xml->children() as $xmlchild)
{
$xmlname = $xmlchild->getName();
echo $xmlname."-".$xmlchild."<br />";
}
?>

Once the server executes this PHP page, it would output the following to the browser:

temp-12.7
windspd-34.6
winddir-170
humid-54

Of course, you'd also want to build in controls to alter the query, do calculations with the data, display it in a meaningful way etc. but this is the basic technique I've been using - use PHP to send a request to a third party server, process and parse the response on a local sever, and serve the results back to the browser.

No comments:

Post a Comment