REST API calls with Invoke-RestMethod in PowerShell - Time & Space Complexity
When using Invoke-RestMethod to call REST APIs, it's important to understand how the time taken grows as you make more calls.
We want to know how the total time changes when the number of API requests increases.
Analyze the time complexity of the following code snippet.
$urls = @('https://api.example.com/data1', 'https://api.example.com/data2', 'https://api.example.com/data3')
foreach ($url in $urls) {
$response = Invoke-RestMethod -Uri $url -Method Get
Write-Output $response
}
This code sends a GET request to each URL in the list and outputs the response.
- Primary operation: The foreach loop that sends an API request for each URL.
- How many times: Once for each URL in the list.
Each additional URL means one more API call, so the total time grows as you add more URLs.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 API calls |
| 100 | 100 API calls |
| 1000 | 1000 API calls |
Pattern observation: The total work grows directly with the number of URLs.
Time Complexity: O(n)
This means the time to complete all API calls grows linearly with the number of URLs.
[X] Wrong: "All API calls happen instantly or at the same time, so adding more URLs doesn't increase time much."
[OK] Correct: Each API call waits for a response before moving on, so more calls add more total time.
Understanding how repeated API calls affect time helps you write scripts that scale well and manage waiting times effectively.
"What if we changed the code to send all API requests at the same time using background jobs? How would the time complexity change?"