Alex Pavlov
Alex Pavlov

Reputation: 581

Yii2 rest api getBodyParams() can't get params from PUT request

How can I get "token" param from PUT request?

Controller:

public function actionUpdate()
{
    $params = Yii::$app->getRequest()->getBodyParams();
    return $params;
}

Request:

curl -X PUT -H "Authorization: Bearer LL_nACyYVJFJyuHJxcOtiXu3OVNBJ_xo" -F "token=12345" "http://localhost/api/v1/devices/1"

Response:

{"success":true,"data":{"--------------------------580af3364bd175a7\r\nContent-Disposition:_form-data;_name":"\"token\"\r\n\r\n12345\r\n--------------------------580af3364bd175a7--\r\n"}}r

I have tried this:

return $params['token'];

PHP Notice: Undefined index: token

And this

parse_str(file_get_contents("php://input"), $params);

Will return the same result

Upvotes: 3

Views: 3760

Answers (2)

robsch
robsch

Reputation: 9728

You could use Yii's MultipartFormDataParser. This allows you to use Yii::$app->request->post() or Yii::$app->request->getBodyParams() on PUT or DELETE requests, as you know it from POST requests.

You just need to configure it that it gets applied:

return [
    'components' => [
        'request' => [
            'parsers' => [
                'multipart/form-data' => 'yii\web\MultipartFormDataParser'
            ],
        ],
    ],
];

That's it.

Upvotes: 0

csminb
csminb

Reputation: 2382

i think the problem is related to the content type of your request. getting body params from put/post requires Content-type: application/x-www-form-urlencoded

try using curl with -d instead of -F:

curl -X PUT -H "Authorization: Bearer LL_nACyYVJFJyuHJxcOtiXu3OVNBJ_xo" -d "token=12345" "http://localhost/api/v1/devices/1"

Upvotes: 3

Related Questions