Search code examples
powershellwebrequest

Invoke-Webrequest host variable, Invalid URI: The hostname could not be parsed


I'm trying to do an api call to a webservice and not sure what goes wrong. Could be the quotation that is wrong in the $request variable.

[string]$subKey = "AAAAA-BBBBB-FFFFFF-EEEEEE-DDDDD"
[string]$method = "GET"
[string]$searchParam = "Type"
[string]$searchQuery = "QQ"
$request=("""https://api.test.com/api/assets/search?" + $searchParam + "=" + $searchQuery + "&PageSize=10&Page=1"""+" -Headers @{""Authorization"""+"="""+"SubKey "+$subKey+"""}")

Invoke-WebRequest $request -Method Get

This results in:

Invalid URI: The hostname could not be parsed.

If I just copy the output of $request and run Invoke-WebRequest it works.


Solution

  • The Invoke-WebRequest cmdlet takes an -Uri and a -Headers parameter. Also you can simplify the URL:

    [string]$subKey = "AAAAA-BBBBB-FFFFFF-EEEEEE-DDDDD"
    [string]$method = "GET"
    [string]$searchParam = "Type"
    [string]$searchQuery = "QQ"
    $uri= "https://api.test.com/api/assets/search?$searchParam=$searchQuery&PageSize=10&Page=1"
    
    Invoke-WebRequest -Uri $uri -Headers @{Authorization ="SubKey $subKey"} -Method Get