Cloudworks API demo


/ Published in: PHP
Save to your folder(s)

Following our recent work on an [API for Cloudworks](http://freear.org.uk/node/40) I thought I\'d post this simple demo, which uses cURL and json_decode. [Email us](mailto:cloudworks AT open.ac.uk?subject=API) for an API key. (15-24 June 2010.)


Copy this code and paste it in your HTML
  1. <?php
  2. /** A simple demonstration of the Cloudworks API, using cURL.
  3.  * @copyright 2010 The Open University.
  4.  */
  5. # Uncomment the following line to set a proxy for cURL.
  6. //putenv("http_proxy=MY_HOST:PORT");
  7.  
  8. # Please request your API key via [cloudworks AT open.ac.uk]
  9. $api_key = 'NNNNN'; //// MODIFY placeholder.
  10.  
  11. # Specify the item that you want.
  12. $item_type= 'clouds'; # Or 'cloudscapes' etc.
  13. $term = '2978'; # A cloud ID.
  14. $related = null; # null: just view the cloud; or 'followers' etc.
  15.  
  16. # Form the request URL.
  17. if ($related) $related = "/$related";
  18. $url = "http://cloudworks.ac.uk/api/$item_type/$term$related.json?api_key=$api_key";
  19.  
  20. ?><!DOCTYPE html><html lang="en"><meta charset="utf-8"><title>Cloudworks API Demo</title><?php #HTML5.
  21.  
  22. # Make the HTTP request.
  23. echo "GET $url<br>";
  24. $result= http_request_curl($url);
  25.  
  26. $item = json_decode($result->data);
  27.  
  28. if ($result->success) {
  29. # Success: display some data relevant to your request.
  30. echo "OK: <a href='$item->html_url'>$item->title</a>";
  31. } else {
  32. # Handle HTTP errors.
  33. echo ($item) ? "Error: $item->code, $item->message" : "Error: ".$result->info['http_code'];
  34. }
  35. ?></html><?php
  36.  
  37. /** Make a HTTP request using cURL.
  38.  */
  39. function http_request_curl($url) {
  40. if (!function_exists('curl_init')) die('Error, cURL is required.');
  41. if (!function_exists('json_decode'))die('Error, json_decode is required.');
  42.  
  43. $h_curl = curl_init($url);
  44. curl_setopt($h_curl, CURLOPT_USERAGENT,'My-Client/0.1 (PHP/cURL)'); //// MODIFY.
  45. curl_setopt($h_curl, CURLOPT_REFERER, 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
  46. curl_setopt($h_curl, CURLOPT_RETURNTRANSFER, TRUE);
  47. $result = (object) array('data' => curl_exec($h_curl));
  48. if ($errno = curl_errno($h_curl)) {
  49. die("Error: cURL $errno, ".curl_error($h_curl)." GET $url");
  50. }
  51. $result->info = curl_getinfo($h_curl);
  52. $result->success = ($result->info['http_code'] < 300);
  53. return $result;
  54. }

URL: http://cloudworks.ac.uk

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.