Many times when you create a Magento 2 REST API, you want to get the request body content. This is different from fetching the POST parameters. For example, you are creating a web service endpoint for a third party service that sends JSON content in the body of the request and not as POST parameters. Good thing is that it is extremely easy to do so in Magento 2.
I assume that you have already created a web service interface and the model that implements that interface. In the implementing model, you can get the request body content by Injecting Magento\Framework\Webapi\Rest\Request
class instead of Magento\Framework\App\RequestInterface
.
Here is the sample class to do so:
<?php namespace Webspeaks\Custom\Model; class ServiceManagement { protected $request; public function __construct( \Magento\Framework\Webapi\Rest\Request $request ) { $this->request = $request; } /** * {@inheritdoc} */ public function getSomeInfo() { // This function will get the body content of the request $body = $this->request->getBodyParams(); var_dump($body); return [ ["foo" => 'bar'], ]; } }
One thought on “Magento 2: How to get Post Body Content in REST Api”
Comments are closed.