2

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!!

  • can you share if you figured some solution for optional params ? – Ajwad Syed Nov 14 at 12:59
  • @AjwadSyed You can't set optional params in URL directly. You can go with any of the provided 2 solutions. – Vinoth S Nov 14 at 13:03
  • From below @Adam solution is for required params and with #NID solution we can not have option to pass optional params while testing from default magento swagger UI, as it only accepts required params – Ajwad Syed Nov 14 at 13:09
1

It is possible to pass an optional param but not like this <route url="/V1/product/:productId/:optionalParam" method="GET">

you can pass it with the endpoint by using a question mark(?)

Suppose your endpoint is this: http://www.example.com/rest/V1/product/3 and if you want to pass some optional parameter, you can pass it like this:

http://www.example.com/rest/V1/product/3?optional_param=8

you can retrieve it like this:

$optional = $this->_request->getParam('optional_param');
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.