PowerShell: call Sume's image API with -StatusCodeVariable

-StatusCodeVariable and -SkipHttpErrorCheck let a PowerShell 7 script read the 200, 202 or 502 from Sume's /v1/images, then save the file with -OutFile.

4 min readSume
All posts

Pass -StatusCodeVariable sc and -SkipHttpErrorCheck to Invoke-RestMethod, then branch on $sc. Microsoft's cmdlet reference takes the status variable's name as a string such as -StatusCodeVariable "scv", and says the parameter can tell success from failure messages when used with -SkipHttpErrorCheck. Without them, a non-success status throws and you lose the body that explains why.

A Sume image call needs that, because three statuses carry a body you want to read. 200 has data[].url. 202 has a job envelope. 502 is a terminal failure with an error envelope that names a code and a next_action. The image API docs say to examine the status code, not the body shape.

A script that handles all three

Run it with PowerShell 7 and a key in $env:SUME_API_KEY. It stops on an empty key, prints the error body on anything but 200, and saves the image with -OutFile, which the cmdlet reference lists among its parameters.

$key = $env:SUME_API_KEY
if (-not $key) { throw "SUME_API_KEY is empty" }
$body = @{
  model = "openai/gpt-image-2.5"; prompt = "a red kettle on a white table"
  quality = "low"; output_format = "png"
} | ConvertTo-Json
$r = Invoke-RestMethod -Method Post -Uri "https://api.sume.com/v1/images" `
  -Headers @{ Authorization = "Bearer $key" } `
  -ContentType "application/json" -Body $body `
  -StatusCodeVariable sc -SkipHttpErrorCheck
if ($sc -ne 200) {
  Write-Error "status $sc"
  $r | ConvertTo-Json -Depth 6
  exit 1
}
Invoke-RestMethod -Uri $r.data[0].url -OutFile out.png
Write-Output "saved out.png, cost $($r.usage.cost) USD"

What about the 202 branch?

Slow settings, such as 4K, high quality or a large n, are the ones the docs name as likely to exceed the 30-second wait. For those, read $r.data.status_url and poll it with Start-Sleep and a growing delay until the status is completed, failed or canceled, then read the result_url. The jobs guide says not to resend the paid create call because your own timeout fired.

The usage.cost property in the last line is the billed USD amount. Sume bills image models per image, and the token counts in usage are always 0, so only the cost field is worth printing.

Run the script with pwsh (PowerShell 7), and check the version notes in the cmdlet reference before you rely on these two parameters in Windows PowerShell. Where they are missing, wrap the call in try and read the status from the caught exception. Keep -ContentType "application/json" on the call: without it, the cmdlet may not send the JSON header that Sume expects.

Sources

Related posts

More in Developers

All Developers posts

Written by Sume