I am trying to create a simple module to return JSON data, if i returned string or array it will return the targeted data, but i can’t return JSON object with key value
when i return the interface it will return error 500, the second time i refresh it will keep loading forever. so i have to restart apache to work.
so my code, first the product interface:
<?php
namespace MzTestApiToolApiData;
interface ProductInterface
{
/**
* @return int
*/
public function getId();
/**
* @param int $id
* @return $this
*/
public function setId($id);
/**
* @return string
*/
public function getName();
/**
* @param string $name
* @return $this
*/
public function setName($name);
}
the used model:
<?php
namespace MzTestApiToolModelData;
use MagentoFrameworkDataObject;
use MzTestApiToolApiDataProductInterface;
class Product extends DataObject implements ProductInterface
{
/**
* @inheritdoc
*/
public function getId()
{
$this->getId();
return $this->getData('id');
}
/**
* @inheritdoc
*/
public function setId($id)
{
return $this->setData('id', $id);
}
/**
* @inheritdoc
*/
public function getName()
{
return $this->getData('name');
}
/**
* @inheritdoc
*/
public function setName($name)
{
return $this->setData('name', $name);
}
}
and in the method:
/**
* @api
* @param int $id
* @return MzTestApiToolApiDataProductInterface
* @throws NoSuchEntityException
*/
public function show($id)
{
/** @var MzTestApiToolApiDataProductInterface $productInterface */
$productInterface = $this->productInterfaceFactory->create();
try {
/** @var MagentoCatalogApiDataProductInterface $product */
$product = $this->productRepository->getById($id);
$productInterface->setId($product->getId());
$productInterface->setSku($product->getSku());
$productInterface->setName($product->getName());
return $productInterface;
} catch (NoSuchEntityException $th) {
throw NoSuchEntityException::singleField('id', $id);
}
}
Update:
ProductRepositoryInterface:
<?php
namespace MzTestApiToolApi;
use MagentoFrameworkExceptionNoSuchEntityException;
interface ProductRepositoryInterface
{
/**
* Undocumented function
*
* @api
* @param int $id
* @return MzTestApiToolApiDataProductInterface
* @throws NoSuchEntityException
*/
public function show($id);
}