magento2的RESTApi返回Json数据格式

详情参考:magento webapi 接口返回 json对象_.net webapi接口返回json-CSDN博客

本例用到的模型为ToDoList,可以参考CRUD模型进行创建:magento2框架MVVC開發入門(四)创建 Magento 2 CRUD 模型-CSDN博客

(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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值