Using the REST API with PHP¶
Here is an example that uses PHP ActiveResource, a lightweight PHP library that can be used to access Rails' REST APIs:
1<?php 2require_once ('ActiveResource.php'); 3 4class Issue extends ActiveResource { 5 var $site = 'http://username:password@192.168.199.129:3000/'; 6 var $request_format = 'xml'; // REQUIRED! 7} 8 9// create a new issue 10$issue = new Issue (array ('subject' => 'XML REST API', 'project_id' => '1')); 11$issue->save (); 12echo $issue->id; 13 14// find issues 15$issues = $issue->find ('all'); 16for ($i=0; $i < count($issues); $i++) { 17 echo $issues[$i]->subject; 18} 19 20// find and update an issue 21$issue->find (1); 22echo $issue->subject; 23$issue->set ('subject', 'This is the new subject')->save (); 24 25// delete an issue 26$issue->find (1); 27$issue->destroy (); 28?>
Known issues
- If you are working with large descriptions, the webserver can return a 417 error (Bad Expectation).
You should replace line 381 in ActiveResource.php with the following code:1curl_setopt ($ch, CURLOPT_HTTPHEADER, array ('Expect:',"Content-Type: text/xml", "Length: " . strlen ($params))); - If you are trying to use the class to write
time_entries, you will get a 404 response (#9375). The reason for that is that the class is unable to create the correct singular form from the pluralized version of the entity name. (edit 2011-10-06: according to the website the bug was fixed in the latest release: https://github.com/lux/phpactiveresource/issues/7#issuecomment-2300502)
This can be patched in ActiveResource.php by: - adding the class variable
$sOriginalElementName:1protected $sOriginalElementName = ''; - changing the constructor to set the class variable using the original entity name before the pluralization is called:
1function __construct ($data = array ()) { 2 $this->_data = $data; 3 4 // add this line here - to store the original name of the entity 5 $this->sOriginalElementName = ($this->element_name ? $this->element_name : strtolower (get_class ($this))); 6 // Allow class-defined element name or use class name if not defined 7 $this->element_name = ($this->element_name ? $this->pleuralize ($this->element_name) : $this->pleuralize (strtolower (get_class ($this)))); 8... - and then changing the method
_send_and_receiveto use$sOriginalElementNameinstead ofsubstr ($this->element_name, 0, -1):1function _send_and_receive ($url, $method, $data = array ()) { 2 $params = ''; 3 $el = $this->sOriginalElementName;//substr ($this->element_name, 0, -1); 4 if ($this->request_format == 'url') { 5...