'Powershell pagination with page token

I am trying to curl an API on loop while the page token is not empty. Essentially get all the results. I am having difficulties implementing the pagination.

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept", "application/json")
$headers.Add("Authorization", "Basic *************************")
$headers.Add("Content-Type", "application/json")

$body = "{
`n    `"aggregations`": [
`n        {
`n            `"metric`": `"io.confluent.kafka.server/received_bytes`"
`n        }
`n    ],
`n    `"filter`": {
`n        `"field`": `"resource.kafka.id`",
`n        `"op`": `"EQ`",
`n        `"value`": `"********`"
`n    },
`n    `"granularity`": `"P1D`",
`n    `"group_by`": [
`n        `"metric.topic`"
`n    ],
`n    `"intervals`": [
`n        `"now-7d/now`"
`n    ]
`n}"

$response = Invoke-RestMethod 'https://api.telemetry.confluent.cloud/v2/metrics/cloud/query' -Method 'POST' -Headers $headers -Body $body 
$Nextpage = $response.meta.pagination.next_page_token
$url = 'https://api.telemetry.confluent.cloud/v2/metrics/cloud/query?next_page_token='

while ($Nextpage -ne $null){
    $response = Invoke-RestMethod $url$Nextpage -Method 'POST' -Headers $headers -Body $body | ConvertTo-Json
    $Nextpage = $response.meta.pagination.next_page_token
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source