Search code examples
apirestcurlyii2updatemodel

How to make CURL call from CMD line (Win 7) to MVC action with parameter?


I'm building the REST-full API with CRUD actions in Yii 2.0 and I need help for update action.

In my Yii 2.0 MVC controller I have actions create and update as follow:

public function actionCreate()
{
    ...
}

For create action I can make CURL calls successfully with the command:

curl -X POST -d column_one=create_test1 -d column_two=create_test2 http://localhost/MyApp/web/tabletest/create

And after this call, the new row in my table with the above values for columns is successfully created.

Now I need to make CURL calls for update action as well:

public function actionUpdate($id)
{
    ...
}

I have tried a lot of variations for this command (now we have parameter in the function and I'm not sure how to pass it - let's assumed that $id=2). These are only a few of the ones that I tried, none is working:

curl -X PUT -d column_two=updated_cmd_2 http://localhost/MyApp/web/tabletest/update/2

curl -X PUT -d "column_two=updated_cmd_2" "http://localhost/MyApp/web/tabletest/update/2"

curl -X PUT -d "id=2&column_two=updated_cmd_2" "http://localhost/MyApp/web/tabletest/update"

But in most of the cases I got the error:

Bad Request (#400)

*NOTE: The create method is defined as POST method and update method is defined as PUT method, so the method type is not a problem in this case. I think that format of CURL call for update is not correct.


Solution

  • I solved the problem by replacing one of my custom actions in the controller:

    public function beforeAction($action) 
    {
        if($this->action->id == 'create'){
            $this->enableCsrfValidation = false;
        }
    
        return parent::beforeAction($action);
    }
    

    into:

    public function beforeAction($action) 
    {
        if($this->action->id == 'create' || $this->action->id == 'update'){
            $this->enableCsrfValidation = false;
        }
    
        return parent::beforeAction($action);
    }
    

    and now:

    curl -X PUT -d column_two=updated_cmd_2 http://localhost/MyApp/web/tabletest/update/2
    

    is working.