Invoke Rest APIs in powershell and await for the response

9.7k views Asked by At

I am very new to PowerShell. I am running multiple rest API calls in one powershell script using Invoke-RestMethod and the second rest api call returns 200, but it fails at what it needs to do. It looks like it is failing because the first API endpoint has not finished the work.

Because when I run the second api separately in the separate script, it runs fine. Is there a async and await in powershell invoke-rest method function

Current code


try {
    #First Rest API It works fine
    Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Body $body  
}
catch {
    Write-Host "Failed"
    
}

try {
    #Second Rest API This returns 200 but does not do the work and if I run this API in a separate script
    #It runs fine in a separate script
    Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Body $body  
}
catch {
    Write-Host "Failed"  
}

Just wanted to see if I can await the first rest method

1

There are 1 answers

3
PowerShellGuy On BEST ANSWER

Like what Mathias stated in their comment Invoke-RestMethod Will return only when it completes what it's doing with the API.

If the API you're using has a GET method that allows you get a status of the POST in question, you can do something like this.

Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Body $body
do
{
    # Let's assume it returns a string: "OK"
    $status = Invoke-RestMethod -Uri $uri -Method Get -Headers $headers
}
while($status -ne "OK")