Magento – How to return Associative Array from API in Magento 2

apimagento2restservice-contractsoap

I have created Custom Api which returns associativeArray.

  1. If I use associativeArray it's giving error
  2. If I use string[] it's working

    But I want to return associativeArray.

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

Example Methods:

 /**
     * Create multi Customers
     *
     * @param \Magento\Customer\Api\Data\CustomerInterface $customer
     * @return string[]
     */
    public function save(\Magento\Customer\Api\Data\CustomerInterface $customer);

save method working fine.

 /**
     * Create multi Customers
     *
     * @param \Magento\Customer\Api\Data\CustomerInterface $customer
     * @return array()|associativeArray()
     */
    public function save1(\Magento\Customer\Api\Data\CustomerInterface $customer);

save1 method returning error.

Error: Class "array()" does not exist. Please note that namespace must
be specified

So how can I return associativeArray?

Thanks in advance.

Best Answer

Custom data interface should be created to represent key-value pairs, e.g.

<?php
namespace Vendor\Module\Api\Data;

/**
 * Interface which represents associative array item.
 */
interface AssociativeArrayItemInterface
{
    /**
     * Get key
     * 
     * @return string
     */
    public function getKey();

    /**
     * Get value
     * 
     * @return string
     */
    public function getValue();
}

Then for the new service method it is possible to specify:
@return \Vendor\Module\Api\Data\AssociativeArrayItemInterface[].

Service layer must comply with some rules to be exposed via SOAP and REST. It is impossible to represent associative arrays in WSDL without key-value data interfaces, all complex entities in WSDL must be described using primitive types (but this will make it more difficult for clients written in strictly typed languages to consume such API).

There is one exception supported though, but is highly discouraged and should be used only in very special cases. If return or param type will be specified as mixed, it will be transformed in WSDL into anyType.