Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 RESTful Webservice: JSON Request Format

this is my first question:

I'm trying to build a RESTful Webservice with Yii2. The Controller extends from ActiveController and has the corresponding model. Reading of data works fine and without problems.

But when I try to create new Objects I run into an error. I use the Chrome extension Advanced Rest Client and POST the following data:

{
    "team": 1
}

I also tried different formats.

But I always get this response:

[{
    "field":"team",
    "message":"Team cannot be blank."
}]

Do you have any suggestions what I'm doing wrong?

Thanks!

like image 533
PhilippS Avatar asked Jun 23 '14 15:06

PhilippS


2 Answers

I think you all got me on the right track. Thanks for that!

The problem was that Yii2 uses an integrated parser for parsing JSON request. I thought these parser is konfigured by default (as there is no hint to configure it in the documentation). But the parser had to be configured by myself.

Here is how to configure the parser in the main-configuration:

'request' => [
    'parsers' => [
        'application/json' => 'yii\web\JsonParser',
    ]
]

You can find more information here: JsonParser

I hope this can help others running into the same problem.

like image 169
PhilippS Avatar answered Nov 07 '22 08:11

PhilippS


I think you are capturing the posted data with $_POST which doesn't work. Because you are sending json data. If so you have to use file_get_contents('php://input') to access the sending data. It's an issue with the Content-Type header of the request. The $_POST works when it is set to application/x-www-form-urlencoded

Here is a similar question handle json request in PHP

like image 3
Gihan Avatar answered Nov 07 '22 06:11

Gihan