从 POST 到自定义 REST Api 路由没有响应
-
12-12-2019 - |
题
我为 Magento 的 REST Api 设置了一个工作自定义路由。
它适用于 GET 请求,因为 _retrieve()
对应的函数 V1.php
类按预期被调用并返回数据。但现在我正在尝试处理 POST 请求,而此时 Magento 的行为很奇怪:
- 当您想要发布数据时,您必须将数据定义为集合而不是实体
etc/api2.xml
像这样:<action_type>collection</action_type>
. 。否则 Magento 会抛出这个错误Mage_Api2_Model_Resource
(第 207 行):
// Creation of objects is possible only when working with collection
$this->_critical(self::RESOURCE_METHOD_NOT_IMPLEMENTED);
因此,当我将 action_type 定义为集合时,那么 _multiCreate()
对应的函数 V1.php
正在按预期被调用。
然而 Magento 现在不允许我返回任何数据。我想以 JSON 格式返回这个数组:
$response = array("success"=>true, "error"=>"", "model"=>array(1,2,3));
“success”、“error”和“model”被定义为 api2.xml 中的属性,因此应该可用。但当我回来时 $response
, ,响应是空的,状态为207 ...嗯!现在,由于它有 action_type 集合,我也尝试返回 $response
包装在另一个数组中,但没有成功。
在我的最后尝试中,我发现通过使用该方法设置数据 $this->getResponse()->addMessage(....)
我能够检索数据,但我认为这不是正确的方法,因为它被认为适用于成功/错误/警告消息类型,并且不符合我的数据类型要求。
最后但并非最不重要的一点是,我还尝试使用 $this->getResponse()->setBody($result)
和 $this->getResponse()->setRawBody($result)
方法,但再次 - 没有成功:
Magento 专家 - 从 POST 请求到 REST Api 检索数据的正确方法是什么?我非常需要你的帮助!
这是我的 api2.xml
:
<customer_login translate="title" module="Test_Restapi">
<group>restapi</group>
<model>restapi/api2_customer_login</model>
<title>Blablabla</title>
<sort_order>10</sort_order>
<privileges>
<customer>
<create>1</create>
<update>1</update>
<retrieve>1</retrieve>
</customer>
<guest>
<create>1</create>
<update>1</update>
<retrieve>1</retrieve>
</guest>
</privileges>
<attributes>
<success>Success</success>
<error>Error</error>
<model>Model</model>
</attributes>
<routes>
<route_collection>
<route>/restapi/customer/login</route>
<action_type>collection</action_type>
</route_collection>
</routes>
<versions>1</versions>
</customer_login>
解决方案
如果你看一下课堂 Mage_Api2_Model_Resource
应该由你的班级扩展,你可以找到函数 _render()
.
通过检查 dispach()
这个类的函数,你可以看到, _render()
函数由检索操作调用。所以你可以在操作结束时使用这个函数,如下所示 $this->_render($data)
.
创建操作不使用此函数,创建操作仅将 Location 标头设置为新创建的资源 url。
要利用属性过滤的优势,请使用 $this->getFilter()->out($data)
前 $this->_render($data)
Mage_Api2_Model_Resource::dispatch()
可以回答很多关于magento REST的问题!
其他提示
我设法从 _createMulti()
通过遵循 @raivis.krumins 建议来发挥作用。在 - 的里面 dispatch()
的功能 Mage_Api2_Model_Resource
我在第 228 行末尾添加了这 3 行 if
设置位置标头的语句:
$retrievedData = $this->_createMulti($filteredData);
$returnData = $this->getFilter()->out($retrievedData);
$this->_render($returnData);
第一行检索函数的结果,第二行过滤掉不需要的属性(未在 api2.xml
)最后第三行返回响应中的数据。
请注意,这些更改应始终在自定义模块中进行。永远不要改变核心类!
在您的自定义模块函数集中重新运行之前
$this->getResponse()->appendBody(json_encode($response));