详情参考:magento webapi 接口返回 json对象_.net webapi接口返回json-优快云博客
本例用到的模型为ToDoList,可以参考CRUD模型进行创建:magento2框架MVVC開發入門(四)创建 Magento 2 CRUD 模型-优快云博客
(1)后端开发
首先在 你的模组/Api 目录下定义一个Api接口:
interface Product2VendorInterface
{
/**
* @return JsonObject
*/
public function getProduct2VendorInfo();
}
在 你的模组/Model/Api 目录下实现Api接口(注入了ToDoList的Collection):
class Product2Vendor implements \Bcn\ToDoCrud\Api\Product2VendorInterface
{
protected $_collection;
public function __construct(CollectionFactory $collection)
{
$this->_collection = $collection;
}
public function getProduct2VendorInfo()
{
$itemId = 2;
$a = $this->_collection->create();
$a->selectById($itemId);
$a->load();
$todoListData = [];
foreach ($a as $item) {
$todoListData[] = [
'item'=>[
'itemId'=>$item->getItemId(),
'content'=>$item->getContent()
],
'code'=>200
];
}
return $todoListData;
}
}
在 你的模组/etc 目录下编写di.xml文件和webapi.xml文件:
webapi.xml:
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route method="GET" url="/V1/testtodo">
<service class="Bcn\ToDoCrud\Api\Product2VendorInterface" method="getProduct2VendorInfo" />
<resources>
<resource ref="anonymous" />
</resources>
</route>
</routes>
di.xml:
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Bcn\ToDoCrud\Api\Product2VendorInterface" type="Bcn\ToDoCrud\Model\Api\Product2Vendor"/>
</config>
(2)Postman调用接口 http://hyh.local.com/rest/V1/testtodo,这里路径和webapi中的route一致,域名为你initial这个magento2工程的时候定义的base-url。