Yii2 RESTful Webservice: JSON Request Format

13,008

Solution 1

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.

Solution 2

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

Share:
13,008
PhilippS
Author by

PhilippS

Java & JavaScript Developer from Germany philipp-schuermann.de

Updated on July 22, 2022

Comments

  • PhilippS
    PhilippS almost 2 years

    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!