Difference between #12 and #19 of
How-To: Create a REST API

Changes

Title unchanged

How-To: Create a REST API

Category unchanged

How-tos

Yii version unchanged

Tags changed

REST, API, Tutorial, Backbone

Content changed

This article will explain how to create a REST API with the Yii framework. ## Information about REST A good introduction about implementing REST service with PHP can be found on [http://www.gen-x-design.com](https://web.archive.org/web/20130910164802/http://www.gen-x-design.com/archives/create-a-rest-api-with-php/).

## Usefull Tools
[...]
* **Create a new post:** _index.php/api/posts_ (_POST_)
* **Update a post:** _index.php/api/posts/123_ (_PUT_)
* **Delete a post:** _index.php/api/posts
/123_ (_DELETE_)
[...]
'Error: Mode <b>list</b> is not implemented for model <b>%s</b>',
$_GET['model']) );
exitYii::app()->end(); } // Did we get some results? if(is_nullempty($models)) {
// No
$this->_sendResponse(200,
[...]
'Mode <b>view</b> is not implemented for model <b>%s</b>',
$_GET['model']) );
exitYii::app()->end();
}
// Did we find the requested model? If not, raise an error
[...]
$this->_sendResponse(404, 'No Item found with id '.$_GET['id']);
else
$this->_sendResponse(200, CJSON::encode($
_GET['model']));
}
```
[...]
sprintf('Mode <b>create</b> is not implemented for model <b>%s</b>',
$_GET['model']) );
exitYii::app()->end();
}
// Try to assign POST values to attributes
[...]
// Try to save the model
if($model->save())
$this->_sendResponse(200,

 
                $this->_getObjectE
CJSON::encoded($_GET['model'], $model->attributes) model));
else {
// Errors occurred
[...]
public function actionUpdate()
{
// Parse the PUT parameters

 
   
. This didn't work: parse_str(file_get_contents('php://input'), $put_vars);  
    $json = file_get_contents('php://input'); //$GLOBALS['HTTP_RAW_POST_DATA'] is not preferred: http://www.php.net/manual/en/ini.core.php#ini.always-populate-raw-post-data
 
    $put_vars = CJSON::decode($json,true); //true means use associative array


switch($_GET['model'])
[...]
sprintf( 'Error: Mode <b>update</b> is not implemented for model <b>%s</b>',
$_GET['model']) );
exitYii::app()->end(); } // Did we find the requested model? If not, raise an error if(is_null($model)$model === null)
$this->_sendResponse(400,
sprintf("Error: Didn't find any model <b>%s</b> with ID <b>%s</b>.",
[...]
// Try to save the model
if($model->save())
$this->_sendResponse(200,

 
                sprintf('The model <b>%s</b> with id <b>%s</b> has been updated.',
CJSON::encode($model));
 
    else
 
        // prepare the error $msg
 
        // see actionCreate
// ...
 
$_GET['model'], $_GET['id']) );
 
    else
 
        // prepare the error $msg
 
        // see actionCreate
this->_sendResponse(500, $msg );
 
}
 
```
 
 
Please keep in mind to check your model `beforeSave` and `afterSave` methods if any code eventually uses a logged-in user's id like the blog `Post` model:
 
 
 
```php 
protected function beforeSave()
 
{
...
 
// ...
 
        $this->_sendResponse(500, $msg );
author_id may have been posted via API POST
 
    if(is_null($this->author_id) or $this->author_id=='')
 
        $this->author_id=Yii::app()->user->id;
 
    ...
} ```
 
### Delete a Model Action
[...]
sprintf('Error: Mode <b>delete</b> is not implemented for model <b>%s</b>',
$_GET['model']) );
exitYii::app()->end(); } // Was a model found? If not, raise an error if(is_null($model)$model === null)
$this->_sendResponse(400,
sprintf("Error: Didn't find any model <b>%s</b> with ID <b>%s</b>.",
[...]
$num = $model->delete();
if($num>0)
$this->_sendResponse(200,

 
                sprintf("Model <b>%s</b> with ID <b>%s</b> has been deleted.",
 
                $_GET['model'], $_GET['id']) );
$num); //this is the only way to work with backbone
else
$this->_sendResponse(500,
[...]
How are the API responses actually sent? Right, we need to implement the _sendResponse method.

This code is borrowed from [http://www.gen-x-design.com/archives/create-a-rest-api-with-php](
https://web.archive.org/web/20130910164802/http://www.gen-x-design.com/archives/create-a-rest-api-with-php/).
[...]
// send the body
echo $body;
        exit;
 
}
// we need to create the body if none is passed
else
[...]
echo $body;
}
 
exit;
 
    }
Yii::app()->end();
}
```
[...]
## Code Download

Of course you can download the code developed [here](http://www.diggin-data.de/download/yii-blog-rest.tar.gz).

 
 
 
Links
 
-----
 
- [Chinese version](http://www.itkuaixun.com/bbs/thread-217-1-1.html "Chinese version")
98 2
123 followers
Viewed: 498 902 times
Version: 1.1
Category: How-tos
Written by: jwerner
Last updated by: Rohit Suthar
Created on: Apr 15, 2011
Last updated: 9 years ago
Update Article

Revisions

View all history