I'm trying to call an API that I created, using Azure DevOps pipelines (yaml file), and in it I need to pass in the headers the Authorization with Bearer token coming from the devops library and in the body the project that comes from System.TeamProject and the buildId of the pipeline that comes from Build.BuildId, but when the task is executed through the pipeline I get the following error: "errors":{"$.project":["The JSON value could not be converted to System.String. Path: $.project | LineNumber: 0 | BytePositionInLine: 51."]}}.
I've already researched a lot around here about the error and how I can solve it, but all of them didn't solve my case, does anyone know what I can do in this situation?
- job: 'step_two'
dependsOn: 'step_one'
condition: succeeded()
displayName: 'Step Two'
steps:
- task: PowerShell@2
inputs:
targetType: 'inline'
script: |
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Authorization','Bearer $(token)')
$headers.Add('Accept','application/json')
$headers.Add('Content-Type','application/json')
$url = 'https://example-api.com'
$body = @{
"buildId" = "$(Build.BuildId)"
"project" = "$(System.TeamProject)"
}
$json = $body | ConvertTo-Json
$response = Invoke-RestMethod -Method Post -Headers $headers -Uri $url -Body $json
echo $response
I have already tried to use an INVOKE REST API, but also without success, as it ends up causing me another problem, the token that comes from the AzureKeyVault is apparently not replaced, as it always returns 401 (unauthorized), but when I use the token directly or through another library is successfully authenticated.
- job: 'Call API'
dependsOn: 'step_one'
condition: succeeded()
displayName: 'Call API'
pool: server
steps:
- task: InvokeRESTAPI@1
inputs:
connectionType: 'connectedServiceName'
serviceConnection: 'My Service Connection'
method: 'POST'
headers: |
{
"Content-Type":"application/json",
"Authorization":"Bearer $(AzureKeyVaultToken)"
}
body: |
{
"buildId": "$(Build.BuildId)",
"project": "$(System.TeamProject)"
}
waitForCompletion: 'false'
All I hope is that in both the first and second cases I get a response from the API, authenticating correctly.