How to trigger an Azure DevOps Pipeline via API

Azure DevOps pipelines can be triggered very easily using their API.

In practice, most build pipelines would be triggered via code changes or similar actions directly in Azure repos, so an external trigger would not be required. However, triggering via API can be very useful for a few different scenarios.

Some examples could be:

  1. Triggering a pipeline from a Slack message/bot.
  2. Triggering a pipeline to begin when a deployment ends on another service.
  3. Triggering a pipeline to begin if a critical error message is logged.

In my case, I was looking to run a set of automated tests via a webhook coming from an external CI/CD tool. This simple webhook would begin the automated test suite (webdriverio) when a deployment was complete.

Running the Pipeline

All that is required is a standard POST request.

fetch(AZURE_PIPELINE_URL, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: 'Basic ' + AZURE_PERSONAL_ACCESS_TOKEN,
  },
  body: JSON.stringify({
    resources: {
      repositories: {
        self: {
          refName: 'refs/heads/master',
        },
      },
    },
  }),
})

The endpoint follows the pattern: https://dev.azure.com/{organization}/{project}/_apis/pipelines/{pipelineId}/runs?api-version=6.1-preview.1

You will also need a Personal Access Token from your Azure account:

  1. Go to your Azure Portal → https://dev.azure.com/
  2. In the upper right hand corner, click the User Setting icon and then Personal Access Tokens
  3. Click New Token and enter your details. For Scopes, select Read & Execute under Build.
  4. Save your new token and copy the token ID to use in your application.

There are lots of other things you can do with the Azure DevOps API.
Check out the full docs here.

Hi, I'm Tom

I’m a Software Developer and Engineering Advocate current working for Deloitte Digital in Ireland. If you are one of the lucky ones to land here, please sign my Guestbook.