Monday, December 16, 2019

How to use Azure DevOps API for Get,Patch, Post in ADO using C#?

In this blog, I am going to discuss about how to GET,PATCH and POST the ADO Rest API's using C#.

AzureDevOps provides rest API's as their endpoints to fetch the data,partial update(patch), or to create in ADO. We can call these API's in different programming languages. Below is how we can use it in C#

GET:

Below is a generic function which can be used as "GET" function in c#

public string getAdoapi(string pat,string link)
{
    string Url = link;
    string responseBody = "";
    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
        ASCIIEncoding.ASCII.GetBytes(
        string.Format("{0}:{1}", "", pat))));
        using (HttpResponseMessage response = client.GetAsync(Url).Result)
        {
        response.EnsureSuccessStatusCode();
        responseBody = response.Content.ReadAsStringAsync().Result;
        }

    }
    return responseBody;
}


POST:

Similarly for POST, apart from API and PAT the function requres postJson i.e the JSON which is contains the data that has to be posted over to ADO.

public string postAdoapi(string pat,string link,string postJson)
{
    string Url = link;
    string responseBody = "";
    using (HttpClient client = new HttpClient())
    {
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
    ASCIIEncoding.ASCII.GetBytes(
    string.Format("{0}:{1}", "", pat))));
    var method = new HttpMethod("POST");
    var request = new HttpRequestMessage(method, Url)
    {
    Content = new StringContent(postJson, Encoding.UTF8, "application/json")
    };
    using (HttpResponseMessage response = client.SendAsync(request).Result)
    {
    response.EnsureSuccessStatusCode();
    }
    }

}

Here is how you can pass JSON in c#:

 public static string postmyJSON(string xyz)
        {
            return JsonConvert.SerializeObject(new
            {
                activitytitle = "Notification from AzureDevOps",
                activitySubtitle = "BuildQueued",
                impactedarea = "http://dev.azure.com/myorg",
                description = descriptionforqueues
            });

        }

PATCH:

As you saw in POST API, we need to have patchjson needs to be passed to the function patchAdoapi. You can use the same postmyJSON for creating JSON for patch(purely depends on what kind of json you need) and also call the patch function simillar to postAdoapi: - myfunction(postmyJSON(xyz)pat)

public static void patchAdoapi(string pat, string link,string patchJson)
{
string responseBody = "";
string Url = link;
//HttpClient client = new HttpClient();
using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json-patch+json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
    ASCIIEncoding.ASCII.GetBytes(
    string.Format("{0}:{1}", "", pat))));
    var method = new HttpMethod("PATCH");
    var request = new HttpRequestMessage(method, Url)
    {
        Content = new StringContent("[" + patchJson + "]", Encoding.UTF8, "application/json-patch+json")
    };
    using (HttpResponseMessage response = client.SendAsync(request).Result)
    {
        response.EnsureSuccessStatusCode();
        responseBody = response.Content.ReadAsStringAsync().Result;
    }
    //var responseMessage = await client.PatchAsync(new Uri(Url), httpContent);
    } 
}

PATCH JSON : 

 public static string patchmyJSON(string xyz)
        {
            return JsonConvert.SerializeObject(new
            {
                activitytitle = "Notification from AzureDevOps",
                activitySubtitle = "BuildQueued",
                impactedarea = "http://dev.azure.com/myorg",
                description = descriptionforqueues
            });


        }

Now you just need to call these generic functions as required:

Here link refers to the API all the below functions. For example:

objGetApi is object of the class I created.

string listofProjects = objGetApi.getAdoapi(pat,Url = string.Format(
            @"https://dev.azure.com/{0}/_apis/projects?$top=500&api-version=5.1",
        accountName));

For POST:

objPostApi.postADOapi(pat,@"https://dev.azure.com/{0}/{1}/_apis/wit/workitems/${type}api-version=5.1",accountName),postJson);

For PATCH:

objPatchApi.patchADOapi(pat, projectsUrl = string.Format(@"https://vsaex.dev.azure.com/{0}/_apis/groupentitlements/{1}?api-version=5.1-preview.1", accountName, groupId), jsonProject);

Hope this helps!!





No comments:

Post a Comment