Use yii to develop RESTAPI
Recently, I have a project for Android client development. because I need to communicate with the server, I decided to use RESTFUL APIs after reading some documents.
Here I will share with the blog program that comes with the yii Framework how to use yii to develop REST APIs.
REST API URI
| Access method |
URL |
Description |
Corresponding controller and action |
| GET |
/Api/post |
Blog list |
Api/post/index |
| GET |
/Api/post/12 |
Blog page |
Api/post/iew |
| POST |
/Api/post |
Add blog |
Api/post/create |
| PUT |
/Api/post/12 |
Modify blog |
Api/post/update |
| DELETE |
/Api/post/12 |
Delete blog |
Api/post/delete |
Architecture Analysis
- API as a module of the application
- All API controllers use the same base class RestController
- Because REST is stateless, HTTP Header is used for logon verification.
Implementation code
- Configuration file
- ApiModule
- RestController
- Post Controller)
- Test
Configuration file
... 'modules' => array( 'api' , ),...
ApiModule
The code is as follows:
SetImport (array ('api. models. * ', 'api. components. * ',); // when an error message is returned, Yii: app () is returned () -> setComponents (array ('errorhandler' => array ('erroraction' => 'api/default/error',);} public function beforeControllerAction ($ controller, $ action) {if (parent: beforeControllerAction ($ controller, $ action) {return true;} else return false ;}}
Note: In the preceding errorAction, the api/default/error must be the same as that defined in protected/config/main. php. Otherwise, the module cannot be found.
RestController
RestController is a base class. The directory is/protected/modules/api/components/. the code is as follows:
$ ErrorCode, 'errormessage' => $ errorMessage = null? RestError: getErrorMessage ($ errorCode): $ errorMessage, 'data' => $ data); echo CJSON: encode ($ response); Yii: app () -> end ();}/*** send error message * @ param integer $ errorCode error code * @ param string $ errorMessage error message, if it is null, information is automatically obtained based on the error code */public function sendError ($ errorCode, $ errorMessage) {header ("Content-type: application/json ;"); $ response = array ('errorcode' => $ errorCode, 'errormessage' => $ errorM Essage = null? RestError: getErrorMessage ($ errorCode): $ errorMessage,); echo CJSON: encode ($ response); Yii: app ()-> end ();} /*** action filter: only users who pass verification are allowed to access * @ param CFilterChain $ filterChain * @ throws CHttpException */public function filterAuthOnly ($ filterChain) {if ($ this-> validateAuth () $ filterChain-> run (); else throw new CHttpException (401, Yii: t ('yii ', 'Your authorization is invalid. ');}/*** action filter, only users with PUT requests can access * @ param CFilterChain $ filterChain * @ throws CHttpException */public function filterPutOnly ($ filterChain) {if (Yii: app () -> getRequest ()-> getIsPutRequest () $ filterChain-> run (); else throw new CHttpException (400, Yii: t ('yii ', 'Your request is invalid. ');}/*** verify the user information, based on HTTP Base verification * @ return boolean */protected function validateAuth () {$ http_authorization = $ _ SERVER ['http _ authorization']; list ($ username, $ password) = explode (':', base64_decode (substr ($ http_authorization, (6); $ form = new LoginForm (); $ form-> username = $ username; $ form-> password = $ password; if ($ form-> validate () {$ form-> login (); return true;} else {return false ;}}}Post Controller)
Because PostController does not post a large amount of content, see the source code directly.
Test
I used Chrome's extended Postman to perform the test, but unfortunately, I cannot export the configuration I wrote above. you can perform the test according to the REST standard, if you have any questions, contact me.
Source code download
This article is original on this site. For more information, see [http://www.yiiwiki.com/38/].