JIRA, REST and .NET

I haven't seen much in the way of .NET code for talking to JIRA via REST so I thought I'd post some code from a spike I've been fooling around with.

In this example I'm deserializing JSON into known objects - that I created earlier using Visual Studio's EDIT > Paste Special > Paste JSON As Classes command - but you could just go with dynamic objects if you know the properties you want (though that's slower of course).

namespace JiraRestSpike
{
    using System;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using Newtonsoft.Json;
 
    public class Program
    {
        public static void Main(string[] args)
        {
            // Check out: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+APIs
 
            GetIssue();
            ////CreateIssue();
        }
 
        private static async void GetIssue()
        {
            // retrieve details for issue 6 specifically
            var issueUrl = "http://yourjirainstance.jiraoncloud.com/rest/api/latest/issue/PROJECTNAME-6.json";
 
            var httpClient = GetHttpClient();
            var response = httpClient.GetAsync(issueUrl).Result;
 
            var content = await response.Content.ReadAsStringAsync();
 
            // deserialize into an object we generated earlier - or use DeserializeObject
            var issue = JsonConvert.DeserializeObject<Issue>(content);
 
            // display some props
            Console.WriteLine("Key: " + issue.key);
            Console.WriteLine("Project: " + issue.fields.project.name);
            Console.WriteLine("Description: " + issue.fields.summary);
            Console.WriteLine("Type: " + issue.fields.issuetype.name);
            Console.WriteLine("Created: " + issue.fields.created);
            Console.WriteLine("Reporter: " + issue.fields.reporter.displayName);
            Console.WriteLine("Priority: " + issue.fields.priority.name);
            Console.WriteLine("Description: " + issue.fields.description);
            Console.WriteLine("Status: " + issue.fields.status.name);
 
            Console.ReadKey();
        }
 
        public static async void CreateIssue()
        {
            // validate the shape of your JSON at http://jsonlint.com/
            var data = @"{
    ""fields"": {
        ""project"": {
            ""key"": ""PROJECTNAME""
        },
        ""summary"": ""My Test Issue"",
        ""description"": ""Created programmatically"",
        ""issuetype"": {
            ""name"": ""Story""
        }
    }
}";
 
            // this is the URl for posting issues
            var postUrl = "http://yourjirainstance.jiraoncloud.com/rest/api/2/issue/";
 
            // this line is very important!
            var encodedData = new StringContent(data, Encoding.UTF8, "application/json");
 
            var httpClient = GetHttpClient();
            var response = httpClient.PostAsync(postUrl, encodedData).Result;            
 
            var content = await response.Content.ReadAsStringAsync();
 
            if (response.IsSuccessStatusCode)
            {
                var issue = JsonConvert.DeserializeObject<Issue>(content);
                Console.WriteLine(issue.key + " created");
            }
            else
            {
                Console.WriteLine(Convert.ToInt32(response.StatusCode) + " - " + response.ReasonPhrase);
 
                var error = JsonConvert.DeserializeObject<Error>(content);
 
                foreach (var errorMessage in error.errorMessages)
                {
                    Console.WriteLine(errorMessage);
                }                
            }
 
            Console.ReadKey();
        }
 
        private static HttpClient GetHttpClient()
        {
            // need to get through the proxy
            var handler = new HttpClientHandler();
            handler.AllowAutoRedirect = true;
            handler.Proxy = new WebProxy("http://yourproxy:8080"truenullCredentialCache.DefaultNetworkCredentials);
 
            // need to pass a valid username + password to JIRA
            var jiraCredentials = UTF8Encoding.UTF8.GetBytes("yourUsername:yourPassword");
 
            var httpClient = new HttpClient(handler);
            httpClient.MaxResponseContentBufferSize = int.MaxValue;
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic"Convert.ToBase64String(jiraCredentials));
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 
            return httpClient;
        }
    }
}

Comments