Search code examples
c#.netrestjira

Converting JIRA API cURL to c# http request


I have a cURL with which I connect to Atlassian JIRA API and search an issue with JQL, filtering issues by project name and status.

This is the cURL command, which works pretty well:

curl -u JIRAUSER:JIRATOKEN -X POST --data '{ "jql": "project = \"QA\" AND status=\"To Do\" " }' -H "Content-Type: application/json" https://jiraserver.atlassian.net/rest/api/2/search

I'm trying to re-build it on C# with httpclient POST method. The code is given below:

static async System.Threading.Tasks.Task Main(string[] args)
        {
            using (var httpClient = new HttpClient())
            {
                using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://jiraserver.atlassian.net/rest/api/2/search"))
                {
                    var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("JIRAUSER:JIRA TOKEN"));
                    request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");

                    request.Content = new StringContent("{ \"jql\": \"project = \"QA\" AND status = \"To Do\" }");
                    request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    var response = await httpClient.SendAsync(request);

                    Console.WriteLine(response);


                }
            }

        }

response returns the following error:

StatusCode: 400, ReasonPhrase: '', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent

And in System.Diagnostics.Debug.Write I get the following error:

error CS0428: Cannot convert method group 'Write' to non-delegate type 'object'. Did you intend to invoke the method?

Please give me some hint.


Solution

  • I'd suggest using JIRA SDK to interact with your JIRA instance -> https://bitbucket.org/farmas/atlassian.net-sdk/src/master/.

    Basically, set of steps are

    1) initiate jira client:
    
        var jiraClient = Jira.CreateRestClient(<jiraURL>, <jiraUserName>, <jiraUserPwd>);
    
    2) connect to jira, and pull based on search criteria:
    
         var jql =  "project = QA + " AND status in (To Do)";
        IEnumerable<Atlassian.Jira.Issue> jiraIssues = AsyncTasker.GetIssuesFromJQL(jiraClient, jql, 999);
    
    3) then, you can enumerate in the pulled issues
    
        ...
        foreach(var issue in jiraIssues)
        {   
            /*      
            ... for example, some of the available attributes are:
    
                        issue.Key.Value
                        issue.Summary
                        issue.Description
                        issue.Updated
                        String.Format("{0}/browse/{1}", jiraURL.TrimEnd('/') , issue.Key.Value)
            ...
            */
        }                    
    
    • on the side note, it's advisable not to use using(... = new HttpClient()){....}