C#: Creating Work Items in Azure DevOps using REST API

Source:www.opentechguides.com | Date Published: 2020-04-29 17:38:45

Azure DevOps Services, formerly known as Visual Studio Team Services(VSTS) is a Microsoft product that provides DevOps capabilities for application development such as automation, collaboration, requirements management, test management, Continuous integration (CI), Continuous Delivery (CD) and monitoring. Azure DevOps Services REST API enables you to interact with Azure DevOps programmatically. You can make REST API calls to create, list, update and delete various resources in Azure DevOps links projects, boards, work items, test cases, commits, files, so on, and so forth. In this tutorial, you will learn how to how to make REST API calls from a C# console application to create work items in an Azure DevOps project.

Create C# Project in Visual Studio

First of all lets create a C# console app in Visual Studio. To do this,

Install Json.NET Package

The data that is exchanged between your application and Azure DevOps REST API service is in JSON format. So the next step is to install Json.Net which is a JSON framework for .NET that allows you to serialize and deserialize the data easily.

Create a Personal Access Token

A Personal Access Token (PAT) is required to authenticate your application with Azure DevOps Services. Click here to learn how to generate a PAT.

Program flow

  1. Azure Class: Inside a static class named Azure we have defined the following constants that are specific to your Azure DevOps environment. Make sure you update these values for your environment.

  2. Main Method: Main() method is where the program execution starts and the following actions are performed inside the Main method.

  3. CreateWIT Method: The (HttpClient client, string uri, HttpContent content) method sends an asynchronous POST request on the resource URI which is passed to this method as a parameter. If the POST is successful, this method returns the JSON string response received from REST API service otherwise it prints the error message and returns an empty string.

Program source code

Here is the full code.

using System;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;

namespace CreatWorkItems
{
  static class Azure
    {
      public const string BASE = "https://dev.azure.com";
      public const string PAT = "3ljqhiwlkowddiqscp2xd6nd3rwfs2g6vs5yfaeg2kcdzsgi264a";
      public const string ORG = "OpenTechGuides";
      public const string API = "api-version=5.1";
      public const string PROJECT = "OTGRESTDemo";
      public const string WIT_TYPE = "$Task";
    }
    
 class Program
    {
        static void Main(string[] args)
        {
           // Create and initialize HttpClient instance.
           HttpClient client = new HttpClient();

           // Set Media Type of Response.
           client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

           // Generate base64 encoded authorization header.
           client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "", Azure.PAT))));

           // Build the URI for creating Work Item.
           string uri = String.Join("?", String.Join("/", Azure.BASE, Azure.ORG, Azure.PROJECT, "_apis/wit/workitems", Azure.WIT_TYPE), Azure.API);
    
           // Create Request body in JSON format.
           string json = "[{ \"op\": \"add\", \"path\": \"/fields/System.Title\", \"from\": null, \"value\": \"REST API Demo task\"}]";
           HttpContent content = new  StringContent(json, Encoding.UTF8, "application/json-patch+json");
           
           // Call CreateWIT method.
            string result = CreateWIT(client, uri, content).Result;

            // Pretty print the JSON if result not empty or null.
            if (!String.IsNullOrEmpty(result))
            {
                dynamic wit = JsonConvert.DeserializeObject<object>(result);
                Console.WriteLine(JsonConvert.SerializeObject(wit, Formatting.Indented));
            }
     
            // Presss any key to exit
            Console.ReadLine();
            client.dispose();
        }
 
        public static async Task<string> CreateWIT(HttpClient client, string uri, HttpContent content)
        {
            try
            {
                // Send asynchronous POST request.
                using (HttpResponseMessage response = await client.PostAsync(uri, content))
                {
                    response.EnsureSuccessStatusCode();
                    return (await response.Content.ReadAsStringAsync());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return string.Empty;
            }
        } // End of CreateWIT method
 }
}

Common Errors

Here are some of the common errors that you encounter while working with REST API and their potential causes and resolution.


Open Tech Guides | www.opentechguides.com