简体   繁体   English

如何正确调用 Jira Rest API

[英]How to properly call the Jira Rest API

I have been trying to set up a function to call the Jira Rest API with parameters to then be able to create an issue in Jira.我一直在尝试设置一个函数来调用带有参数的 Jira Rest API,然后能够在 Jira 中创建问题。 To call the Rest API Jira provided a documentation which describes how to call the Rest APIhere .调用 Rest API Jira 提供了一份文档,描述了如何在此处调用 Rest API。 On the website, the CURL and the JSON are given.在网站上,给出了 CURL 和 JSON。 Here is the REST API request I tried to set up in C# :这是我尝试在C#设置的 REST API 请求:

curl -D- -u peno.ch:yourpassword -H "Content-Type: application/json" --data @foo.json https://jira-test.ch.*******.net/rest/api/latest/issue/

This is the foo.json payload:这是 foo.json 负载:

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

I have tried to Implement a HttpWebRequest to call the Rest API and also I have tried with a WebClient .我试图实现一个HttpWebRequest来调用 Rest API,我也尝试过使用WebClient None of them worked.他们都没有工作。 I kind of understand the API but I think I haven't got the parameters right, I think I am doing something wrong there.我有点了解 API,但我认为我没有正确设置参数,我认为我在那里做错了。 Also on Google, I didn't find any solution.同样在谷歌上,我没有找到任何解决方案。

I am getting an Internal error from Jira when executing the function below.执行以下函数时,我收到来自 Jira 的内部错误。 (no specific information on the error) (没有关于错误的具体信息)

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

    var client = new WebClient();        
    string data = JsonConvert.SerializeObject(jiraApiObject);
    client.Credentials = new System.Net.NetworkCredential(user, password);
    client.UploadStringTaskAsync(url, data);
}

This is my JiraApiObject which exactly translates to the Json payload shown above.这是我的 JiraApiObject,它完全转换为上面显示的 Json 负载。

public class JiraApiObject
{
    public class Project
    {
        public string key { get; set; }
    }

    public class Issuetype
    {
        public string name { get; set; }
    }

    public class Fields
    {
        public Project project { get; set; }
        public Issuetype issuetype { get; set; }
        public string summary { get; set; }
    }

    public class RootObject
    {
        public Fields fields { get; set; }
    }
}

When I execute the CURL command on the console everything works I just couldn't figure out how to structure the WebClient or HttpWebRequest .当我在控制台上执行 CURL 命令时,一切正常,我只是不知道如何构建WebClientHttpWebRequest

I find that many Jira users face this problem and there is not a single good solution I could find on the internet.我发现很多 Jira 用户都面临这个问题,而且我在互联网上找不到一个好的解决方案。 I hope to find a solution and help others who have the same problem by raising this question.我希望通过提出这个问题找到解决方案并帮助其他有同样问题的人。

In general, its best practice (many a times necessary) that you explicitly specify the content type, HTTP method, etc whenever you make a REST API call. 通常,最佳做法是(最好多次)在每次进行REST API调用时都明确指定内容类型,HTTP方法等。 Also, I prefer using HttpWebRequest object to make REST API calls. 另外,我更喜欢使用HttpWebRequest对象进行REST API调用。 Here is the re-factored code: 这是重构后的代码:

public static void CreateJiraRequest(Chat 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();
            // Do what you need to do with the response here.
        }
    }
    catch (Exception ex)
    {
        // Handle your exception here
        throw ex;
    }
}

Also, ensure that the JSON structure after serialising JiraApiObject matches the required JSON structure of the API in question. 另外,请确保序列化JiraApiObject之后的JSON结构与所需的API JSON结构匹配。 For your convenience, you may want to consider using JsonObject and JsonProperty attributes on the classes and properties so that you name them the way the API expects. 为了方便起见,您可能需要考虑在类和属性上使用JsonObjectJsonProperty属性,以便按API期望的方式命名它们。

Following is your backend RESTapi code in C#以下是 C# 中的后端 RESTapi 代码

    public class JiraController : ApiController
    {
        public IJiraInterface repository = new JiraRepository();

        [Route("api/Jira/getTickets")]
        [HttpGet]
        [EnableCors(origins: "http://localhost:8080", headers: "*", methods: "*")]
        public Object getTickets(string startAt,string maxResults)
        {
            return repository.getTickets(startAt,maxResults);
        }

        [Route("api/Jira/createTicket")]
        [HttpPost]
        [EnableCors(origins: "http://localhost:8080", headers: "*", methods: "*")]
        public Object createTicket(IssueModel issueModelObject)
        {
            return repository.createTicket(issueModelObject);
        }
    }

This is how your interface class should look这就是您的接口类的外观

public interface IJiraInterface
{
    Object getTickets(string startAt,string maxResults);
    Object createTicket(IssueModel issueObj);
}

This is how entity looks like这就是实体的样子

    public class IssueModel
    {
      #region Properties
      public string RequesterType { get; set; }
      public string Summary { get; set; }
      public string Description { get; set; }
      public string Email { get; set; }
      #endregion
    }

This is your repository class这是您的存储库类

public class JiraRepository : IJiraInterface
{
      public JiraRepository()
      {
      }
      public Object getTickets(string startAt, string maxResults)
      {
        string URL = "https://YOUR_SUB_DOMAIN.atlassian.net/rest/api/3/search?jql=project=PROJECT_NAME"+ 
            "&startAt="+ startAt + 
            "&maxResults=" + maxResults;
        
        HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(URL);
        httpWReq.PreAuthenticate = true;
        httpWReq.Headers.Add("Authorization", "Basic " + getAuthorization());
        httpWReq.Headers.Add("Access-Control-Allow-Origin", "*");
        

        HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string responseString = reader.ReadToEnd();
        return JObject.Parse(responseString);
      }
      public Object createTicket(IssueModel issueObj)
      {
        string URL = "https://YOUR_SUB_DOMAIN.atlassian.net/rest/api/3/issue";

        HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(URL);
        httpWReq.ContentType = "application/json";
        httpWReq.PreAuthenticate = true;
        httpWReq.Method = "POST";
        using (var streamWriter = new StreamWriter(httpWReq.GetRequestStream()))
        {
            string json =
            "{\n  \"update\": {},\n  \"properties\" : [\n      {\n          \"key\":\"requestType\",\n          \"value\":\""+ issueObj.RequesterType + "\"\n      }\n  ],\n\n  \"fields\": {\n    \"summary\": \"" + issueObj.Summary + "\",\n    \"issuetype\": {\n      \"id\": \"10203\"\n    },\n    \"project\": {\n      \"id\": \"10512\"\n    },\n  \"description\": {\n      \"type\": \"doc\",\n      \"version\": 1,\n      \"content\": [\n        {\n          \"type\": \"paragraph\",\n          \"content\": [\n            {\n              \"text\": \"" + issueObj.Description + "\",\n              \"type\": \"text\"\n            }\n          ]\n        }\n      ]\n    },\n    \"priority\": {\n      \"id\": \"10000\"\n    }\n  }\n}";
            streamWriter.Write(json);
        }
        httpWReq.Headers.Add("Authorization", "Basic " + getAuthorization());
        httpWReq.Headers.Add("Access-Control-Allow-Origin", "*");

        try
        {
            HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string responseString = reader.ReadToEnd();
            return JObject.Parse(responseString);
        }
        catch(Exception e)
        {
            return JObject.Parse(e.Message);
        }

      }
    
      public string getAuthorization()
      {
        var username = "YOUR_JIRA_USERNAME_KEY";
        var password = "YOUR_JIRA_PASSWORD_KEY";
        return Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));

      } 
}

For frontend gothrough the following link https://stackoverflow.com/a/70280761/4921412对于前端,请通过以下链接https://stackoverflow.com/a/70280761/4921412

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM