Magento 2 API – How to Use Dynamic Parameter in Custom REST API Module

apimagento2rest

Here is the url I want to to access the custom rest api.

http://127.0.0.1/index.php/rest/V1/customapi/filter1/sku_gt_2/filter2/price_gt_10

How do I define webapi.xml & the method parameters in interface?

<route url="/V1/customapi/add/:^filter/:value" method="GET">
    <service class="Custom\Pluginname\Api\CustomInterface" method="add"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

interface:

public function add($filter, $value); 

Is the about parameter filter can be received as a array?

Best Answer

You cannot use array, but you can use mixed as a Valid scalar type

for your example try to use this

in your webapi.xml file use this url [/V1/customapi/add]

your interface

    /**
     * @param mixed $filter
     * @return string
     */
    public function add($filter);

put your return type as you need

you model could be

    /**
     * {@inheritdoc}
     */
    public function add($filter)
    {
        return $filter['1'].$filter['2'];
    }

use the array as you need

end point example

/V1/customapi/add?filter[1]=sku_gt_2&filter[2]=price_gt_10

See

http://devdocs.magento.com/guides/v2.1/extension-dev-guide/service-contracts/service-to-web-service.html

for more details Hope this will help you