Sormita Chakraborty
Sormita Chakraborty

Reputation: 1055

Get file from azure devops repository using rest api

I am trying to get a particular file from AzureDevops repository using the following code:

public static async void GetFile()
        {
            try
            {
                var personalaccesstoken = "XXXXXXXXX";

                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(
                        new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                        Convert.ToBase64String(
                            System.Text.ASCIIEncoding.ASCII.GetBytes(
                                string.Format("{0}:{1}", "", personalaccesstoken))));

                    using (HttpResponseMessage response = client.GetAsync(
                                "https://dev.azure.com/MS-ADM/SAPBuild/_apis/git/repositories/SAPBuild/items?path=/TestResult&download=true&api-version=5.0").Result)
                    {
                        response.EnsureSuccessStatusCode();
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                        Console.ReadLine();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

But I am getting back the following json back:

{
    "objectId": "08205d1ecfa86e4d8a2451fa189e68711398f126",
    "gitObjectType": "tree",
    "commitId": "xxxxxxxxxxxxxxxx",
    "path": "/TestResult",
    "isFolder": true,
    "url": "https://dev.azure.com/MS-ADM/xxxxxxxxxx/_apis/git/repositories/768454e2-4250-4d83-821b-7ac1c2707f5d/items?path=%2FTestResult&versionType=Branch&versionOptions=None",
    "_links": {
        "self": {
            "href": "https://dev.azure.com/MS-ADM/xxxxxxxx/_apis/git/repositories/768454e2-4250-4d83-821b-7ac1c2707f5d/items?path=%2FTestResult&versionType=Branch&versionOptions=None"
        },
        "repository": {
            "href": "https://dev.azure.com/MS-ADM/xxxxxxxxx/_apis/git/repositories/768454e2-4250-4d83-821b-7ac1c2707f5d"
        },
        "tree": {
            "href": "https://dev.azure.com/MS-ADM/xxxxxxx/_apis/git/repositories/768454e2-4250-4d83-821b-7ac1c2707f5d/trees/08205d1ecfa86e4d8a2451fa189e68711398f126"
        }
    }
}

What should I write in the url to get the file inside TestResult folder?

Upvotes: 3

Views: 14236

Answers (3)

Devanathan M
Devanathan M

Reputation: 11

The below fix worked for me to get the JSON file content,

In the URL you have to include the below property

"&includeContent=true" to retrieve its content, if it is a json file

and then from the reponse body, you have to do deserialize to get the exact json content

dynamic jsonData = JsonConvert.DeserializeObject(responseBody);

var responseContent = jsonData.content;

enter image description here

Upvotes: 0

PatrickLu-MSFT
PatrickLu-MSFT

Reputation: 51093

The API you are using "https://dev.azure.com/MS-ADM/SAPBuild/_apis/git/repositories/SAPBuild/items?path=/TestResult&download=true&api-version=5.0

You should specify that particular file path instead of folder path such as path=path=%2FTestResult/**Home.cshtml**

Using a folder path, as you can see, the return json also shows "isFolder": true,.

More details and powershell sample, you could kindly refer below samples:

  1. How to download a file in a branch from a Git repo using Azure DevOps REST Api?
  2. Download an application from Azure Devops via command line

Upvotes: 3

Xavier John
Xavier John

Reputation: 9437

Here is a way to download some files using Powershell script.

# Get personal access token
az login
$azureDevopsResourceId = "499b84ac-1321-427f-aa17-267ca6975798"
$token = az account get-access-token --resource $azureDevopsResourceId | ConvertFrom-Json
$pat = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":" + $token.accessToken))

# project and files
$project = '<project>'
$repository = '<repo>'

$files = @(
    'file1.json',
    'file2.json'
)

foreach ($file in $files) {
    $url = "https://dev.azure.com/$project/_apis/git/repositories/$repository/items?scopePath=/src/$file"
    $outfile = "$($PSScriptRoot)\src\$file"
    Write-Output  $outfile
    Invoke-RestMethod $url -Headers @{Authorization = "Basic ${pat}"} -OutFile $outfile
 }

Upvotes: 2

Related Questions