2

I want to return the JSON response suggested by the mobile app developer. My custom rest API currently returning responses in the below format.

[{
"status": true,
"data": [
  {
    "entity_id": "3",
    "name": "Test category",
    "icon_name": "test",
    "category_url": "http://127.0.0.1/magento/pub/catalog/category/view/s/test-category/id/3/",
    "button_name": "Sell Now"
  },
  {
    "entity_id": "4",
    "name": "magento Test",
    "icon_name": null,
    "category_url": "http://127.0.0.1/magento/pub/catalog/category/view/s/magento-test/id/4/",
    "button_name": "Sell Now"
  }
]}]

And below is the expected result:

 {"status": true,
    "data": [
      {
        "entity_id": "3",
        "name": "Test category",
        "icon_name": "test",
        "category_url": "http://127.0.0.1/magento/pub/catalog/category/view/s/test-category/id/3/",
        "button_name": "Sell Now"
      },
      {
        "entity_id": "4",
        "name": "magento Test",
        "icon_name": null,
        "category_url": "http://127.0.0.1/magento/pub/catalog/category/view/s/magento-test/id/4/",
        "button_name": "Sell Now"
      }
    ]
  }

The code that I have implemented: Interface:

 /**
     * Get category collection
     *
     * @api
     * @return string
     */
    public function getCategoryCollection();

Model:

public function getCategoryCollection()
      {
          try
          {
            $collection = $this->_categoryCollectionFactory->create();
            $collection->addAttributeToSelect('*');         
            $collection->addIsActiveFilter();          
            $i=0;
            if(count($collection)){
              foreach ($collection as $category){
                $data[$i]=["entity_id" => $category->getId(),
                            "name"=> $category->getName(),
                            "icon_name" => $category->getData('category_icon_name'),
                            "category_url" => $category->getUrl(),
                            "button_name" => "Sell Now"
                            ];
                      $i++;
                }
                $output = ["status"=>true, "data"=>$data];
            }
            else{
              $output=["status"=>false,"message"=>"No Category found"];
            }            
            return [$output]; 
          }
          catch (\Exception $exception) { 
            $output=["status"=> false, 'message' => $exception->getMessage()];
            return [$output];
          }
      }

I got one solution to add the below code but using that might be not appropriate:

print_r(json_encode($output)); 
die();

Any help will be grateful.

4

1 Answer 1

2

Try sending response like this

$this->response is object of \Magento\Framework\Webapi\Rest\Response class

  $this->response->setHeader('Content-Type', 'application/json', true)
                ->setBody(json_encode($output))
                ->sendResponse();
6
  • response is which class's object? Sep 7, 2022 at 8:15
  • 1
    this should not be used in webapi controllers Sep 7, 2022 at 8:41
  • Getting response like this: can't parse JSON. Raw result: {"status":true,"data":[{"entity_id":"3","name":"Test category","icon_name":"test","category_url":"http:\/\/127.0.0.1\/magento\/pub\/catalog\/category\/view\/s\/test-category\/id\/3\/","button_name":"Sell Now"},{"entity_id":"4","name":"magento Test","icon_name":null,"category_url":"http:\/\/127.0.0.1\/magento\/pub\/catalog\/category\/view\/s\/magento-test\/id\/4\/","button_name":"Sell Now"}]}[] Sep 7, 2022 at 8:41
  • Magento\Framework\Webapi\Rest\Response Inject this response object in your class using dependency injection Sep 7, 2022 at 9:45
  • We should use $jsonResponse = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON); from the controller
    – HoangHieu
    Sep 7, 2022 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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