Magento – Magento 2. Make soap response as array

apimagento2soap

I'm implementing custom API for Magento 2. My client want the response to be as associative array.
Here is my class method:

class Gcapiapi implements GcapiapiInterface
{
     /**
       * Returns greeting message to user
       *
       * @param string[] $products
       * @return array
       */

       public function list($products  = NULL)
       {
          $result = array();
          $stockItems = ...
          ...
          foreach($stockItems as $stockItem){
             $itemData = array('product_id' => $product->getId(), 'sku' => $productSku, 'qty' => $stockItem->getQty(), 'is_in_stock' => $stockItem->getIsInStock());
             $result[] = $itemData;
          }
          return $result;
       }
}

Here is interface declaration:

interface GcapiapiInterface
{
   /**
   * Returns greeting message to user
   *
   * @param string[] $products
   * @return array
   */
    public function list($products = NULL);

}

I've added logs and I see that my method list executing. But in response I'm getting 500 error.
In exception.log I see the error:

Message: Class "array" does not exist. Please note that namespace must be specified.

I want to get the following response:

array (size=2)
0 => 
array (size=4)
  'product_id' => string '3708' (length=4)
  'sku' => string 'W3L2221LDCB2' (length=12)
  'qty' => string '228.0000' (length=8)
  'is_in_stock' => string '1' (length=1)
1 => 
array (size=4)
  'product_id' => string '3709' (length=4)
  'sku' => string 'W7L1226E5C96' (length=12)
  'qty' => string '23.0000' (length=7)
  'is_in_stock' => string '1' (length=1)

Can I get SOAP response as associative array somehow?
Thanks,

Best Answer

Rewrite your class as:

class Gcapiapi implements GcapiapiInterface
{
     /**
       * Returns greeting message to user
       *
       * @param string[] $products
       * @return mixed[]
       */

       public function list($products  = NULL)
       {
          $result = array();
          $stockItems = ...
          ...
          foreach($stockItems as $stockItem){
             $itemData = array('product_id' => $product->getId(), 'sku' => $productSku, 'qty' => $stockItem->getQty(), 'is_in_stock' => $stockItem->getIsInStock());
             $result[] = $itemData;
          }
          return $result;
       }
}

You can see the change in return type: array -> mixed[]
It's strongly advised to use Data interface in such cases even though mixed[] will work for you.