0

I am invoking an REST API to assemble a .csv with users of software products, but sometimes it got stuck on page 0 and providing the same information again and again until the taskscheduler stops the script. Running on PS version 5.1 and below is the do / while I am using. Is there any way to check if the loop is already stuck at page 0 or to avoid this?

$i = 0
do {

    #invoke software products 
    $response = Invoke-RestMethod -Method GET -Uri "$aAppBaseUrl/software-products?size=2000&page=$i" -Headers $headers

    #function execution block
    myFunction

    $i = $i + 1
    $last = $response.last

} While ($last -eq $False)
userM
  • 1
  • 1
  • 1
    Does the Rest API return a 'next' URL as well as the 'last' property you're using? I've seen this with a lot of APIs and it means you simply invoke this 'next' URL until there isn't one returned, which saves any issues with you tracking the pages. – boxdog Jul 05 '22 at 07:14

1 Answers1

0

i don't think it "just" stuck at page 0 => $i = 0. If that only sometimes happens, as you say, i'm pretty sure that you reset $i anywhere in your "myFunction" block.

You also could check if there is a prevPage and nextPage Property in the response. If there is an lastPage im sure there is also a nextPage Property. In this case you dont need your $i anymore.

However: Here is how i would print the variables nextPage and prevPage.

Tip: Let your code explain what's going on. Just dont say "$i", it's "nextPage". And while "hasNextPage" you want to fetch more information.

$prevPage = 0
$nextPage = 0
do {

    Write-Host "Prev Page = $prevPage"
    Write-Host "Next Page = $nextPage"
    
    #invoke software products 
    $response = Invoke-RestMethod -Method GET -Uri "$aAppBaseUrl/software-products?size=2000&page=$nextPage" -Headers $headers

    #function execution block
    myFunction

    $prevPage = $nextPage 
    $nextPage += 1

    $hasNextPage = !$response.last


} while ($hasNextPage)

Sven
  • 420
  • 3
  • 10