In Magento2, when we call order API

/V1/orders/:id method="GET", 
magento uses *Magento\Sales\Api\OrderRepositoryInterface::get($id)* 

which is defined in the *Magento\Sales\Model\OrderRepository::get($id)*,

So My question is, whenever I use either of the classes to fetch data similar to API response(json array) it returns PHP Object, so how can I receive the similar response.


You can use \Magento\Framework\Controller\Result\JsonFactory by injecting it in your controller constructor. Using it you will be able to return a PHP object into JSON format

Check this:

protected $resultJsonFactory;

public function __construct( 
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
        $this->resultJsonFactory = $resultJsonFactory;

public function execute()
    $message = 'Hello World';
    $result = $this->resultJsonFactory->create();
    $response = $result->setData(['Test Message' => $message]);
    return $response;


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.