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->_getObjectECJSON::encode
d($
_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.',
$_GET['model'], $_GET['id']) CJSON::encode($model));
else
// prepare the error $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()
{
...
// 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();
}
```
### Getting the Status Codes[...]