This powershell script gets :
Error sending API request:
The remote server returned an error: (400) Bad Request.
what could be the root cause ? bad url ?
apiUrl = "https://${location}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${location}/publishers/google/models/${modelVersion}:predict"
# Get Access Token Correctly
$serviceAccountKey="C:\temp\e97314fdbd4.json"
gcloud auth activate-service-account --key-file=$serviceAccountKey 2>$null
$accessToken = gcloud auth print-access-token
if (-not $accessToken) {
Write-Host "Failed to obtain access token. Ensure your service account is authenticated."
exit 1
}
# Create the request payload
$body = @{
instances = @(
@{ content = "Summarize this text: Artificial Intelligence is transforming industries by automating processes and improving efficiency." }
)
parameters = @{
temperature = 0.7
maxOutputTokens = 100
}
} | ConvertTo-Json -Depth 5
# Define headers correctly as a hash table
$headers = @{
"Authorization" = "Bearer $accessToken"
"Content-Type" = "application/json"
}
# Send API request using Invoke-WebRequest
try {
$response = Invoke-WebRequest -Uri $apiUrl -Method Post -Headers $headers -Body $body -ContentType "application/json" -UseBasicParsing
Write-Host "Response:"
Write-Host $response.Content
} catch {
Write-Host "Error sending API request:"
Write-Host $_.Exception.Message
}
Hi @faridn,
Welcome to the Google Cloud Community!
The (400) Bad Request error message you received indicates a problem with either the structure of the request or how the API endpoint is being used.
Here are possible causes and ways to troubleshoot the issue:
Was this helpful? If so, please accept this answer as “Solution”. If you need additional assistance, reply here within 2 business days and I’ll be happy to help.