I'm encountering an error while making an API call using PowerShell. The error message I receive is:
Error calling the API: "errorTypeCode":"REQUEST-EMPTY","message":"Supply valid JSON-object when posting.".Exception.Message"
This issue occurs when I try to interact with the StatBank Denmark API (https://api.statbank.dk/v1/data). DOC: https://www.dst.dk/en/Statistik/brug-statistikken/muligheder-i-statistikbanken/api
I started by running this script, and it worked fine. However, when I use the second script, it fails. Now, I have just gone blind to the script and don't understand why it can't be executed since the syntax is the same (I'm still a beginner in PowerShell)..
My working-script is:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$apiUrl = "https://api.statbank.dk/v1/data"
$payload = @{
"table" = "FOLK1c"
"format" = "CSV"
"variables" = @(
@{
"code" = "IELAND"
"values" = @("5100","0000")
}
)
}
try {
$response = Invoke-RestMethod -Uri $apiUrl -Headers @{ "Content-Type" = "application/json" } -Method Post -Body ($payload | ConvertTo-Json)
if ($response) {
# Store CSV data in a variable
$csvData = $response
$filePath = "C:\"
$csvData | Out-File -FilePath $filePath -Encoding UTF8
Write-Host "CSV data has been saved to: $filePath"
} else {
Write-Host "API returned no data."
}
}
catch {
Write-Host "Error calling the API: $_.Exception.Message"
}
My non-working script is:
\[Net.ServicePointManager\]::SecurityProtocol = \[Net.SecurityProtocolType\]::Tls12
$apiUrl = "https://api.statbank.dk/v1/data"
$payload = @{
"table" = "AUS08"
"format" = "CSV"
"variables" = @(
@{
"code" = "OMRÅDE"
"values" = @("*")
},
@{
"code" = "SAESONFAK"
"values" = @("*")
},
@{
"code" = "Tid"
"values" = @("\*")
}
)
} | ConvertTo-Json
try {
$response = Invoke-WebRequest -Uri $apiUrl -Headers @{ "Content-Type" = "application/json" } -Method Post -Body $payload
if ($response) {
$csvData = $response.Content
$filePath = "C:\"
$csvData | Out-File -FilePath $filePath -Encoding UTF8
Write-Host "CSV data has been saved to: $filePath"
} else {
Write-Host "API returned no data."
}
}
catch {
Write-Host "Error calling the API: $\_.Exception.Message"
}