I have created Magento2 Api which is working fine when return type is string and When return type is Array it's throwing Error.
Error: main.CRITICAL: exception 'Exception' with message 'Report ID:
webapi-5612096a251d1; Message: Notice: Array to string conversion.
my code is:
app/etc/config.php
modules' =>
array (
'Learning_Test' => 1,
),
app/code/Learning/TestWebService/Api
<?php
namespace Learning\TestWebService\Api;
interface TestInterface
{
/**
* Return the Concatenate of the two values.
*
* @api
* @param string $name1 Left hand operand.
* @param string $name2 Right hand operand.
* @return array list of the two values.
*/
public function say($name1,$name2);
}
app/code/Learning/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<preference for="Learning\TestWebService\Api\TestInterface" type="Learning\TestWebService\Model\Test" />
</config>
app/code/Learning/etc/webapi.xml
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
<route url="/V1/test/say/:name1/:name2" method="GET">
<service class="Learning\TestWebService\Api\TestInterface" method="say"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>
app/code/Learning/TestWebService/Model/Test.php
<?php
namespace Learning\TestWebService\Model;
use Learning\TestWebService\Api\TestInterface;
class Test implements TestInterface
{
/**
* * Return the Concatenate of the two values.
*
* @api
* @param string $name1 Left hand operand.
* @param string $name2 Right hand operand.
* @return array list of the two values
*/
public function say($name1,$name2) {
return array(
'name1' => $name1,
'name2' => $name2,
);
}
}
Could you please suggest me how to return Array?
Best Answer
You case sounds like you are trying to return associative array. This is not supported by SOAP (which must be supported by service interfaces), that is why new data interface should be introduced.
Then in your method annotations specify:
@return \Learning\TestWebService\Api\Data\ComplexItemInterface
.