CodexBloom - Programming Q&A Platform

PowerShell 7.3 - implementing Using Invoke-RestMethod for JSON Response in a Loop

👀 Views: 1511 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-16
powershell api http error-handling PowerShell

I'm converting an old project and I'm experimenting with I'm upgrading from an older version and I'm experiencing unexpected behavior when using `Invoke-RestMethod` in a loop to fetch data from an API... My goal is to retrieve a list of user IDs from an endpoint, but it seems to unexpected result intermittently when the list is large. Here's the code I'm using: ```powershell $userIds = 1..1000 # Simulated list of user IDs $results = @() foreach ($userId in $userIds) { try { $response = Invoke-RestMethod -Uri "https://api.example.com/users/$userId" -Method Get -ErrorAction Stop $results += $response } catch { Write-Host "Failed to fetch user ID $userId: $_" } } ``` This seems to work for the first few hundred user IDs, but then I start seeing errors like: ``` Invoke-RestMethod : Unable to connect to the remote server ``` or sometimes: ``` The operation has timed out ``` I suspect it might be due to rate limiting on the API or perhaps a network scenario, but I'm unsure how to handle this gracefully. I've tried adding a `Start-Sleep -Seconds 1` before each call, but it hasn't made much difference. How can I effectively handle such errors and ensure that I can complete the loop without losing data? Is there a better approach to implement retries or to manage the rate at which requests are sent? Any suggestions would be appreciated. My team is using Powershell for this mobile app. Thanks, I really appreciate it! Thanks for your help in advance! My development environment is Ubuntu 22.04. What's the correct way to implement this?