Magento 2 Controller – Get JSON Response

jsonmagento2

I've created my custom controller and I want to return the result formated with JSON. I always get a JSON: []

Route:

 <route url="/V1/points/get" method="GET">
    <service class="module\Points\Controller\Points" method="get"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

Controller:

class Points extends Action implements \module\Points\Api\PointsInterface {
   protected $request;
   protected $resultJsonFactory;

protected $_pointFactory;

public function __construct(
    Context $context,
    \Magento\Framework\App\Request\Http $request,
    \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
    \YellowOctopus\Points\Model\PointFactory $pointFactory
)
{
    parent::__construct($context);
    $this->request = $request;
    $this->_pointFactory = $pointFactory;
    $this->resultJsonFactory = $resultJsonFactory;
}

/**
 * @return \Magento\Framework\Controller\Result\JsonFactory
 */
public function get()
{
   try {
      (...)
//$result = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON);
        return $this->resultJsonFactory->create()
         ->setData([
            'act' => 'success',
            'totalResults' => 16,
            'results' => [],
        ]);
    } catch (\Exception $e) {
        $result = $this->resultJsonFactory->create();
        return $result->setData([
            'act' => 'error',
            'm' => $e->getMessage(),
        ]);
    }
}

/**
 * @return \Magento\Framework\Controller\Result\Json
 */
public function execute() {}

Request:
GET: …/rest/V1/points/get?lat=50.164001&lng=-5.069998&distance=1500

Response (Postman):
https://prntscr.com/hg738w.jpg

Best Answer

I added this code to function and now work fine

$this->getResponse()->setHeader('Content-type', 'application/json');
$this->getResponse()->setBody(\Zend_Json::encode($response));
$this->getResponse()->sendResponse();
exit;
Related Topic