Polaris (A PowerShell Module) Tip: Using Optional Route Parameter


It’s Saturday evening and I decided to grab a coffee and blog about Polaris. I should admit that I don’t use Polaris in my office project for now. Soon, I will do it with PSHTML. So, All my blog articles are just my demo. Here I am back with another tip that is using optional route parameter.  For example, if my endpoint is http://localhost:8080/employee/ I need to do something and if http://localhost:8080/employee/{ID} do something else. Yes, you are correct ID is an optional parameter.

In PowerShell all parameters are optional if not explicitly decorated as $true right?. Similarly we can decorate REST API endpoint as well. By default it’s required and we tweak to make it as optional. Enough of theory and let me show it in action.

New-PolarisGetRoute -Path "/employee/:ID?" -Scriptblock {
    if($Request.Parameters.ID) {
        $HTML = H1 "Employee ID is $($Request.Parameters.ID)" -Style "font-family:'Candara'"
    else {
        $HTML = H1 "Employee ID is EMPTY" -Style "font-family:'Candara'"

Check the route path decoration “/employee/:ID?”. Yes, ID followed by a question mark makes it as OPTIONAL. Execute and browse to http://localhost:8080/employee/ and http://localhost:8080/employee/{VALUE} and you will experience it!

Leave a Reply

Your email address will not be published. Required fields are marked *