Azure DevOps Go API

repository·dev·Indexed 42 days ago

https://github.com/microsoft/azure-devops-go-api

Go language bindings for interacting with and managing Azure DevOps services. This library acts as a thin wrapper around the official Azure DevOps REST APIs, providing typed clients for functional areas such as Core, CIX (Continuous Integration eXperience), and Cloud Load Test. It supports authentication via Personal Access Tokens (PAT) or anonymous connections and includes utilities for pagination using ContinuationTokens and custom HTTP client configuration via ClientOptionFunc.

Tokens
32.3K
Snippets
102
Records
185
Agent score
53%

What's inside Azure DevOps Go API

  1. Understand the relationship between the Go API and Azure DevOps REST APIs

    dev
    This library acts as a thin wrapper around the official Azure DevOps REST APIs. While the Go library provides typed clients and methods, the underlying logic and available endpoints are defined by the Azure DevOps REST API specification. For detailed information on specific API behaviors, parameters, and endpoints, refer to the Azure DevOps REST API reference.
  2. How to get help and report issues

    dev
    If you encounter bugs or wish to request new features for the Azure DevOps Go API, use GitHub Issues. Before creating a new issue, search the existing issue tracker to ensure your topic has not already been addressed, which helps prevent duplicate reports.
  3. Get started with the Azure DevOps Go API

    dev

    To interact with Azure DevOps, you must establish a connection using your organization's URL and a Personal Access Token (PAT). Once a connection is established, you can create specific clients (e.g., core.NewClient) to perform operations within different functional areas of Azure DevOps.

    Note that many API responses use pagination via a ContinuationToken. When a response contains a ContinuationToken, you should pass it into the next API call using the corresponding Args struct to retrieve the subsequent page of results.

    package main
    
    import (
    	"context"
    	"log"
    	"strconv"
    
    	"github.com/microsoft/azure-devops-go-api/azuredevops/v7"
    	"github.com/microsoft/azure-devops-go-api/azuredevops/v7/core"
    )
    
    func main() {
    	organizationUrl := "https://dev.azure.com/myorg" // todo: replace value with your organization url
    	personalAccessToken := "XXXXXXXXXXXXXXXXXXXXXXX" // todo: replace value with your PAT
    
    	// Create a connection to your organization
    	connection := azuredevops.NewPatConnection(organizationUrl, personalAccessToken)
    
    	ctx := context.Background()
    
    	// Create a client to interact with the Core area
    	coreClient, err := core.NewClient(ctx, connection)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// Get first page of the list of team projects for your organization
    	responseValue, err := coreClient.GetProjects(ctx, core.GetProjectsArgs{})
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	index := 0
    	for responseValue != nil {
    		// Log the page of team project names
    		for _, teamProjectReference := range (*responseValue).Value {
    			log.Printf("Name[%v] = %v", index, *teamProjectReference.Name)
    			index++
    		}
    
    		// if continuationToken has a value, then there is at least one more page of projects to get
    		if responseValue.ContinuationToken != "" {
    
    			continuationToken, err := strconv.Atoi(responseValue.ContinuationToken)
    			if err != nil {
    				log.Fatal(err)
    			}
    
    			// Get next page of team projects
    			projectArgs := core.GetProjectsArgs{
    				ContinuationToken: &continuationToken,
    			}
    			responseValue, err = coreClient.GetProjects(ctx, projectArgs)
    			if err != nil {
    				log.Fatal(err)
    			}
    		} else {
    			responseValue = nil
    		}
    	}
    }
  4. Use ETags for Dashboard Widget concurrency

    dev

    When retrieving or updating widgets, the API uses ETags to ensure version consistency.

    1. When calling GetWidgets, the returned WidgetsVersionedList contains an ETag field.
    2. When performing a ReplaceWidgets or UpdateWidgets operation, you can provide this ETag in the ReplaceWidgetsArgs or UpdateWidgetsArgs to ensure you are modifying the expected version of the dashboard's widget collection.
  5. How the Client manages requests and sessions

    dev

    The Client acts as the central engine for all API interactions. It handles:

    • URL Generation: It uses ApiResourceLocation (retrieved from the server) and routeValues to build the correct REST endpoint.
    • Request Construction: It automatically injects Authorization, Accept (with api-version), Content-Type, and User-Agent headers.
    • Session Management: It tracks a SessionId (a UUID). If the Azure DevOps server provides a new session ID in the X-TFS-Session header of a response, the client updates its internal SessionId to ensure subsequent requests remain within the same session.
    • Error Handling: It uses UnwrapError to parse error responses from the server, converting them into structured WrappedError types.
  6. Handle Azure DevOps API errors

    dev
    When a request fails (status code outside the 200-299 range), SendRequest calls UnwrapError. This method attempts to parse the error body into a WrappedError structure. If the error is returned as plain text, it returns a WrappedError containing the status and the text message. If it is JSON, it parses the error details provided by the Azure DevOps service.
  7. Initialize a V6 Policy Client

    dev

    To manage policy configurations in Azure DevOps using the V6 API, use the NewClient function. This requires an existing azuredevops.Connection object. The client provides methods to create, update, delete, and retrieve policy configurations and their revisions.

    import (
    	"context"
    	"github.com/microsoft/azure-devops-go-api/azuredevops/v6"
    	"github.com/microsoft/azure-devops-go-api/azuredevops/v6/policy"
    )
    
    // Assuming 'connection' is an already initialized *azuredevops.Connection
    client, err := policy.NewClient(ctx, connection)
    if err != nil {
    	// handle error
    }
  8. Initialize an Azure DevOps client

    dev

    To interact with Azure DevOps, you must create a Client instance. You can do this using NewClient for standard configurations or NewClientWithOptions if you need to provide custom ClientOptionFunc modifiers (such as a custom http.Client).

    Both methods require a *Connection object (which contains authorization and TLS settings) and a baseUrl string representing the Azure DevOps organization URL.

    // Using NewClient
    client := azuredevops.NewClient(connection, "https://dev.azure.com/your-org")
    
    // Using NewClientWithOptions for custom configuration
    client := azuredevops.NewClientWithOptions(connection, "https://dev.azure.com/your-org", azuredevops.WithHTTPClient(myCustomHttpClient))
  9. Initialize a CIX client

    dev

    To use the CIX (Continuous Integration eXperience) client, use the NewClient function. This requires an existing azuredevops.Connection object. The NewClient function retrieves the appropriate client for the connection's base URL and returns a Client interface used to manage project connections and resources.

    client := cix.NewClient(ctx, connection)
  10. Initialize the Extension Management Client

    dev

    To manage installed extensions in Azure DevOps, use NewClient from the extensionmanagement package. This requires an existing azuredevops.Connection object. The client provides access to preview APIs for installing, uninstalling, listing, and updating extensions.

    package main
    
    import (
    	"context"
    	"github.com/microsoft/azure-devops-go-api/azuredevops/v6"
    	"github.com/microsoft/azure-devops-go-api/azuredevops/v6/extensionmanagement"
    )
    
    func main() {
    	ctx := context.Background()
    	// connection is an existing *azuredevops.Connection
    	client, err := extensionmanagement.NewClient(ctx, connection)
    	if err != nil {
    		panic(err)
    	}
    	_ = client
    }
  11. Initialize the Contributions Client

    dev

    To interact with the Azure DevOps Contributions API (used for querying installed extensions and contribution nodes), use the NewClient function. This requires an existing azuredevops.Connection object.

    Note that all methods in this client are currently marked as [Preview API].

    import (
    	"context"
    	"github.com/microsoft/azure-devops-go-api/azuredevops/v7"
    	"github.com/microsoft/azure-devops-go-api/azuredevops/v7/contributions"
    )
    
    // Assuming 'connection' is an already initialized *azuredevops.Connection
    client, err := contributions.NewClient(ctx, connection)
    if err != nil {
    	// handle error
    }
    client, err := contributions.NewClient(ctx, connection)
  12. Initialize the Cloud Load Test client

    dev

    To use the Cloud Load Test API, create a new client using NewClient. This requires a context.Context and an existing azuredevops.Connection object. The client provides methods to manage agent groups, test definitions, test drops, and test runs.

    client, err := cloudloadtest.NewClient(ctx, connection)
    if err != nil {
    	// handle error
    }