Rest api with php » History » Version 1

Jean-Philippe Lang, 2010-01-17 20:53

1 1 Jean-Philippe Lang
h1. Using the REST API with PHP
2 1 Jean-Philippe Lang
3 1 Jean-Philippe Lang
Here is an example that uses "phpactiveresource":http://wiki.github.com/lux/phpactiveresource/, a lightweight PHP library that can be used to access Rails' REST APIs:
4 1 Jean-Philippe Lang
5 1 Jean-Philippe Lang
<pre>
6 1 Jean-Philippe Lang
<?php
7 1 Jean-Philippe Lang
require_once ('ActiveResource.php');
8 1 Jean-Philippe Lang
9 1 Jean-Philippe Lang
class Issue extends ActiveResource {
10 1 Jean-Philippe Lang
    var $site = 'http://username:password@192.168.199.129:3000/';
11 1 Jean-Philippe Lang
    var $request_format = 'xml'; // REQUIRED!
12 1 Jean-Philippe Lang
}
13 1 Jean-Philippe Lang
14 1 Jean-Philippe Lang
// create a new issue
15 1 Jean-Philippe Lang
$issue = new Issue (array ('subject' => 'XML REST API', 'project_id' => '1'));
16 1 Jean-Philippe Lang
$issue->save ();
17 1 Jean-Philippe Lang
18 1 Jean-Philippe Lang
// find issues
19 1 Jean-Philippe Lang
$issues = $issue->find ('all');
20 1 Jean-Philippe Lang
for ($i=0; $i < count($issues); $i++) {
21 1 Jean-Philippe Lang
	echo $issues[$i]->subject;
22 1 Jean-Philippe Lang
}
23 1 Jean-Philippe Lang
24 1 Jean-Philippe Lang
// find and update an issue
25 1 Jean-Philippe Lang
$issue->find (1);
26 1 Jean-Philippe Lang
echo $issue->subject;
27 1 Jean-Philippe Lang
$issue->set ('subject', 'This is the new subject')->save ();
28 1 Jean-Philippe Lang
29 1 Jean-Philippe Lang
// delete an issue
30 1 Jean-Philippe Lang
$issue->find (1);
31 1 Jean-Philippe Lang
$issue->destroy ();
32 1 Jean-Philippe Lang
?>
33 1 Jean-Philippe Lang
</pre>