Quantcast
Channel: Excellence Technologies Magento Blog | Magento Tutorials | Magento Developer
Viewing all articles
Browse latest Browse all 69

Magento 2 – Request Response JSON

$
0
0

In this blog, we will learn about different operations on request and response in magento2. First of all, let’s start with reading GET/POST data. In many cases, we need to read data passed using GET or POST method such as data passed from form. To process this data, we need to first read the data. The method is similar to magento 1.

To read data passed via get Method we simply use following two methods:

$this->getRequest()->getParams()

this will read all the get data but to read any specific data we use

$this->getRequest()->getParam('data');

To read data passed via POST method, we use following method:

$this->request->getPost()

this will read all the the data being passed via post. But if we want to read specific data then we will use

$this->getRequest()->getPost('data');

But, if you go through the magento2 core files, then you will find getPostvalue() method used instead of getPost(). It is defined in lib\internal\Magento\Framework\HTTP\PhpEnvironment\Request.php:

public function getPostValue($name = null, $default = null)
{
    $post = $this->getPost($name, $default);
    if ($post instanceof ParametersInterface) {
        return $post->toArray();
    }
    return $post;
}

You can access the post data by using:

$post = $this->getRequest()->getPostValue();

Although both the methods, getPost() & getPostValue() have almost similar functionality but there is slight difference in the format they return data. In magento2, it is supposed to be good practice to use getPostValue().

Following example will make you understand better:

When we use getPost(), then it returns an instance like Zend\Stdlib\Parameters Object ( [storage:ArrayObject:private] => Array ( [data] => Array ( [title] => abc [status] => 1 [submit] => Save ) ) )

But when we use getPostValue() then we get a well structured array like: Array ( [data] => Array ( [title] => abc [status] => 1 [submit] => Save ) ) which is easy to manipulate. This is the reason, getPostValue is preferred over getPost() method.

then It get the getPost value from vendor\zendframework\zend-http\src\Request.php:

public function getPost($name = null, $default = null)
{
    if ($this->postParams === null) {
        $this->postParams = new Parameters();
    }

    if ($name === null) {
        return $this->postParams;
    }

    return $this->postParams->get($name, $default);
}

The above methods will work if you are trying this from a controller that extends Magento\Framework\App\Action\Action you can get the request. In other cases you need to inject request in the constructor as:

class ClassName 
{
     protected $request;
     public function __construct(
     \Magento\Framework\App\Request\Http $request,
     ....//rest of parameters here
     ) {
          $this->request = $request;
          ...//rest of constructor here
     }
     public function getPost()
     {
          return $this->request->getPost();
     }
}

Sending Custom Header/Response from Controller:

In magento2, it is possible, from a controller execute method, to manipulate the request to send a custom header and error page.

First of all, to comply with action controller interface \Magento\Framework\App\ActionInterface::execute(), your action must return an instance of \Magento\Framework\Controller\ResultInterface (\Magento\Framework\App\ResponseInterface is also supported, but is legacy and will be removed in future releases of M2, when all core usages are refactored).

So choose from available implementations of \Magento\Framework\Controller\ResultInterface. The most suitable for custom REST API (assuming it operates with JSON) seems to be \Magento\Framework\Controller\Result\Json. However, if you need something even more custom, consider \Magento\Framework\Controller\Result\Raw.

Here is code snippet which will help you to understand it better:

namespace VendorName\ModuleName\Controller;

/**
 * Demo of authorization error for custom REST API
 */
class RestAuthorizationDemo extends \Magento\Framework\App\Action\Action
{
    /** @var \Magento\Framework\Controller\Result\JsonFactory */
    protected $jsonResultFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory
    ) {
        parent::__construct($context);
        $this->jsonResultFactory = $jsonResultFactory;
    }

    public function execute()
    {
        /** @var \Magento\Framework\Controller\Result\Json $result */
        $result = $this->jsonResultFactory->create();
        /** You may introduce your own constants for this custom REST API */
        $result->setHttpResponseCode(\Magento\Framework\Webapi\Exception::HTTP_FORBIDDEN);
        $result->setData(['error_message' => __('What are you doing here?')]);
        return $result;
    }
}

The code above will result in response with HTTP status code 403 and body

{“error_message”:”Authorization Failed”}

The post Magento 2 – Request Response JSON appeared first on Excellence Technologies Magento Blog | Magento Tutorials | Magento Developer.


Viewing all articles
Browse latest Browse all 69

Trending Articles