Exploring Azure DevOps APIs

Azure DevOps API has everything you need to build your software product from envisioning to put in into end-users’ hands. The Azure-hosted DevOps services can enable your end to end product delivery with excellent traceability across the teams.  Azure DevOps provides you the ability to plan your project using agile tools, manage your source code using several code repositories, automate your build and release using highly scalable build and release pipeline, manage your test plan and automate your test case execution. All in all, an end to end traceability dashboard for Business users, developers, and other project team members.

Inside Azure DevOps

When we start looking inside Azure DevOps portal, it has 6 significant services that span across and helps in Application Lifecycle Management. Every service is integrated to support the robustness and speed of software development. Not every team member needs to be involved in every area of services. However, if you are the technical stakeholder, product owner, architect and responsible for the product, you must know every service offered by the Azure DevOps and how to leverage them to fast-track your software development.

Azure DevOps Services

Turning Azure DevOps Service On or Off

Azure DevOps Tips and Trick

Azure DevOps Services and REST API

Azure DevOps Services also exposes comprehensive REST APIs to interact with your data, integrate with DevOps and access all Azure DevOps features from custom applications. Using Azure DevOps Services API, let you access Azure DevOps features including Work Items, Dashboard, creating and managing Build and Release, access test data, in fact, everything you perform through the portal.

Having an additional layer of API’s access exposes several opportunities for developers such as:

  • Developing Custom LOB applications
  • Building its own data query and visualization layers
  • Building Custom extension
  • Developing Custom widgets
  • Integration with third-party applications
  • and many more…

Create and Deploy your Python Django App using Azure DevOps Project

Azure DevOps Tips & Tricks

Connecting with Azure DevOps Services APIs

Now, Let’s explore some of the basic Azure DevOps API using different mechanisms. In this article, we will explore the following three approaches:

  • Using API Client
  • Using PowerShell
  • Using Custom Application

Before getting into them, let’s set up the authentication layer for accessing the APIs.

Authentication

To access Azure DevOps API’s, first, we need to authenticate against the Azure DevOps organization. There are several ways to authenticate to Azure DevOps, using Azure Active Directory, OAuth or using a Personal Access Token. You need to choose Authentication mechanism depends on your business scenarios. For an instance, for an organizational level access of your application you can use Azure AD Authentication, whereas for a personal level you can use Personal Access Token (PAT). In this article we will explore using PAT.

Creating Personal Access Token

To create a Personal Access Token, login to Azure DevOps in this organization. From User Settings, select “Personal Access Tokens” to generate a new token.

azure devops apis
Create Personal Access Token

Create a Dashboard without a Team in Azure DevOps

Azure DevOps Tips & Tricks

From the Personal Access Token generation screen, create a new PAT Token, and grant the required scope. Ensure you copy the generated token and keep it for reference.

azure devops apis
Personal Access Tokens

Scopes for PAT access token defines set of features access for Azure DevOps API. You can either choose full access or custom defined.

Personal Access Token Scope

We have the authentication token, Now let’s try to get the list of projects from the DevOps Organization.

Using API Client – Postman

From the Postman, you need to follow few basic steps to call the API and get the data.

First, provide API URL to get list of project. This URL needs to have the DevOps organization.

https://dev.azure.com/abhijan/_apis/projects

Second, set the Query Parameter as following

api-version 5.1
Authorization Basic BASE64PATSTRING

Move to the Authorization section, sect Type as Basic Auth and provide the PAT Token to the Password field.

Once done, send the request, You will have JSON Response of all the Projects.

azure devops apis

If you just need to explore the API’s using postman, create an environment with PAT token and query parameter and then call the series of APIs to explore.

Using PowerShell

Invoking the Azure DevOps API is also straightforward from Powershell, Construct the URI and invoke it using Invoke-RestMethod.

$PATToken = "tf5qxxxxxxddmrkvmtoxxxxxxxxxxxxxtzljsulaq"
$AuthHeader= @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($PATToken)")) }

$uri = "https://dev.azure.com/abhijan/_apis/projects?api-version=5.1"

Invoke-RestMethod -Uri $uri -Method get -Headers $AuthHeader 

Once you execute the above script, it will return the total number of projects along with an array of all the projects.

Using Custom Application

While Postman lets you test APIs quickly and explores the data for testing, Powershell script with Azure DevOps API can let you connect and automate several things. Accessing the Azure DevOps API using Code gives lots of flexibility and let you build several custom application top of DevOps Services.

Accessing the DevOps API will remain same as we connect with any REST APIs using HTTPClient. You can find the reference sample from the Azure DevOps API Site.

Here is the sample snippet to get all the projects from Azure DevOps.

 public static async Task<RootObject> GetProjects()
        {
            RootObject projects = null;
            try
            {
                var personalaccesstoken = "tf5xxxxxxxqbt5vbn6hxxxxmjttzljxxxxxsulaq";

                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 = await client.GetAsync("https://dev.azure.com/abhijan/_apis/projects?api-version=5.1"))
                    {
                        response.EnsureSuccessStatusCode();
                        string responseBody = await response.Content.ReadAsStringAsync();

                        projects = JsonConvert.DeserializeObject<RootObject>(responseBody);

                    }
                }


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return projects;
        }

Following class are the model class defined to get the Object from the JSON,

    public class RootObject
    {
        public int count { get; set; }
        public List<ProjectItems> value { get; set; }
    }

    public class ProjectItems
    {

        public string id { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public string url { get; set; }
        public string state { get; set; }
        public int revision { get; set; }
        public string visibility { get; set; }
        public DateTime lastUpdateTime { get; set; }

    }

RootObject projects, will contain the counts of project and list of projects.

Following is the screenshots form one utility that read the projects and bind on the UI.

iotDevOps

Further, you call the APIs for get Workitems by passing the respective project .

GET https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id}?api-version=5.1

Work Item Query Language (WIQL)

Furthermore, you can also use Work Item Query Language ( WIQL), which allows access and filter query data top of Azure DevOps Services. WIQL Editor is a nice extension to start exploring WIQL in Azure DevOps.

azure devops apis
Azure DevOps

You can also write your own code and execute the WIQL in your custom application. Following code, snippet shows how we can leverage WIQL and built specific queries to fetch the data from Azure DevOps.

 private async void GetEpics()
        {

            Uri devopsOrgULR = new Uri("https://abhijan.visualstudio.com/");
            String patToken = "4yyc2ztg3xxxxrivoolh64ajnhxxxea3dejoa";
            VssConnection connection = new VssConnection(devopsOrgULR, new VssBasicCredential(string.Empty, patToken));
            WorkItemTrackingHttpClient witHTTPClient = connection.GetClient<WorkItemTrackingHttpClient>();
            Wiql wiqlQuery = new Wiql
            {
                Query = $"SELECT [System.Id], [System.WorkItemType], [System.Title], [System.State] FROM workitems WHERE [System.TeamProject] = 'my project' and   [System.WorkItemType] = 'EPIC"
            };

            WorkItemQueryResult tasks = await witHTTPClient.QueryByWiqlAsync(wiqlQuery);
        
            IEnumerable<WorkItemReference>  workItemReference = tasks.WorkItems.OrderBy(item => item.Id);

            List<WorkItem> tasksList = witHTTPClient.GetWorkItemsAsync(workItemReference.Select(itemID => itemID.Id)).Result;

            foreach (var task in tasksList)
            {
                EpicCombo.Items.Add(task.Fields["System.Title"].ToString());
            }

        }

Read More and Explore

Azure DevOps Services REST API Reference

Summary

Azure DevOps has everything you need to build your software product from envisioning to put in into end-users’ hands. Azure DevOps APIs allow developers or DevOps Engineers to make extended application top of DevOps. In this article, we have seen different options to connect and interacts with Azure DevOps services. Now, you can start deep dive and build your custom solution top of Azure DevOps Services.

About the Author:

Abhijit Jana is a Technology Leader, Technical Strategist, Solution Architect, Development Consultant, and a Trusted Technology Advisor with over thirteen years of experience in the IT industry with expertise in Development, Architecting, Engineering, Consulting, and Services Delivery. He is a former Microsoft MVP, Author of “Kinect for Windows SDK Programming Guide” and “HoloLens BluePrints” books and founder of The Daily .NET Tips. To know more about Abhijit, visit “https://abhijitjana.net.”

Reference:

Jana, A. (2020). Exploring Azure DevOps APIs. Available at: https://abhijitjana.net/2020/04/11/exploring-azure-devops-apis/ [Accessed: 19th May 2020].

Check out more great Azure content here

Share this on...

Rate this Post:

Share:

Topics:

Azure