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?


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);
  • Thanks for following up with them. That's helpful to know and I hope they do add this in one of the next releases.
    – Udo
    Aug 9 '19 at 7:24
  • @Udo They did mention they would be adding it to the roadmap for a future release at some point.
    – Joel
    Aug 9 '19 at 20:42

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.
    – benface
    Feb 7 '20 at 8:25
  • @benface Yeah, action params in the body are ignored if the content-type is application/json, because it’s likely that the action param wasn’t actually intended for request routing in that case (GitHub webhooks send an action value in JSON, for example). So you will need to either route the request based on an action param in the query string, or define a URL rule in config/routes.php, etc. Feb 7 '20 at 13:27
  • Thanks Brandon, that makes sense!
    – benface
    Feb 8 '20 at 15:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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