### Install Azure DevOps Go API Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/getting-started.md Install the Azure DevOps Go API library using the go get command. ```bash go get github.com/microsoft/azure-devops-go-api/azuredevops/v7 ``` -------------------------------- ### Complete Example: List All Projects with Pagination Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/getting-started.md A comprehensive example demonstrating how to list all projects in an Azure DevOps organization, including handling pagination using the ContinuationToken. This example sets up the connection, creates a client, and iterates through all project pages. ```go package main import ( "context" "fmt" "log" "strconv" "github.com/microsoft/azure-devops-go-api/azuredevops/v7" "github.com/microsoft/azure-devops-go-api/azuredevops/v7/core" ) func main() { // Create connection connection := azuredevops.NewPatConnection( "https://dev.azure.com/myorg", "pat-token", ) ctx := context.Background() // Create client coreClient, err := core.NewClient(ctx, connection) if err != nil { log.Fatal(err) } // Get projects with pagination index := 0 responseValue, err := coreClient.GetProjects(ctx, core.GetProjectsArgs{}) if err != nil { log.Fatal(err) } for responseValue != nil { for _, project := range responseValue.Value { fmt.Printf("%d. %s\n", index, *project.Name) index++ } // Check for more pages if responseValue.ContinuationToken != "" { continuationToken, _ := strconv.Atoi(responseValue.ContinuationToken) responseValue, err = coreClient.GetProjects(ctx, core.GetProjectsArgs{ ContinuationToken: &continuationToken, }) if err != nil { log.Fatal(err) } } else { responseValue = nil } } } ``` -------------------------------- ### Make Standard API Requests Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/getting-started.md Most API calls will use the default API version configured for the client. This example shows a standard request to get projects. ```go // Standard request (uses default version) projects, _ := coreClient.GetProjects(ctx, core.GetProjectsArgs{}) ``` -------------------------------- ### Get Build Timeline Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/build-client.md Retrieves the execution timeline for a specific build, including its tasks and steps. This can be useful for monitoring build progress or analyzing performance. The example shows how to iterate through the timeline records to find and print task details. ```go timeline, err := buildClient.GetBuildTimeline(ctx, build.GetBuildTimelineArgs{ ProjectId: stringPtr("my-project"), BuildId: intPtr(123), }) if timeline.Records != nil { for _, record := range *timeline.Records { if record.Type != nil && *record.Type == "Task" { fmt.Printf("Task: %s (Duration: %v)\n", *record.Name, record.FinishTime) } } } ``` -------------------------------- ### Get Deployments by Project and Definition Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/release-client.md Retrieves a list of deployments filtered by project, definition ID, status, and the number of results. Use this to get a paginated list of failed deployments for a specific release definition. ```go deployments, err := releaseClient.GetDeployments(ctx, release.GetDeploymentsArgs{ ProjectId: stringPtr("my-project"), DefinitionId: intPtr(5), StatusFilter: release.DeploymentStatusValues.Failed, Top: intPtr(10), }) ``` -------------------------------- ### Get Client by URL Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/DOCUMENTATION_SUMMARY.txt Retrieves an API client instance using the service URL. ```go func GetClientByUrl(connection *Connection, url string) (interface{}, error) ``` -------------------------------- ### QueueBuild Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/build-client.md Queues a new build, initiating a build run. It accepts build configuration details and project information to start the process. ```APIDOC ## QueueBuild ### Description Queues a new build (triggers a build run). It accepts build configuration details and project information to start the process. ### Method POST (Assumed, based on action) ### Endpoint /{project}/_apis/build/builds?api-version=7.0 (Assumed, based on common Azure DevOps REST API patterns) ### Parameters #### Path Parameters - **Project** (string) - Required - Project ID or name. #### Query Parameters - **api-version** (string) - Required - The version of the API to use. #### Request Body - **Build** (*Build) - Required - Build queue request object containing definition, parameters, source branch/version, and priority. - **Definition** (*DefinitionReference) - Required - The build definition to queue. - **Id** (*int) - Required - The ID of the build definition. - **Parameters** (*string) - Optional - JSON string of variable overrides. - **SourceBranch** (*string) - Optional - Git branch to build (e.g., "refs/heads/main"). - **SourceVersion** (*string) - Optional - Specific commit hash or revision. - **Priority** (*QueuePriority) - Optional - Build priority (Low, BelowNormal, Normal, AboveNormal, High). - **ProjectId** (*string) - Required - Project ID or name. - **DefinitionId** (*int) - Required - Build definition ID. - **IgnoreWarnings** (*bool) - Optional - Proceed even if there are validation warnings. - **CheckInTicket** (*string) - Optional - TFS check-in ticket (for TFVC). ### Response #### Success Response (200) - ***Build**: Queued build reference with ID. #### Response Example ```json { "id": 123, "status": "queued", "definition": { "id": 5 }, "sourceBranch": "refs/heads/feature/my-feature" } ``` ``` -------------------------------- ### Get All Processes Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/core-client.md Retrieves all processes available in the organization. This includes System, Custom, and Inherited process types. ```go func (client *ClientImpl) GetProcesses(ctx context.Context, args GetProcessesArgs) (*[]Process, error) ``` -------------------------------- ### Get Agent Capabilities Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/taskagent-client.md Retrieves the installed tools and software capabilities of a specific agent within a pool. Use this to check for required software versions. ```go caps, err := taskAgentClient.GetAgentCapabilities(ctx, taskagent.GetAgentCapabilitiesArgs{ PoolId: intPtr(1), AgentId: intPtr(5), }) for capability, value := range *caps { fmt.Printf("%s: %s\n", capability, value) } // Output: // Agent.OS: Linux // Agent.OSVersion: Ubuntu 20.04 // npm: 6.14.4 // node: v14.15.0 ``` -------------------------------- ### Example ApiResourceLocation Usage Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/types.md Demonstrates how to construct an ApiResourceLocation object, often used internally by the API client to build request URLs and manage versioning. ```go // Retrieved from OPTIONS request; used internally by Send() location := &azuredevops.ApiResourceLocation{ Area: stringPtr("core"), ResourceName: stringPtr("projects"), RouteTemplate: stringPtr("{area}/{resource}"), Id: uuidPtr(uuid.Parse("79134c72-4a58-4b42-976c-04e7115f32bf")), MinVersion: stringPtr("5.0"), MaxVersion: stringPtr("5.1"), ReleasedVersion: stringPtr("5.1"), } ``` -------------------------------- ### Context with Timeout Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/README.md This example shows how to set a 30-second timeout for an API request using `context.WithTimeout`. Ensure `cancel()` is deferred to release resources. ```go // With timeout ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) def cancel() // defer cancel() ``` -------------------------------- ### Get Project Properties Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/core-client.md Retrieves custom properties for a specific project. You can fetch all properties or a subset by providing specific keys. ```go func (client *ClientImpl) GetProjectProperties(ctx context.Context, args GetProjectPropertiesArgs) (*[]ProjectProperty, error) ``` -------------------------------- ### Get Projects with Default API Version Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/README.md This snippet demonstrates how to retrieve projects using the core client. The client automatically negotiates the appropriate API version with the server. ```go projects, _ := coreClient.GetProjects(ctx, core.GetProjectsArgs{}) ``` -------------------------------- ### Get Client by URL Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/connection-and-authentication.md Retrieves or creates an HTTP client for a specific URL. Clients are cached per normalized URL, ensuring the same instance is returned for identical URLs. ```go client := connection.GetClientByUrl("https://dev.azure.com/myorg") ``` -------------------------------- ### Configure Timeout and TLS for Connection Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/connection-and-authentication.md Example of setting a custom HTTP request timeout and TLS configuration for an Azure DevOps connection. ```go import "time" timeout := 30 * time.Second connection := azuredevops.NewPatConnection("https://dev.azure.com/myorg", "token") connection.Timeout = &timeout ``` -------------------------------- ### Get Single Project by ID or Name Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/core-client.md Retrieves details for a specific project using its ID or name. Optionally includes project capabilities and history. Handles 'Project not found' errors. ```Go project, err := coreClient.GetProject(ctx, core.GetProjectArgs{ ProjectId: stringPtr("my-project"), IncludeCapabilities: boolPtr(true), }) if err != nil { if we, ok := err.(*azuredevops.WrappedError); ok && *we.StatusCode == 404 { fmt.Println("Project not found") } } ``` -------------------------------- ### Get Agent Pools by Name Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/taskagent-client.md Retrieve agent pools, optionally filtering by name. Ensure the 'taskagent' package is imported and a client is initialized. ```go pools, err := taskAgentClient.GetAgentPools(ctx, taskagent.GetAgentPoolsArgs{ PoolName: stringPtr("Default"), }) if err != nil { log.Fatal(err) } for _, pool := range *pools { fmt.Printf("Pool: %s (ID: %d)\n", *pool.Name, *pool.Id) } ``` -------------------------------- ### Retrieve Single Build Definition Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/build-client.md Gets the full details of a specific build definition by its ID. You can optionally specify a revision or filter properties. ```go def, err := buildClient.GetDefinition(ctx, build.GetDefinitionArgs{ ProjectId: stringPtr("my-project"), DefinitionId: intPtr(5), }) if err != nil { log.Fatal(err) } fmt.Printf("Definition: %s\nRepository: %s\n", *def.Name, *def.Repository.Id) ``` -------------------------------- ### WIQL Query for Items Assigned to User Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/workitemtracking-client.md Example WIQL query to find work items assigned to the current user ('@me') that are not in a 'Done' state. This is useful for personal task tracking. ```sql "SELECT [System.Id], [System.Title] " + "FROM workitems " + "WHERE [System.AssignedTo] = @me " + "AND [System.State] <> 'Done'" ``` -------------------------------- ### Implement Context with Cancellation Signal Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/getting-started.md Use context cancellation to manually abort API requests, for example, in response to an operating system signal. Remember to defer the cancel function. ```go // Cancellation from signal ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Call API... ``` -------------------------------- ### WIQL Query for Active Bugs Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/workitemtracking-client.md Example WIQL query to retrieve active bugs within the current project. Ensure the 'Bug' work item type and 'Active' state match your requirements. ```sql "SELECT [System.Id], [System.Title], [System.State] " + "FROM workitems " + "WHERE [System.TeamProject] = @project " + "AND [System.WorkItemType] = 'Bug' " + "AND [System.State] = 'Active'" ``` -------------------------------- ### List All Projects Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/README.md Demonstrates how to list all projects in an Azure DevOps organization. Requires a PAT connection and the core client. ```go package main import ( "context" "fmt" "log" "github.com/microsoft/azure-devops-go-api/azuredevops/v7" "github.com/microsoft/azure-devops-go-api/azuredevops/v7/core" ) func main() { connection := azuredevops.NewPatConnection( "https://dev.azure.com/myorg", "your-pat-token", ) ctx := context.Background() coreClient, _ := core.NewClient(ctx, connection) projects, err := coreClient.GetProjects(ctx, core.GetProjectsArgs{}) if err != nil { log.Fatal(err) } for _, project := range projects.Value { fmt.Println(*project.Name) } } ``` -------------------------------- ### Queue a New Project Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/core-client.md Use this snippet to queue a new project for creation. It requires project details like name, description, and visibility. The function returns an operation reference for polling the creation status. ```go projectData := &core.TeamProject{ Name: stringPtr("NewProject"), Description: stringPtr("My new project"), Visibility: core.ProjectVisibilityValues.Private, } opRef, err := coreClient.QueueCreateProject(ctx, core.QueueCreateProjectArgs{ ProjectToCreate: projectData, }) if err != nil { log.Fatal(err) } // Poll for completion opsClient, _ := operations.NewClient(ctx, connection) for { op, err := opsClient.GetOperation(ctx, operations.GetOperationArgs{ OperationId: opRef.Id, }) if err != nil { break } if *op.Status == operations.OperationStatusValues.Succeeded { fmt.Println("Project created") break } time.Sleep(1 * time.Second) } ``` -------------------------------- ### Create Basic HTTP Client Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/connection-and-authentication.md Use NewClient to create a new HTTP client. It copies TLS and timeout settings from the provided connection. ```go func NewClient(connection *Connection, baseUrl string) *Client ``` ```go client := azuredevops.NewClient(connection, "https://dev.azure.com/myorg") ``` -------------------------------- ### Get All Branches Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/git-client.md Retrieves all branches in a repository by filtering references. Use this to get a list of all branches. ```go // Get all branches refs, err := gitClient.GetRefs(ctx, git.GetRefsArgs{ RepositoryId: stringPtr("repo-id"), ProjectId: stringPtr("my-project"), Filter: stringPtr("heads/"), }) ``` -------------------------------- ### Get Resource Location (Internal) Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/DOCUMENTATION_SUMMARY.txt Internal helper function to get resource location information. ```go func getResourceLocation(connection *Connection, locationId string) (*ApiResourceLocation, error) ``` -------------------------------- ### Create Core Service Client Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/getting-started.md Instantiate a client for the Core API service to manage projects and other core resources. Ensure a valid connection object is passed. ```go import ( "context" "github.com/microsoft/azure-devops-go-api/azuredevops/v7/core" ) ctx := context.Background() coreClient, err := core.NewClient(ctx, connection) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Retrieve All Projects with Pagination Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/core-client.md Fetches all projects accessible to the user, demonstrating pagination using continuation tokens. Handles multiple requests to retrieve all project data. ```Go responseValue, err := coreClient.GetProjects(ctx, core.GetProjectsArgs{}) if err != nil { log.Fatal(err) } index := 0 for responseValue != nil { for _, project := range responseValue.Value { if project.Name != nil { fmt.Printf("%d. %s\n", index, *project.Name) index++ } } if responseValue.ContinuationToken != "" { continuationToken, _ := strconv.Atoi(responseValue.ContinuationToken) responseValue, err = coreClient.GetProjects(ctx, core.GetProjectsArgs{ ContinuationToken: &continuationToken, }) if err != nil { log.Fatal(err) } } else { responseValue = nil } } ``` -------------------------------- ### Queue a New Build Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/build-client.md Queues a new build run with specified parameters. Ensure all required fields for the Build object and QueueBuildArgs are populated. ```go queuedBuild := &build.Build{ Definition: &build.DefinitionReference{ Id: intPtr(5), }, SourceBranch: stringPtr("refs/heads/feature/my-feature"), Priority: build.QueuePriorityValues.Normal, } result, err := buildClient.QueueBuild(ctx, build.QueueBuildArgs{ Build: queuedBuild, ProjectId: stringPtr("my-project"), DefinitionId: intPtr(5), }) if err != nil { log.Fatal(err) } fmt.Printf("Build queued: %d\n", *result.Id) ``` -------------------------------- ### GetAgentCapabilities Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/taskagent-client.md Retrieves the capabilities of an agent, such as installed tools and software. ```APIDOC ## GetAgentCapabilities ### Description Retrieves capabilities of an agent (installed tools, software, etc.). ### Parameters #### Query Parameters - **PoolId** (int) - Required - Agent pool ID - **AgentId** (int) - Required - Agent ID ### Returns #### Success Response - `*map[string]string`: Capabilities (capability name → value) ### Request Example ```go caps, err := taskAgentClient.GetAgentCapabilities(ctx, taskagent.GetAgentCapabilitiesArgs{ PoolId: intPtr(1), AgentId: intPtr(5), }) for capability, value := range *caps { fmt.Printf("%s: %s\n", capability, value) } // Output: // Agent.OS: Linux // Agent.OSVersion: Ubuntu 20.04 // npm: 6.14.4 // node: v14.15.0 ``` ``` -------------------------------- ### GetProcessById Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/core-client.md Retrieves a specific process by its unique identifier (GUID). ```APIDOC ## GetProcessById ### Description Retrieves a specific process by its unique identifier (GUID). ### Method GET ### Endpoint /processes/{processId} ### Parameters #### Path Parameters - **processId** (uuid.UUID) - Required - The GUID of the process to retrieve. #### Query Parameters - **ctx** (context.Context) - Required - Context for the request. ### Response #### Success Response (200) - **Process**: The retrieved process object. ### Response Example ```json { "id": "uuid-string", "name": "Process Name", "type": "System | Custom | Inherited" } ``` ``` -------------------------------- ### Create HTTP Client with Custom Options Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/connection-and-authentication.md Use NewClientWithOptions to create a client with custom configurations, such as replacing the underlying HTTP client with custom settings like timeouts. ```go func NewClientWithOptions(connection *Connection, baseUrl string, options ...ClientOptionFunc) *Client ``` ```go customHttpClient := &http.Client{ Timeout: 60 * time.Second, } client := azuredevops.NewClientWithOptions( connection, "https://dev.azure.com/myorg", azuredevops.WithHTTPClient(customHttpClient), ) ``` -------------------------------- ### Create Release API Client Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/release-client.md Instantiates a new Release API client using a Personal Access Token (PAT) for authentication. Ensure you have the correct organization URL and token. ```go ctx := context.Background() connection := azuredevops.NewPatConnection("https://dev.azure.com/myorg", token) releaseClient, err := release.NewClient(ctx, connection) ``` -------------------------------- ### Get Process by ID Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/core-client.md Retrieves a specific process by its unique identifier. Requires a GetProcessByIdArgs struct containing the ProcessId. ```go func (client *ClientImpl) GetProcessById(ctx context.Context, args GetProcessByIdArgs) (*Process, error) ``` -------------------------------- ### Retrieve Build Definitions Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/build-client.md Fetches a list of build definitions for a given project, with options to filter by name, repository, and other properties. Supports pagination. ```go definitions, err := buildClient.GetDefinitions(ctx, build.GetDefinitionsArgs{ ProjectId: stringPtr("my-project"), Top: intPtr(10), }) if err != nil { log.Fatal(err) } for _, def := range *definitions { fmt.Printf("Build: %s (ID: %d)\n", *def.Name, *def.Id) } ``` -------------------------------- ### Get Group Memberships with Identity Client Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/identity-client.md Retrieves the groups an identity belongs to. Supports expanded membership queries. ```go groups, err := identityClient.GetGroupMemberships(ctx, identity.GetGroupMembershipsArgs{ IdentityId: stringPtr("user-descriptor"), QueryMembership: identity.QueryMembershipValues.Expanded, }) for _, group := range *groups { fmt.Printf("Group: %s\n", *group.DisplayName) } ``` -------------------------------- ### CreateEnvironment Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/taskagent-client.md Creates a new deployment environment with the specified configuration. ```APIDOC ## CreateEnvironment ### Description Creates a new deployment environment. ### Parameters #### Request Body - **EnvironmentCreateParameter** (object) - Required - Environment configuration - **Name** (string) - Required - Environment name - **Description** (string) - Optional - Environment description #### Query Parameters - **ProjectId** (string) - Required - Project ID or name ### Returns #### Success Response (200) - **EnvironmentInstance** - The newly created environment ``` -------------------------------- ### Get Client by Resource Area ID Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/DOCUMENTATION_SUMMARY.txt Retrieves an API client instance based on the Resource Area ID. ```go func GetClientByResourceAreaId(connection *Connection, resourceAreaId string) (interface{}, error) ``` -------------------------------- ### Create Git API Client Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/git-client.md Instantiates a new Git API client using a background context and an Azure DevOps connection. Ensure the Git API is registered for the provided connection. ```go ctx := context.Background() connection := azuredevops.NewPatConnection("https://dev.azure.com/myorg", token) gitClient, err := git.NewClient(ctx, connection) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Teams in a Project Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/core-client.md Retrieves a list of teams within a specified project. Supports pagination with Top and Skip parameters. ```go teams, err := coreClient.GetTeams(ctx, core.GetTeamsArgs{ ProjectId: stringPtr("my-project"), Top: intPtr(10), }) if err != nil { log.Fatal(err) } for _, team := range *teams { fmt.Println(*team.Name) } ``` -------------------------------- ### Build Logs - GetBuildLogs Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/build-client.md Retrieves a list of all logs associated with a specific build. This can be used to get task or job logs. ```APIDOC ## GetBuildLogs Retrieves all logs for a build. ### Parameters #### Path Parameters - **ProjectId** (string) - Required - Project ID or name - **BuildId** (int) - Required - Build ID #### Query Parameters - **Top** (int) - Optional - Maximum logs to return ### Returns - `*[]BuildLog`: Task/job logs ``` -------------------------------- ### Get All Members of Admin Group Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/identity-client.md Retrieves all members of a specified group, such as 'Project Administrators'. This requires first finding the group by its name. ```go // First find the admin group groups, _ := identityClient.ReadIdentities(ctx, identity.ReadIdentitiesArgs{ SearchFilter: stringPtr("AccountName"), FilterValue: stringPtr("Project Administrators"), }) if groups != nil && len(*groups) > 0 { adminGroup := (*groups)[0] // Get all members members, _ := identityClient.GetGroupMembers(ctx, identity.GetGroupMembersArgs{ GroupId: adminGroup.Id, }) for _, member := range *members { fmt.Printf("Admin: %s\n", *member.DisplayName) } } ``` -------------------------------- ### Update Project Details Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/core-client.md This snippet demonstrates how to update an existing project's properties such as name, description, or visibility. It also shows how to restore a deleted project by setting the state. You need to provide the project ID and the updated project data. ```go projectUpdate := &core.TeamProject{ Name: stringPtr("Renamed Project"), Description: stringPtr("Updated description"), } opRef, err := coreClient.UpdateProject(ctx, core.UpdateProjectArgs{ ProjectUpdate: projectUpdate, ProjectId: stringPtr("my-project"), }) ``` -------------------------------- ### Get Identity Descriptor from GetIdentity Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/identity-client.md Obtain an identity descriptor from the result of a GetIdentity call. This descriptor can be used for subsequent API calls. ```go identity, _ := identityClient.GetIdentity(ctx, identity.GetIdentityArgs{ IdentityId: stringPtr("john.doe@contoso.com"), }) descriptor := identity.Id // Use this for subsequent calls ``` -------------------------------- ### Create Build API Client Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/build-client.md Initializes a new Build API client using an Azure DevOps connection. Ensure the Build API is available for your organization. ```go ctx := context.Background() connection := azuredevops.NewPatConnection("https://dev.azure.com/myorg", token) buildClient, err := build.NewClient(ctx, connection) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Group Members with Identity Client Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/identity-client.md Retrieves members of a specified group. Use Top and Skip parameters to paginate results. ```go members, err := identityClient.GetGroupMembers(ctx, identity.GetGroupMembersArgs{ GroupId: stringPtr("group-descriptor"), Top: intPtr(50), }) for _, member := range *members { fmt.Printf("Member: %s (%s)\n", *member.DisplayName, *member.UniqueName) } ``` -------------------------------- ### Handle ArgumentNilError Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/errors.md Example of triggering and handling an `ArgumentNilError`. This occurs when a required argument, like `ConnectedServiceCreationData`, is passed as `nil` to a client method. ```go // This triggers ArgumentNilError with ArgumentName="ConnectedServiceCreationData" _, err := coreClient.CreateConnectedService(ctx, core.CreateConnectedServiceArgs{ ConnectedServiceCreationData: nil, ProjectId: stringPtr("project-id"), }) if argErr, ok := err.(azuredevops.ArgumentNilError); ok { log.Printf("Missing required argument: %s", argErr.ArgumentName) } ``` -------------------------------- ### Access Multiple Azure DevOps Services Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/getting-started.md Demonstrates how to create clients for different Azure DevOps services (Core, Git, Build) and access their respective APIs using a single connection. Ensure you have the necessary client libraries imported. ```go // Core coreClient, _ := core.NewClient(ctx, connection) projects, _ := coreClient.GetProjects(ctx, core.GetProjectsArgs{}) // Git gitClient, _ := git.NewClient(ctx, connection) repos, _ := gitClient.GetRepositories(ctx, git.GetRepositoriesArgs{ ProjectId: stringPtr("my-project"), }) // Build buildClient, _ := build.NewClient(ctx, connection) definitions, _ := buildClient.GetDefinitions(ctx, build.GetDefinitionsArgs{ ProjectId: stringPtr("my-project"), }) ``` -------------------------------- ### Get Multiple Work Items Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/workitemtracking-client.md Retrieves a collection of work items using their IDs. Allows specifying fields to return for each work item. ```go ids := []int{123, 456, 789} workItems, err := witClient.GetWorkItems(ctx, workitemtracking.GetWorkItemsArgs{ Ids: &ids, Fields: &[]string{"System.Id", "System.Title", "System.State"}, }) ``` -------------------------------- ### Checking HTTP Status Codes for Project Operations Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/errors.md Demonstrates how to check for specific HTTP status codes (404, 401) when retrieving project details. This helps differentiate between a non-existent project and authentication issues. ```go project, err := coreClient.GetProject(ctx, core.GetProjectArgs{ ProjectId: stringPtr("my-project"), }) if err != nil { if we, ok := err.(*azuredevops.WrappedError); ok { if we.StatusCode != nil && *we.StatusCode == 404 { // Project doesn't exist log.Println("Project not found") } else if we.StatusCode != nil && *we.StatusCode == 401 { // Authentication issue log.Println("Invalid credentials") } } } ``` -------------------------------- ### Create a Pull Request Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/README.md Demonstrates how to create a new pull request in a Git repository. Requires the Git client, repository and project IDs, and details for the source and target branches. ```go gitClient, _ := git.NewClient(ctx, connection) newPR := &git.GitPullRequestToCreate{ SourceRefName: stringPtr("refs/heads/feature/new-feature"), TargetRefName: stringPtr("refs/heads/main"), Title: stringPtr("Add new feature"), Description: stringPtr("This PR implements..."), } pr, _ := gitClient.CreatePullRequest(ctx, git.CreatePullRequestArgs{ GitPullRequestToCreate: newPR, RepositoryId: stringPtr("repo-id"), ProjectId: stringPtr("my-project"), }) fmt.Printf("PR #%d created\n", *pr.PullRequestId) ``` -------------------------------- ### Get Identity Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/identity-client.md Retrieves identity information (user or group) based on its descriptor. It demonstrates how to check the identity type and print relevant details. ```APIDOC ## Get Identity ### Description Retrieves identity information (user or group) based on its descriptor. It demonstrates how to check the identity type and print relevant details. ### Method Signature `identityClient.GetIdentity(ctx context.Context, args identity.GetIdentityArgs) (*identity.Identity, error)` ### Arguments - `ctx` (context.Context): The context for the request. - `args` (identity.GetIdentityArgs): - `IdentityId` (string): The descriptor of the identity to retrieve. ``` -------------------------------- ### Create Core API Client Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/core-client.md Instantiates a new Core API client using a provided Azure DevOps connection. Ensure the Core API is registered in your organization. ```Go ctx := context.Background() connection := azuredevops.NewPatConnection("https://dev.azure.com/myorg", token) coreClient, err := core.NewClient(ctx, connection) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Handle ArgumentNilOrEmptyError Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/errors.md Example of triggering and handling an `ArgumentNilOrEmptyError`. This error is raised when a string parameter, such as `ProjectId`, is empty or `nil`, typically for route values. ```go // This triggers ArgumentNilOrEmptyError with ArgumentName="args.ProjectId" _, err := coreClient.CreateTeam(ctx, core.CreateTeamArgs{ Team: &core.WebApiTeam{Name: stringPtr("Team A")}, ProjectId: stringPtr(""), // Empty! }) // Checking the error if argErr, ok := err.(azuredevops.ArgumentNilOrEmptyError); ok { log.Printf("Invalid parameter: %s", argErr.ArgumentName) } ``` -------------------------------- ### Get Variable Groups in a Project Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/taskagent-client.md Retrieves a list of variable groups within a specified project. You can filter by name, state, and limit the number of results. ```go groups, err := taskAgentClient.GetVariableGroups(ctx, taskagent.GetVariableGroupsArgs{ ProjectId: stringPtr("my-project"), }) for _, group := range *groups { fmt.Printf("Variable Group: %s\n", *group.Name) } ``` -------------------------------- ### NewClient Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/build-client.md Creates a new Build API client. This client is the entry point for interacting with the Build API. ```APIDOC ## NewClient ### Description Creates a new Build API client. This client is the entry point for interacting with the Build API. ### Method `NewClient` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Request context - **connection** (*azuredevops.Connection) - Required - Azure DevOps connection with credentials ### Returns - `Client`: Interface for all Build API operations - `error`: ResourceAreaIdNotRegisteredError if Build API is not available ### Request Example ```go ctx := context.Background() connection := azuredevops.NewPatConnection("https://dev.azure.com/myorg", token) buildClient, err := build.NewClient(ctx, connection) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Get Active Pull Requests Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/git-client.md Retrieves active pull requests within a repository. This snippet demonstrates filtering by status and limiting the number of results. ```go activePRs, err := gitClient.GetPullRequests(ctx, git.GetPullRequestsArgs{ RepositoryId: stringPtr("repo-id"), ProjectId: stringPtr("my-project"), SearchCriteria: &git.GitPullRequestSearchCriteria{ Status: &git.PullRequestStatusValues.Active, Top: intPtr(20), }, }) ``` -------------------------------- ### Usage of ProjectState Enum in Go Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/types.md Demonstrates how to use the defined ProjectState constants for creating values, comparisons, and string conversions. Ensure the enum values match the expected API strings. ```go // Create a value using the constant set state := core.ProjectStateValues.WellFormed // Use in comparisons if projectState == core.ProjectStateValues.Deleted { // Handle deleted project } // String conversion (ProjectState is an alias for string) stringValue := string(state) ``` -------------------------------- ### Check Organization URL Format Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/README.md Ensure the organization URL follows the correct format for establishing a connection. Avoid trailing slashes. ```go // Check organization URL format // ✓ https://dev.azure.com/myorg // ✓ https://myorg.visualstudio.com // ✗ https://dev.azure.com/myorg/ (no trailing slash) // Validate PAT // Create at: https://dev.azure.com/myorg/_usersSettings/tokens // Use scopes: Code (Read & Write), Build (Read & Execute), Release (Read, Create & Execute) ``` -------------------------------- ### Get a Single Work Item Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/workitemtracking-client.md Retrieves a specific work item by its ID. You can specify fields to return or request historical data using the AsOf parameter. ```go workItem, err := witClient.GetWorkItem(ctx, workitemtracking.GetWorkItemArgs{ Id: intPtr(123), Fields: &[]string{"System.Title", "System.State", "System.AssignedTo"}, }) if err != nil { log.Fatal(err) } fmt.Printf("Title: %s\n", workItem.Fields["System.Title"]) ``` -------------------------------- ### Create Identity Client Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/identity-client.md Instantiate a new Identity API client using a background context and an Azure DevOps connection. Ensure to handle potential errors during client creation. ```go ctx := context.Background() connection := azuredevops.NewPatConnection("https://dev.azure.com/myorg", token) identityClient, err := identity.NewClient(ctx, connection) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Query Work Items Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/README.md Shows how to query work items based on a WIQL (Work Item Query Language) statement. Requires the work item tracking client and a valid connection. ```go witClient, _ := workitemtracking.NewClient(ctx, connection) query := &workitemtracking.Wiql{ Query: stringPtr( "SELECT [System.Id], [System.Title], [System.State] " + "FROM workitems " + "WHERE [System.TeamProject] = @project " + "AND [System.State] = 'Active' " + "ORDER BY [System.ChangedDate] DESC", ), } results, _ := witClient.QueryByWiql(ctx, workitemtracking.QueryByWiqlArgs{ Wiql: query, }) for _, item := range results.WorkItems { fmt.Printf("ID: %d\n", *item.Id) } ``` -------------------------------- ### Get Commits with Search Criteria Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/git-client.md Retrieves a list of commits from a repository using specified search criteria. Useful for filtering commits by author, date, or other attributes. ```go commits, err := gitClient.GetCommits(ctx, git.GetCommitsArgs{ RepositoryId: stringPtr("repo-id"), ProjectId: stringPtr("my-project"), SearchCriteria: &git.GitCommitSearchCriteria{ User: stringPtr("john.doe@contoso.com"), Top: intPtr(10), }, }) ``` -------------------------------- ### Context and Cancellation Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/getting-started.md Emphasizes the importance of passing a context for cancellation support in API calls. It provides examples of how to set up contexts with timeouts and how to handle cancellation signals. ```APIDOC ## Context and Cancellation Always pass a context for cancellation support: ```go // With timeout ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() projects, err := coreClient.GetProjects(ctx, core.GetProjectsArgs{}) // Cancellation from signal ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Call API... ``` ``` -------------------------------- ### Connection Methods Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/DOCUMENTATION_SUMMARY.txt Methods for establishing connections to Azure DevOps. ```APIDOC ## NewPatConnection ### Description Creates a new connection to Azure DevOps using a Personal Access Token (PAT). ### Method (Not specified, likely a constructor or factory function) ### Endpoint N/A ### Parameters - **pat** (string) - Required - The Personal Access Token for authentication. ### Request Example N/A ### Response - (Connection object) - A connection object to interact with the API. ## NewAnonymousConnection ### Description Creates a new anonymous connection to Azure DevOps. ### Method (Not specified, likely a constructor or factory function) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response - (Connection object) - A connection object to interact with the API. ## GetClientByResourceAreaId ### Description Retrieves an API client for a specific resource area using its ID. ### Method (Not specified, likely a method on a connection object) ### Endpoint N/A ### Parameters - **resourceAreaId** (string) - Required - The ID of the resource area. ### Request Example N/A ### Response - (API Client object) - A client object for the specified resource area. ## GetClientByUrl ### Description Retrieves an API client using a specific URL. ### Method (Not specified, likely a method on a connection object) ### Endpoint N/A ### Parameters - **url** (string) - Required - The URL to connect to. ### Request Example N/A ### Response - (API Client object) - A client object for the specified URL. ``` -------------------------------- ### QueueCreateProject Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/core-client.md Queues a new project for creation. This method returns an operation reference that can be used for status polling. ```APIDOC ## QueueCreateProject ### Description Queues a new project for creation. Returns an operation reference for status polling. ### Method (Not specified, likely a client method call) ### Parameters #### Path Parameters (None specified) #### Query Parameters (None specified) #### Request Body (Not applicable, uses arguments) ### Arguments - **args** (QueueCreateProjectArgs) - Required - Project details and configuration - **ProjectToCreate** (*TeamProject) - No - Project data (Name, Description, Visibility, etc.) ### Returns - ** extit{operations.OperationReference}**: Long-running operation reference - **error**: ArgumentNilError if ProjectToCreate nil, or server error ### Example ```go projectData := &core.TeamProject{ Name: stringPtr("NewProject"), Description: stringPtr("My new project"), Visibility: core.ProjectVisibilityValues.Private, } opRef, err := coreClient.QueueCreateProject(ctx, core.QueueCreateProjectArgs{ ProjectToCreate: projectData, }) if err != nil { log.Fatal(err) } // Poll for completion opsClient, _ := operations.NewClient(ctx, connection) for { op, err := opsClient.GetOperation(ctx, operations.GetOperationArgs{ OperationId: opRef.Id, }) if err != nil { break } if *op.Status == operations.OperationStatusValues.Succeeded { fmt.Println("Project created") break } time.Sleep(1 * time.Second) } ``` ``` -------------------------------- ### Get Identity Descriptor from Graph API Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/identity-client.md Obtain a user descriptor using the Graph API client. This is useful when you have a user's email or ID and need their descriptor. ```go graphClient, _ := graph.NewClient(ctx, connection) user, _ := graphClient.GetUser(ctx, graph.GetUserArgs{ UserId: stringPtr("john.doe@contoso.com"), }) descriptor := user.Descriptor // User descriptor ``` -------------------------------- ### Basic Error Checking in Go Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/errors.md Demonstrates how to perform basic error checking after an API call. If an error occurs, it is logged and the program exits. ```go resp, err := client.Send(ctx, "GET", locationId, "5.1", routeValues, queryParams, nil, "", "application/json", nil) if err != nil { log.Fatal(err) } defer resp.Body.Close() ``` -------------------------------- ### CreateDefinition Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/build-client.md Creates a new build definition with specified configurations for repository, process, triggers, and variables. ```APIDOC ## CreateDefinition ### Description Creates a new build definition. Requires a `BuildDefinition` object containing details like name, repository, process, triggers, and variables. ### Method `CreateDefinition` ### Parameters #### Path Parameters - **ProjectId** (*string) - Required - Project ID or name #### Request Body - **Definition** (*BuildDefinition) - Required - Build definition configuration - **DefinitionToCreate** (*BuildDefinition) - Required - (alternative parameter name) Build definition configuration ### BuildDefinition Fields: - **Name** (*string) - Definition name - **Repository** (*BuildRepository) - Source repository - **Process** (interface{}) - Build process (YAML or classic steps) - **Triggers** (*[]interface{}) - Build triggers - **Variables** (*map[string]Variable) - Build variables - **Queue** (*AgentPoolQueue) - Build queue - **BadgeEnabled** (*bool) - Enable badge ``` -------------------------------- ### Get All Repositories in Project Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/git-client.md Retrieves a list of all Git repositories within a specified Azure DevOps project. Supports filtering by including links, all URLs, and hidden repositories. ```go repos, err := gitClient.GetRepositories(ctx, git.GetRepositoriesArgs{ ProjectId: stringPtr("my-project"), }) if err != nil { log.Fatal(err) } for _, repo := range *repos { fmt.Printf("Repository: %s (%s)\n", *repo.Name, repo.Id) } ``` -------------------------------- ### Get Releases with Filters Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/release-client.md Retrieves a list of releases from Azure DevOps, allowing filtering by project, definition, status, and other criteria. Ensure you have the necessary project and definition IDs. ```go releases, err := releaseClient.GetReleases(ctx, release.GetReleasesArgs{ ProjectId: stringPtr("my-project"), DefinitionId: intPtr(5), StatusFilter: release.ReleaseStatusValues.Active, Top: intPtr(10), }) ``` -------------------------------- ### NewClientWithOptions Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/connection-and-authentication.md Creates a new HTTP client with custom options applied, allowing for more granular control over client configuration such as replacing the underlying HTTP client. ```APIDOC ## NewClientWithOptions ### Description Creates a new HTTP client with custom options applied. ### Method Signature ```go func NewClientWithOptions(connection *Connection, baseUrl string, options ...ClientOptionFunc) *Client ``` ### Parameters #### Path Parameters - **connection** (*Connection) - Required - Source of authorization and defaults - **baseUrl** (string) - Required - Base URL for the client - **options** (...ClientOptionFunc) - Optional - Option functions to customize the client ### Available Options - `WithHTTPClient(*http.Client)`: Replace the underlying HTTP client ### Returns - `*Client`: Configured HTTP client ### Example ```go customHttpClient := &http.Client{ Timeout: 60 * time.Second, } client := azuredevops.NewClientWithOptions( connection, "https://dev.azure.com/myorg", azuredevops.WithHTTPClient(customHttpClient), ) ``` ``` -------------------------------- ### CreateRepository Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/git-client.md Creates a new Git repository in a specified project with the provided configuration options. ```APIDOC ## CreateRepository ### Description Creates a new Git repository in a project. ### Parameters #### Request Body - **GitRepositoryCreateOptions** (*GitRepositoryCreateOptions) - Required - Repository configuration - **ProjectId** (*string) - Required - Project ID or name ### Example ```go newRepo := &git.GitRepositoryCreateOptions{ Name: stringPtr("my-new-repo"), } repo, err := gitClient.CreateRepository(ctx, git.CreateRepositoryArgs{ GitRepositoryCreateOptions: newRepo, ProjectId: stringPtr("my-project"), }) ``` ``` -------------------------------- ### Get Resource Location with Caching Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/client.md Retrieves API resource location by ID. The first call populates a server cache, while subsequent calls return the cached value. ```go func (client *Client) getResourceLocation(ctx context.Context, locationId uuid.UUID) (*ApiResourceLocation, error) ``` -------------------------------- ### Execute a WIQL Query Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/workitemtracking-client.md Executes a Work Item Query Language (WIQL) query. This snippet demonstrates how to construct a WIQL query to find active bugs and iterate through the results. ```go query := &workitemtracking.Wiql{ Query: stringPtr("SELECT [System.Id], [System.Title], [System.State] " + "FROM workitems " + "WHERE [System.TeamProject] = @project " + "AND [System.WorkItemType] = 'Bug' " + "AND [System.State] = 'Active' " + "ORDER BY [System.ChangedDate] DESC"), } results, err := witClient.QueryByWiql(ctx, workitemtracking.QueryByWiqlArgs{ Wiql: query, }) if results.WorkItems != nil { for _, item := range *results.WorkItems { fmt.Printf("ID: %d, URL: %s\n", *item.Id, *item.Url) } } ``` -------------------------------- ### Get All Members of Admin Group Source: https://github.com/microsoft/azure-devops-go-api/blob/dev/_autodocs/api-reference/identity-client.md Retrieves all members of a specified group, identified by its name. This involves first finding the group using `ReadIdentities` and then fetching its members using `GetGroupMembers`. ```APIDOC ## Get All Members of Admin Group ### Description Retrieves all members of a specified group, identified by its name. This involves first finding the group using `ReadIdentities` and then fetching its members using `GetGroupMembers`. ### Methods Used - `identityClient.ReadIdentities` - `identityClient.GetGroupMembers` ### Arguments for `ReadIdentities` - `ctx` (context.Context): The context for the request. - `args` (identity.ReadIdentitiesArgs): - `SearchFilter` (string): The filter to search by (e.g., "AccountName"). - `FilterValue` (string): The value to filter by (e.g., "Project Administrators"). ### Arguments for `GetGroupMembers` - `ctx` (context.Context): The context for the request. - `args` (identity.GetGroupMembersArgs): - `GroupId` (string): The ID of the group whose members are to be retrieved. ```