New Yii REST Tutorial

Solved! my call is wrong, correction is:


data: 'prova='+$("#product").val(),

Tnx at all!! bye ;)

you can check you server .htaccess file, may there is configuration problem.

i used this tutorial, and really rocked !! thanks man !! :rolleyes:

Great tutorial. However, one huge problem for me. API inserts only null values. I believe I isolated the problem to the foreach() in the actionCreate() method (the only one I use).





        foreach ($_POST as $var => $value) {

            // Does the model have this attribute? If not raise an error

            if ($model->hasAttribute($var)) {

                $model->$var = $value;

            } else

                $this->_sendResponse(500,

                    sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var,

                        $_GET['model']));

        }

I know the JSON-encoded data is sent because I tested on a static web service. But, as this is my first attempt to use Yii, I have no idea how to debug this issue. I get no errors and I get an inserted record like this output in the callback:





{

   "user_id":"28",

   "last_visit":null,

   "first_visit":null,

   "locale":null,

   "this_visit":null,

   "latitude":null,

   "longitude":null,

   "device_maker":null,

   "device_model":null,

   "os_platform":null,

   "os_version":null,

   "opted_out":null,

   "opted_in":null,

   "modified":null,

   "model_type":null

}

How do I begin to debug this issue? Where can I set breakpoints so that I can inspect the $_POST global? Your attention and help is greatly appreciated.

hi all

thank you for this post

but what about comment

if i want to view post with its comment

how it should by

thank you very match

You have to be logged in to your application in order to make this work.

I followed this tutorial and it has worked quite well so far. I’m running into problems doing unit testing though. Lots of the methods make a call to


Yii::app()->end();

, which stops a unit test in its tracks.

Is there something I’m not doing right, or is it not possible to properly unit test when this call is done in the REST API methods?

if we create a new API Controller so I need to add the pattern in the URL Manager too something like this:


Controllers\ApiController.php

Controllers\NewApiController.php

in the URL Manager :




// REST patterns

array('api/list', 'pattern'=>'api/<model:\w+>', 'verb'=>'GET'),

array('api/view', 'pattern'=>'api/<model:\w+>/<id:\d+>', 'verb'=>'GET'),

//for new api controller

array('newapi/list', 'pattern'=>'newapi/<model:\w+>', 'verb'=>'GET'),

array('newapi/create', 'pattern'=>'newapi/<model:\w+>', 'verb'=>'POST'),



is that the right way here?

Sorry for my English.

Thank you for your Tutorial, i tried it and it was successfull.

Can you point me a right way how to create and read url for more complex queries, for example:

model ClientPayments

model Clients

what url will be for clientpayment by client with id and for certain date?

[solved] - going to learn regex

Hello everybody,

Trying to run this example I didn’t found the way to get success with it. I added the restclient addon on firefox and setted the parameters

Method: GET

URL: localhost/yiirest/index.php/api/posts

Headers (in menu Headers/Custom header)

X_ASCCPE_USERNAME: demo

X_ASCCPE_PASSWORD: demo

X_USERNAME: demo

X_PASSWORD: demo

Content-Type: application/x-www-form-urlencoded

Content-Type: application/json

private function _checkAuth()


{


    // Check if we have the USERNAME and PASSWORD HTTP headers set?


 


    if(&#33;(isset(&#036;_SERVER['HTTP_X_'.self::APPLICATION_ID.'_USERNAME']))) {


        // Error: Unauthorized


        echo &quot;not is set&quot;;


		exit;


		&#036;this-&gt;_sendResponse(401);


		


    }


	else


	{


		echo &quot;is set&quot;;


		exit;


	}

}

I tried a lot in many ways please help me.

But I am getting this response:

Status Code: 401 Unauthorized

Connection: Keep-Alive

Content-Length: 27

Content-Type: text/html

Date: Fri, 08 Jun 2012 01:10:22 GMT

Keep-Alive: timeout=5, max=100

Server: Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1

X-Powered-By: PHP/5.3.8

Just trying to figure out how works Rest API, any help it’s welcome.

Great tutorial have almost everything working. Like others I have som eproblems with the authentication, specifically I somehow am unable to set the user/pass headers. Any help/pointers would be much apreciated.

Here is what I have tried (based on what I’ve read in here!)

I have the following code:


Const APPLICATION_ID = 'AA';




protected function checkAuth() {

        // Check if we have the USERNAME and PASSWORD HTTP headers set?

        if(isset($_SERVER['HTTP_X_'.self::APPLICATION_ID.'_USERNAME'])){

            echo $_SERVER['HTTP_X_'.self::APPLICATION_ID.'_USERNAME'];

        } else {

         	echo 'Damn HTTP_X_' . self::APPLICATION_ID . '_USERNAME is not set';

        }

        if(!(isset($_SERVER['HTTP_X_'.self::APPLICATION_ID.'_USERNAME']) and isset($_SERVER['HTTP_X_'.self::APPLICATION_ID.'PASSWORD']))) {

            // Error: Unauthorized

            $this->sendResponse(401);

        }

        $username = $_SERVER['HTTP_X_'.self::APPLICATION_ID.'_USERNAME'];

        $password = $_SERVER['HTTP_X_'.self::APPLICATION_ID.'PASSWORD'];


        if($username != '' && $password != ''){

            return true;

            echo 'username and password not empty';

        } else {

            echo 'username and password empty';

            return false;

        }

        // Find the user (Removed until the above works)

    }

I have tried using Firefox with RESTClient set up with:

Header Name Header Value

HTTP_X_AA_PASSWORD demo

HTTP_X_AA_USERNAME demo

5953

RESTClientHeaders.PNG

with the following result:

Damn HTTP_X_AA_USERNAME is not set{"httpCode":401,"message":"Unauthorized"}

And "Advanced Rest Client" in Chrome set up the same way

Header: HTTP_X_AA_PASSWORD: demo

HTTP_X_AA_USERNAME: demo

5952

Chrome ARC Headers.PNG

Result:

Damn HTTP_X_AA_USERNAME is not set{"httpCode":401,"message":"Unauthorized"}

So what am I missing in regards to setting the Header fileds??

Found the answer by accident! Headers were set correctly, just not read.

Turns out that when you run PHP as an Apache module (rather than as CGI) on windows, you won’t get all headers with $_SERVER. So in this case the desired Headers can be retrieved with apache_request_headers() .

solution ?

Hello guys,

Please help me out?

I have used the below link to create a REST API to connect with all models we have in present working site.

The code is working fine for POST model but when i am creating cases for other models like ‘User’ and ‘Comment’. So it throwing an error :-

<h1>Error</h1>Couldn’t create model <b>comments</b><ul><li>Attribute test: url</li><ul><li>Website is not a valid URL.</li></ul></ul>

One more question, did this API code work on mobile ?

Any help is greatly appreciated!

Thanks

Ranjita

Hello Sir,

I am using your tutorial, please guide me, why it is giving me error if i used this for others models.

-> I am running this appliation on Advanced Rest Client on crome.

-> this work grt for only post model.

-> not working for other models

-> I am adding the cases for other models in every function of API like

public function actionList()

{


    &#036;this-&gt;_checkAuth();


    switch(&#036;_GET['model'])


    {


        case 'posts': // {{{ 


            &#036;models = Post::model()-&gt;findAll();


            break; // }}} 


        case 'comments': // {{{ 


            &#036;models = Comment::model()-&gt;findAll();


            break; // }}}   


        case 'users': // {{{ 


            &#036;models = User::model()-&gt;findAll();


            break; // }}}     


        default: // {{{ 


            &#036;this-&gt;_sendResponse(501, sprintf('Error: Mode &lt;b&gt;list&lt;/b&gt; is not implemented for model &lt;b&gt;%s&lt;/b&gt;',&#036;_GET['model']) );


            exit; // }}} 


    }


    if(is_null(&#036;models)) {


        &#036;this-&gt;_sendResponse(200, sprintf('No items where found for model &lt;b&gt;%s&lt;/b&gt;', &#036;_GET['model']) );


    } else {


        &#036;rows = array();


        foreach(&#036;models as &#036;model)


            &#036;rows[] = &#036;model-&gt;attributes;





        &#036;this-&gt;_sendResponse(200, CJSON::encode(&#036;rows));


    }


}

Error Showing:-

500 Internal Server Error

<h1>Error</h1>Couldn’t create model <b>comments</b><ul><li>Attribute test: url</li><ul><li>Website is not a valid URL.</li></ul></ul>

Please help me, as you know better than me.

Thanks

Ranjita

I’m trying to find a way to create a CRUD app in Yii as a REST client.

Like using a "RestDataProvider" in index view;

create and update actions calling a REST url;

I can’t find a way of developing an interface in Yii to an external REST API.

May someone help me?

I’m Using this REST API