Working within the UI on Azure DevOps is great, but I prefer some code to get the job done. Working with a REST API allows you the ability to interact with Azure DevOps within your application.

At the time of writing, the Azure DevOps REST API is on version 5.1.


Pre-requisites:

1. Pycharm or VSCode.

2. An Azure DevOps account.

3. A PAT token (admin rights to Azure DevOps required).

The first thing we want to do is take a look at the REST API itself. Head over to https://docs.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-5.1

If you take a look on the left side, you'll see multiple pieces of documentation. You can interact with Azure DevOps via any of those API's. Today we're going to focus on the Build API.

https://docs.microsoft.com/en-us/rest/api/azure/devops/build/builds?view=azure-devops-rest-5.1

If you click on the link above, you'll see a few different operations. The first piece of code we're going to write is for retrieving the builds. This would be a GET request.

Open up Pycharm or VSCode and lets write some code!

The first thing we'll need to do is import some libraries;

import requests

from requests.auth import HTTPBasicAuth

import logging

import getpass


Let's go over each of these;


requests = A library for API calls (GET, POST, DELETE, etc.)

requests.auth = Authentication for your API call

logging = Logger for specifying errors, warnings, info, etc.

getpass = A secure way to pass in your password (in our case the PAT token). It will not show as plain text.


Now we can start taking a look at our core code. Let's build a function called buildAPI.


def buildAPI(uri, username):

Within our function we'll create a variable for calling our PAT token.


p = getpass.getpass(prompt='Please enter PAT token: ')


Next we'll create our try/except blocks (For more info on error handling, please visit: https://realpython.com/python-exceptions/)


try:

resp = requests.get(uri, auth=HTTPBasicAuth(username, p))

print(resp.text)


except Exception as e:

logging.error(e)


Let's talk about what we're doing above;


1. The first line is starting out try block for error handling purposes

2. The second line is our variable to call our requests library and the get() method. We're passing in our uri and auth. The uri we're getting from our params and the same goes for our username.

3. The third line is to print the response. In our case it's the JSON output of our builds.

4. The forth and fifth line is if any errors occur, print our the errors to our console.


You have successfully used a GET request to retrieve your builds!