Search code examples
authenticationazure-devopsodata

Access Azure Devops OData APIs/endpoints with PAT? (I'm using powershell)


Is there a way to access the Azure DevOps OData feeds using a Personal Access Token (PAT)?

I've tried using the same create-a-PAT-and-base64-encode-it-prepended-with-a-:-and-stuff-it-into-the-authorization-header-as-"Basic $encodedText" process that works for the rest APIs, but that isn't working for the odata endpoints ( I'm trying to use https://analytics.dev.azure.com/org/project/_odata/v3.0-preview/PipelineRuns ).

Is there a way to use a PAT to hit the OData endpoints?

Thank you


Solution

  • The way to call OData queries for Azure DevOps using PAT in PowerShell is same as calling Azure DevOps REST API.

    Below is a sample of PowerShell Script as reference.

    $organization = "Organization Name"
    $project = "Project Name"
    $pipelineName = "Pipeline Name"
    $uri = "https://analytics.dev.azure.com/${organization}/${project}/_odata/v3.0-preview/PipelineRuns?`$apply=filter(Pipeline/PipelineName eq '${pipelineName}')/aggregate(`$count as TotalCount, SucceededCount with sum as SucceededCount, FailedCount with sum as FailedCount, PartiallySucceededCount with sum as PartiallySucceededCount, CanceledCount with sum as CanceledCount)"
    
    # Need to convert the PAT to be base64 token for use in the HTTP request headers.
    $pat = "Personal Access Token"
    $base64Token = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $pat)))
    $headers = @{Authorization = "Basic $base64Token"}
    
    $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $headers
    
    # Convert the output as JSON content and print to console.
    Write-Host ($response | ConvertTo-Json -Depth 10)
    # Save the JSON content of output into a JSON file.
    $response | ConvertTo-Json -Depth 10 | Out-File -FilePath odata-query-output.json
    

    enter image description here