I'm trying to use getBodyParams()
to parse a JSON posted to a module controller action from an API. The incoming headers have content-type
set as application/json; charset=utf-8
, and I've tested to make sure there is a valid JSON string in the body. But when I try to get the retrieve the body using getBodyParams()
, I only get an empty array as a response. The documentation makes it sound like it's possible to parse JSON and other content types. Does anyone know the correct way to use getBodyParams()
to parse a JSON body?
2 Answers
Got in touch with P&T support and got the following response back:
We don't currently support parsing JSON via getBodyParams(), however I'm looking into it and looks like Yii can be configured to support that, when the request's Content-Type header is set to application/json. We would need to enable that feature ourselves though.
In the meantime you could do:
$body = Craft::$app->request->getRawBody(); $data = craft\helpers\Json::decode($body);
As of Craft 3.3, if you send a request to Craft with a Content-Type: application/json
header, Request::getBodyParam('property')
will work as expected, returning the property
value from the JSON data in the request body.
-
Hey Brandon, this doesn't seem to be working for me. To be clear, I'm making a POST request to the current URL (not an action URL specifically) with the Fetch API and the body JSON includes an "action" parameter. It looks like the action is ignored and the route's HTML is returned instead.– benfaceFeb 7, 2020 at 8:25
-
@benface Yeah,
action
params in the body are ignored if the content-type isapplication/json
, because it’s likely that theaction
param wasn’t actually intended for request routing in that case (GitHub webhooks send anaction
value in JSON, for example). So you will need to either route the request based on anaction
param in the query string, or define a URL rule inconfig/routes.php
, etc. Feb 7, 2020 at 13:27 -