9

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!

1
  • Could you pls put the section where you capture the $_POST params in your action?
    – Gihan
    Commented Jun 24, 2014 at 2:40

2 Answers 2

22

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.

3
  • awesome!! this is exactly my problem!
    – intellion
    Commented Jul 17, 2014 at 16:27
  • 1
    It also helps if you explicitly add the headers 'Content-Type = application/json' when you submit the request
    – d.raev
    Commented Jul 18, 2014 at 12:38
  • Still I cannot get the request params 'request' => [ 'parsers' => [ 'application/json' => 'yii\web\JsonParser', ], 'cookieValidationKey' => '1VwIjoKRv9mGh6NTZnmvFu1roaeC2zdQ', ], Commented Sep 8, 2017 at 5:34
3

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

2
  • This worked for me for 'Content-Type: application/xml'
    – crafter
    Commented May 20, 2016 at 19:48
  • You can use Request::getBodyParams to get and parse the input depending on Content-Type header.
    – ezze
    Commented May 27, 2016 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.