Search code examples
.netpowershellrestoctopus-deployhateoas

PowerShell URI template parsing


I'm looking to use the Octopus REST API and I wanted to take full advantage of the HATEOAS links that are provided in Octopus REST API and some of them use URI Templates.

I found a fairly old post on the Octopus forums here but I was wondering with over 4 years passing, if there's a better solution for Uri Template parsing in PowerShell.

If not, I can use a .NET Uri Templating parsing package listed in the forum post.


Solution

  • So I was unable to find any native solutions, but I will share an example that implements Resta.UriTemplates.


    # Example adapted from: https://github.com/a7b0/uri-templates#examples
    
    Install-Package Resta.UriTemplates -Version 1.3.0
    
    # Import the Resta.UriTemplates assembly
    $Path = '.\Resta.UriTemplates.1.3.0\lib\netstandard2.0\Resta.UriTemplates.dll'
    Add-Type -Path $Path -PassThru | Select-Object -ExpandProperty Assembly | Select-Object -ExpandProperty FullName -Unique
    # Returns: 
    # Resta.UriTemplates, Version=1.3.0.0, Culture=neutral, PublicKeyToken=null
    
    $template = [Resta.UriTemplates.UriTemplate]'http://example.org/{area}/news{?type,count}'
    
    Write-Output $template
    # Returns:
    # Template                                    Variables
    # --------                                    ---------
    # http://example.org/{area}/news{?type,count} {area, type, count}
    
    $dict = New-Object 'system.collections.generic.dictionary[string,object]'
    $dict["area"] = "world"
    $dict["type"] = "actual"
    $dict["count"] = "10"
    
    $template.Resolve($dict)
    # Returns: 
    # http://example.org/world/news?type=actual&count=10