Azure DevOps Node.js API Client

15.1.2 · active · verified Sun Apr 19

The `azure-devops-node-api` package provides a robust and officially supported Node.js client for programmatically interacting with Azure DevOps Services and on-premises Team Foundation Server (TFS) REST APIs. It offers strongly typed interfaces for various services including Git, Build, Release, Work Items, and more, simplifying authentication and API calls compared to direct HTTP requests. The current stable version is 15.1.2, requiring Node.js >= 16.0.0. The library's release cadence is generally aligned with major Azure DevOps and TFS server updates, with significant version increments often indicating breaking changes tied to server compatibility and new features. Its key differentiator is providing a comprehensive, type-safe wrapper over the Azure DevOps REST APIs, making development more efficient and less error-prone.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate with Azure DevOps using a Personal Access Token (PAT), establish a connection, obtain a `BuildApi` client, and list the most recent builds for a specified project.

import { WebApi } from 'azure-devops-node-api/WebApi';
import { getPersonalAccessTokenHandler } from 'azure-devops-node-api/handlers/pat';
import { BuildApi } from 'azure-devops-node-api/BuildApi';

async function listBuilds() {
  const orgUrl = process.env.AZURE_DEVOPS_ORG_URL ?? 'https://dev.azure.com/your-organization';
  const token = process.env.AZURE_DEVOPS_PAT ?? ''; // Ensure PAT has 'Build: Read' scope
  const projectName = process.env.AZURE_DEVOPS_PROJECT_NAME ?? 'MyProject';

  if (!token) {
    console.error('AZURE_DEVOPS_PAT environment variable is not set.');
    return;
  }

  try {
    const authHandler = getPersonalAccessTokenHandler(token);
    const connection = new WebApi(orgUrl, authHandler);
    
    // Get the Build API client
    const buildApi: BuildApi = await connection.getBuildApi();

    // List recent builds for a specific project
    console.log(`Fetching builds for project: ${projectName}...`);
    const builds = await buildApi.getBuilds(projectName, undefined, undefined, undefined, undefined, undefined, 5); // Get top 5 builds

    if (builds.length === 0) {
      console.log('No builds found.');
      return;
    }

    console.log(`Found ${builds.length} recent builds:`)
    for (const build of builds) {
      console.log(`  - Build #${build.buildNumber}: ${build.status} - ${build.result ?? 'N/A'}`);
    }
  } catch (error: any) {
    console.error('Error fetching builds:', error.message);
    if (error.statusCode === 401) {
      console.error('Check your PAT and organization URL. Ensure PAT has sufficient scopes.');
    } else if (error.statusCode === 404) {
      console.error('Project or organization URL not found.');
    }
  }
}

listBuilds();

view raw JSON →