Magento – Optional parameter in Magento 2 REST API

apimagento2

I have a API route like,

<route url="/V1/product/:productId" method="GET">
    <service class="Vendor\Sample\Api\SampleInterface" method="sample"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

As you can see this route has a required parameter productId. Is it possible to add a optional parameter to this route?

Something like,

<route url="/V1/product/:productId/:optionalParam" method="GET">

Thanks in advance!!

Best Answer

I may be wrong but I don't think you can declare a specific parameter as optional from within the xml file, though you can declare your routes in such a way that the parameter becomes optional.
For example if you changed your xml to:

<route url="/V1/product/:productId" method="GET">
    <service class="Vendor\Sample\Api\SampleInterface" method="sample"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>
<route url="/V1/product/:productId/:optionalParam" method="GET">
    <service class="Vendor\Sample\Api\SampleInterface" method="sample"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

So long as the underlying method supports it being optional, something like:

public function sample($productId, $optionalParam = null)

This allows the code defined in that method to treat $optionalParam as optional.