Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Issue Jira REST API (400 Bad Request)

The Problem

I am trying to create a REST API call using a HttpWebRequest to our in-house Jira server. But somehow I keep getting back a (400) Bad Request error. I have also tried with WebClient and other ways but I just don't seem to find the correct approach. Any suggestions?

URL is correct

User is correct

Password is correct

JSON Data also correct

There must be another way of accessing the remote server right? I have been searching but not seem to find a solution.

My Code

public static void CreateJiraRequest(JiraApiObject.RootObject jiraApiObject)
{
    string url = "https://jira-test.ch.*********.net/rest/api/latest/issue/";
    string user = "peno.ch";
    string password = "**********";

    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/json";
    request.Credentials = new System.Net.NetworkCredential(user, password);

    string data = JsonConvert.SerializeObject(jiraApiObject);

    using (var webStream = request.GetRequestStream())
    using (var requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
    {
        requestWriter.Write(data);
    }

    try
    {
        var webResponse = request.GetResponse();
        using (var responseReader = new StreamReader(webResponse.GetResponseStream()))
        {
            string response = responseReader.ReadToEnd();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

JSON

{
    "fields": {
       "project":
       {
          "key": "FOO"
       },
       "summary": "Test the REST API",
       "issuetype": {
          "name": "Task"
       }
   }
}

Exception

The exception occurs when entering the try block on request.GetResponse();

Additional information: The remote server returned an error: (400) Bad Request.

Visit the Jira Wiki here

like image 665
Mrs KOODA Avatar asked Jan 20 '26 13:01

Mrs KOODA


1 Answers

#Solution#

The problem in the code above is that Jira requires encoded credentials. Without encoding the credentials the Jira server will return a 400 Bad Request error with no specific information.

I have written two new functions one for the API request and one for the Encoding of the credentials.

#API Call#

public static string PostJsonRequest(string endpoint, string userid, string password, string json)
    {
        // Create string to hold JSON response
        string jsonResponse = string.Empty;
        
        using (var client = new WebClient())
        {
            try
            {
                client.Encoding = System.Text.Encoding.UTF8;
                client.Headers.Set("Authorization", "Basic " + GetEncodedCredentials(userid, password));
                client.Headers.Add("Content-Type: application/json");
                client.Headers.Add("Accept", "application/json");
                var uri = new Uri(endpoint);
                var response = client.UploadString(uri, "POST", json);
                jsonResponse = response;
            }
            catch (WebException ex)
            {
                // Http Error
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
                    var statusCode = (int)wrsp.StatusCode;
                    var msg = wrsp.StatusDescription;
                    throw new HttpException(statusCode, msg);
                }
                else
                {
                    throw new HttpException(500, ex.Message);
                }
            }
        }

        return jsonResponse;
    }

#Encoding Function#

private static string GetEncodedCredentials(string userid, string password)
{
    string mergedCredentials = string.Format("{0}:{1}", userid, password);
    byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
    return Convert.ToBase64String(byteCredentials);
}

Additional Notes: Jira API is case sensitive so for "POST" If you do Fields, Summary, Project it won't work it has to be fields, summary, project

like image 84
Mrs KOODA Avatar answered Jan 23 '26 01:01

Mrs KOODA