Navaneet
Navaneet

Reputation: 1387

Download json file from REST API

I am trying to export a build pipeline from Azure DevOps using the REST API provided by them. I am able to download json file using below sample url which contains the build definition in json format.

https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=5.0-preview.7

But when i try to download using powershell i get HTML file with html tags. But i need just the Json file which will be actual Build definition file to be downloaded. Below is my powershell code . I also tried using -ContentType "application/json" but it didn't resolve it.

$strURL = "https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=5.0-preview.7"
$filePath="C:\Pipeline_export"
$fileName=$filePath+"\build.json"
Invoke-RestMethod -Method Get -Uri $strURL  -OutFile $fileName

Upvotes: 0

Views: 9329

Answers (2)

Mengdi Liang
Mengdi Liang

Reputation: 18988

According to your code, you may lost authorized token in your code. So that it does not work using -ContentType "application/json".

On the other hand, we can also use another way to get code authorized: just enable Allow scripts to access the OAuth token and the script could access the OAuth token through the System.AccessToken variable.

Here is the completely code that can get the Json file correctly which modified on the basis of your code(with System.AccessToken not PAT):

 $strURL = "https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionid}?api-version=5.0-preview.7"
 $filePath="D:\"
 $fileName=$filePath+"\build.json"
 $pipeline =Invoke-RestMethod -Uri $strURL -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"} -Method GET -OutFile $fileName

Before download the Json file locally, you can use

Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"

to check whether the output in PowerShell Script logs is what you want.

Upvotes: 1

D.J.
D.J.

Reputation: 4034

the html is propably an error-page saying you didn't authorize correctly.

I use the following code for rest-api requests:

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "",$connectionToken)))
$result = Invoke-RestMethod -Uri $finalUrl -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

$finalUrl is the url of the resource, $connectionToken is my PersonalAccessToken

Upvotes: 3

Related Questions