Use yii to develop RESTAPI

Source: Internet
Author: User
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
  1. Configuration file
  2. ApiModule
  3. RestController
  4. Post Controller)
  5. 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/].

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.