PageRule Post Api Bad Request

I am using the following powershell to manipulate the api related to page rules. I can get, delete fine so I know my headers are set correctly, but can’t post to create a new page rule. All I get is bad request and no more information. I’ve removed my zone id from the following for privacy reasons.

$cloudFlareUrl = $cloudFlareBaseUrl + 'zones/' + $cloudFlareZoneId + '/pagerules/'

this makes: zone id/pagerules/
I’ve tried this with and without the trailing slash

$forwardingRule = '{targets:[{"target":"url","constraint":{"operator":"matches","value":"' + $sitePrefix + '.' + $SiteBaseUrl + 
    '/*"}}],actions:[{"id":"forwarding_url","value":{"url":"' + 
    $sitePrefix + '.' + $SiteBaseUrl + '/$1","status_code":302}}]}'
$result = Invoke-RestMethod -Method POST -Uri $cloudFlareUrl -Headers $cloudFlareHeaders -Body $forwardingRule

so forwarding rule is

I can set this up manually using the website no problem. I have set it up manually and also checked what I Http GET from the site is also what I am sending.

Please can we have more meaningful error messages? What is wrong with the request above?

In case this helps anyone, powershell Invoke-restmethod was swallowing the error. This told me what the actual error was:

try {
    $result = Invoke-RestMethod -Method POST -Uri $cloudFlareUrl -Headers $cloudFlareHeaders -Body $forwardingRule
} catch {
    // Workaround because Invoke-RestMethod swallows any error message
    $streamReader = [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream())
    $errorResponse = $streamReader.ReadToEnd() | ConvertFrom-Json

I was having the same problem. My error was caused by using “Priority” as descirbed in the documentation. Once I removed this section, I was able to create rules.

I found it helpful to create a pagerule using the GUI, then get the pagerule with the API and convert the results to JSON, then use that as a template, removing the extra items, such as “priority”, etc.

$Results.result | ConvertTo-Json -Depth 4

Below is the code I use to create new forwarding_url pagerules with my $ZoneURL, $Header, $Target, $Destination, and $StatusCode being defined previously. Using @" "@ allows me to write out the JSON as it will be used while still passing variables to the string.

$body = @"
“targets”: [
“target”: “url”,
“constraint”: {
“operator”: “matches”,
“value”: “$Target”
“actions”: [
“id”: “forwarding_url”,
“value”: {
“url”: “$Destination”,
“status_code”: $StatusCode
“status”: “active”

$Results = Invoke-RestMethod -Uri $zoneUrl -Method POST -Headers $Headers -Body $body -ContentType “application/json”