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.