For anyone else looking for answer, I have done similar stuff and here is my solution
to receive 2D array in POST Request, you need Request Interface
namespace [Vendor]\[Namespace]\Api;
use [Vendor]\[Namespace]\Api\RequestInterface;
interface YourInterface
{
/**
* @param RequestInterface[] $cartItem
* @return string
*/
public function getPost(array $cartItem);
}
Create file [Vendor][Namespace]\Api\RequestInterface
namespace [Vendor]\[Namespace]\Api;
interface RequestInterface
{
const QUANTITY = 'qty';
const SKU = 'sku';
/**
* @return int
*/
public function getQty(): int;
/**
* @param int $qty
* @return void
*/
public function setQty(int $qty): void;
/**
* @return string
*/
public function getSku(): string;
/**
* @param string $sku
* @return void
*/
public function setSku(string $sku): void;
}
Create File [Vendor][Namespace]\Model\Api\Request
namespace [Vendor]\[Namespace]\Model\Api;
use [Vendor]\[Namespace]\Api\RequestInterface;
use Magento\Framework\DataObject;
class Request extends DataObject implements RequestInterface
{
/**
* @inheriDoc
*/
public function getQty(): int
{
return (int)$this->getData(self::QUANTITY);
}
/**
* @inheriDoc
*/
public function setQty(int $qty): void
{
$this->setData(self::QUANTITY, $qty);
}
/**
* @inheriDoc
*/
public function getSku(): string
{
return $this->getData(self::SKU);
}
/**
* @inheriDoc
*/
public function setSku(string $sku): void
{
$this->setData(self::SKU, $sku);
}
}
di.xml should be
<?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="[Vendor]\[Namespace]\Api\YourInterface" type="[Vendor]\[Namespace]\Model\Api\YourModel"/>
<preference for="[Vendor]\[Namespace]\Api\RequestInterface" type="[Vendor]\[Namespace]\Model\Api\Request"/>
</config>
This will accept request as
{"cart_item":{"0":{"sku":"SKU1"},"1":{"sku":"SKU2"}}}
Hope this helps