Return to Snippet

Revision: 29044
at July 20, 2010 06:06 by nfreear


Initial Code
<?php
/** A simple demonstration of the Cloudworks API, using cURL.
 *  @copyright 2010 The Open University.
 */
# Uncomment the following line to set a proxy for cURL.
//putenv("http_proxy=MY_HOST:PORT");

# Please request your API key via [cloudworks AT open.ac.uk]
$api_key  = 'NNNNN';   //// MODIFY placeholder.

# Specify the item that you want.
$item_type= 'clouds';  # Or 'cloudscapes' etc.
$term     = '2978';    # A cloud ID.
$related  = null;      # null: just view the cloud; or 'followers' etc.

# Form the request URL.
if ($related) $related = "/$related";
$url = "http://cloudworks.ac.uk/api/$item_type/$term$related.json?api_key=$api_key";

?><!DOCTYPE html><html lang="en"><meta charset="utf-8"><title>Cloudworks API Demo</title><?php #HTML5.

# Make the HTTP request.
echo "GET $url<br>";
$result= http_request_curl($url);

$item  = json_decode($result->data);

if ($result->success) {
    # Success: display some data relevant to your request.
    echo "OK: <a href='$item->html_url'>$item->title</a>";
} else {
    # Handle HTTP errors.
    echo ($item) ? "Error: $item->code, $item->message" : "Error: ".$result->info['http_code'];
}
?></html><?php

/** Make a HTTP request using cURL.
 */
function http_request_curl($url) {
  if (!function_exists('curl_init'))  die('Error, cURL is required.');
  if (!function_exists('json_decode'))die('Error, json_decode is required.');

  $h_curl = curl_init($url);
  curl_setopt($h_curl, CURLOPT_USERAGENT,'My-Client/0.1 (PHP/cURL)');         //// MODIFY.
  curl_setopt($h_curl, CURLOPT_REFERER,  'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
  curl_setopt($h_curl, CURLOPT_RETURNTRANSFER, TRUE);
  $result = (object) array('data' => curl_exec($h_curl));
  if ($errno = curl_errno($h_curl)) {
    die("Error: cURL $errno, ".curl_error($h_curl)." GET $url");
  }
  $result->info = curl_getinfo($h_curl);
  $result->success = ($result->info['http_code'] < 300);
  return $result;
}

Initial URL
http://cloudworks.ac.uk

Initial Description
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.)

Initial Title
Cloudworks API demo

Initial Tags
curl

Initial Language
PHP