Jira REST API v3 在问题存在时抛出 404 错误(问题未找到)。

huangapple go评论75阅读模式
英文:

Jira REST API v3 throwing 404 Error (Issue not Found) when issue exists

问题

我能够在使用指定的工单号时添加评论,但当我从getIssues中使用jquery获取工单号时,我无法添加评论,它会抛出404错误。我对所有操作都使用相同的凭据。我正在使用Python作为我的语言。

我期望能够添加评论。我有类似的代码和评论体,运行得很好,但如果我选择这种方法,我必须在if/else语句中为每个文档项引入工单号和文档链接。所以我尝试使用下面的代码完成这个任务。

我已经尝试过以下方法:

  • 去除任何多余的空格,使用IssueID而不是Issue Key。

当我打印出工单信息时,我获得了正确的字符串格式的工单键。

我有正确的权限来执行这个操作。

代码:

def add_comment(ticket_info_dict, jira_url, api_token, jira_username):
    """
    Add a comment to a Jira ticket with documentation links based on the research type.

    Args:
        ticket_info_dict (dict): A dictionary containing ticket numbers as keys and research types as values.
        jira_url (str): The URL of the Jira instance.
        api_token (str): The API token for authentication with Jira.
        jira_username (str): The username for authentication with Jira.

    Returns:
        bool: True if all comments were added successfully, False otherwise.
    """
    # 遍历ticket_info_dict以处理每个工单及其研究类型
    for ticket_number, research_type in ticket_info_dict.items():
        # 设置用于添加评论到工单的API端点
        print(ticket_number)
        add_comment_endpoint = f"{jira_url}/rest/api/3/issue/{ticket_number}/comment"

        # 编码用于认证的凭据
        credentials = f"{jira_username}:{api_token}"
        base64_credentials = base64.b64encode(credentials.encode()).decode()

        headers = {
            "Authorization": f"Basic {base64_credentials}",
            "Content-Type": "application/json",
        }

        # 检查研究类型是否存在于文档字典中
        if research_type in documentation_dict:
            # 如果找到研究类型,请在评论中包括相应的文档链接
            documentation_links = documentation_dict[research_type]

            # 创建评论体,包括评论文本和文档链接
            comment_body = {
                "body": {
                    "content": [
                        {
                            "type": "paragraph",
                            "content": [
                                {"text": "This documentation relates to this research type:\n", "type": "text"},
                            ],
                        },
                        {
                            "type": "paragraph",
                            "content": [{"text": "Documentation Links:\n", "type": "text"}],
                        },
                        {
                            "type": "paragraph",
                            "content": [
                                {
                                    "text": f"-{doc_text}\n",
                                    "type": "text",
                                    "marks": [{"type": "link", "attrs": {"href": doc_link}}],
                                }
                                for doc_text, doc_link in documentation_links.items()
                            ],
                        },
                    ],
                    "type": "doc",
                    "version": 1
                },
                "properties": [
                    {
                        "key": "sd.public.comment",
                        "value": {
                            "internal": "true"
                        }
                    }
                ],
                "visibility": {
                    "type": "role",
                    "value": "Service Desk Team"
                }
            }

            try:
                # 进行POST请求以添加评论
                comment_response = requests.post(add_comment_endpoint, headers=headers, json=comment_body)

                # 检查请求是否成功(HTTP状态码为201)
                if comment_response.status_code == 201:
                    print(f"Comment added successfully to ticket {ticket_number}.")
                else:
                    print(f"Failed to add comment to ticket {ticket_number}. Status code: {comment_response.status_code}, Response: {comment_response.text}")

            except requests.exceptions.RequestException as e:
                # 处理与HTTP请求相关的异常
                print(f"Error: {e}")
                return False

        else:
            # 如果研究类型在文档字典中找不到,添加通用评论
            generic_comment = f"This ticket has a research type of '{research_type}' but no documentation links are available for this type."
            print(generic_comment)

    # 如果所有评论都成功添加,则返回True
    return True

使用以下函数获取工单信息:

def pull_ticket_info(jql_query, jira_url, api_token, jira_username):
    """
    Retrieve ticket information from Jira using a JQL query.

    Args:
        jql_query (str): The JQL query to search for tickets in Jira.
        jira_url (str): The URL of the Jira instance.
        api_token (str): The API token for authentication with Jira.
        jira_username (str): The username for authentication with Jira.

    Returns:
        str: The ticket number of research tickets. Returns None if no ticket is found.
    """

    ticket_info_dict = {}  # 用于存储工单号和研究类型的字典

    # 设置用于JQL搜索的API端点
    api_endpoint = f"{jira_url}/rest/api/3/search"

    # 编码用于认证的凭据
    credentials = f"{jira_username}:{api_token}"
    base64_credentials = base64.b64encode(credentials.encode()).decode()

    # 设置具有基于Base64编码的凭据的认证标头
    headers = {
        "Authorization": f"Basic {base64_credentials}"
    }

    # 设置JQL查询参数并指定要检索的字段
    params = {
        "jql": jql_query,
        # "fields": "key, summary, customfield_13810, customfield_13427"
    }

    try:
        # 进行GET请求以执行JQL搜索
        jql_response = requests.get(api_endpoint, headers=headers, params=params)
        api_response = jql_response.json()
        # print(api_response)

        if jql_response.status_code == 200:
            for issue in api_response["issues"]:
                ticket_id = issue["id"]
                ticket_number = issue["key"]
                research_type = issue["fields"].get("customfield_13427", {})
                research_type_value = research_type.get("value", "N/A")

                # 将工单号和研究类型添加到字典中
                ticket_info_dict[ticket_number] = research_type_value

            # 返回包含工单号和研究类型的字典
            return ticket_info_dict

       

<details>
<summary>英文:</summary>

I am able to add a comment when using a specified ticket number, but when I pull the ticket number from getIssues with a jquery, the I am not able to add a comment, it throws a 404 error. I&#39;m using the same credentials for it all. I am using python as my language.

I am expecting a comments to be added. I have similar code and comment_body that works just fine, but I have to introduce a ticket number and documentation link with each item of documentation through if/else statements if I go that route. So I&#39;m trying to get this completed through the code below instead.

I&#39;ve tried the following:
Stripping any excess space away, using the IssueID instead of Issue Key.

When I print out the ticket information, I get the correct key in string format.

I have the correct permissions for this

Code:

    def add_comment(ticket_info_dict, jira_url, api_token, jira_username):
        &quot;&quot;&quot;
        Add a comment to a Jira ticket with documentation links based on the research type.
    
        Args:
            ticket_info_dict (dict): A dictionary containing ticket numbers as keys and research types as values.
            jira_url (str): The URL of the Jira instance.
            api_token (str): The API token for authentication with Jira.
            jira_username (str): The username for authentication with Jira.
    
        Returns:
            bool: True if all comments were added successfully, False otherwise.
        &quot;&quot;&quot;
        # Iterate through the ticket_info_dict to process each ticket and its research type
        for ticket_number, research_type in ticket_info_dict.items():
            # Set up the API endpoint for adding comments to the ticket
            print(ticket_number)
            add_comment_endpoint = f&quot;{jira_url}/rest/api/3/issue/{ticket_number}/comment&quot;
    
            # Encode credentials for authentication
            credentials = f&quot;{jira_username}:{api_token}&quot;
            base64_credentials = base64.b64encode(credentials.encode()).decode()
    
            headers = {
                &quot;Authorization&quot;: f&quot;Basic {base64_credentials}&quot;,
                &quot;Content-Type&quot;: &quot;application/json&quot;,
            }
    
            # Check if the research type exists in the documentation dictionary
            if research_type in documentation_dict:
                # If the research type is found, include the corresponding documentation links in the comment
                documentation_links = documentation_dict[research_type]
    
                # Create the comment body including the comment_text and documentation links
                comment_body = {
                    &quot;body&quot;: {
                        &quot;content&quot;: [
                            {
                                &quot;type&quot;: &quot;paragraph&quot;,
                                &quot;content&quot;: [
                                    {&quot;text&quot;: &quot;This documentation relates to this research type:\n&quot;, &quot;type&quot;: &quot;text&quot;},
                                ],
                            },
                            {
                                &quot;type&quot;: &quot;paragraph&quot;,
                                &quot;content&quot;: [{&quot;text&quot;: &quot;Documentation Links:\n&quot;, &quot;type&quot;: &quot;text&quot;}],
                            },
                            {
                                &quot;type&quot;: &quot;paragraph&quot;,
                                &quot;content&quot;: [
                                    {
                                        &quot;text&quot;: f&quot;-{doc_text}\n&quot;,
                                        &quot;type&quot;: &quot;text&quot;,
                                        &quot;marks&quot;: [{&quot;type&quot;: &quot;link&quot;, &quot;attrs&quot;: {&quot;href&quot;: doc_link}}],
                                    }
                                    for doc_text, doc_link in documentation_links.items()
                                ],
                            },
                        ],
                        &quot;type&quot;: &quot;doc&quot;,
                        &quot;version&quot;: 1
                    },
                    &quot;properties&quot;: [
                        {
                            &quot;key&quot;: &quot;sd.public.comment&quot;,
                            &quot;value&quot;: {
                                &quot;internal&quot;: &quot;true&quot;
                            }
                        }
                    ],
                    &quot;visibility&quot;: {
                            &quot;type&quot;: &quot;role&quot;,
                            &quot;value&quot;: &quot;Service Desk Team&quot;
                        }
                }
    
                try:
                    # Make the POST request to add the comment
                    comment_response = requests.post(add_comment_endpoint, headers=headers, json=comment_body)
    
                    # Check if the request was successful (HTTP status code 201)
                    if comment_response.status_code == 201:
                        print(f&quot;Comment added successfully to ticket {ticket_number}.&quot;)
                    else:
                        print(f&quot;Failed to add comment to ticket {ticket_number}. Status code: {comment_response.status_code}, Response: {comment_response.text}&quot;)
    
                except requests.exceptions.RequestException as e:
                    # Handle exceptions related to the HTTP request
                    print(f&quot;Error: {e}&quot;)
                    return False
    
            else:
                # If the research type is not found in the documentation dictionary, add a generic comment
                generic_comment = f&quot;This ticket has a research type of &#39;{research_type}&#39; but no documentation links are available for this type.&quot;
                print(generic_comment)
    
        # Return True if all comments were added successfully
        return True

Getting the ticket info with this function:

    def pull_ticket_info(jql_query, jira_url, api_token, jira_username):
        &quot;&quot;&quot;
        Retrieve ticket information from Jira using a JQL query.
    
        Args:
            jql_query (str): The JQL query to search for tickets in Jira.
            jira_url (str): The URL of the Jira instance.
            api_token (str): The API token for authentication with Jira.
            jira_username (str): The username for authentication with Jira.
    
        Returns:
            str: The ticket number of research tickets. Returns None if no ticket is found.
        &quot;&quot;&quot;
    
        ticket_info_dict = {}  # Dictionary to store ticket number and research type
    
        # Set up the API endpoint for JQL search
        api_endpoint = f&quot;{jira_url}/rest/api/3/search&quot;
    
        # Encode credentials for authentication
        credentials = f&quot;{jira_username}:{api_token}&quot;
        base64_credentials = base64.b64encode(credentials.encode()).decode()
    
        # Set up the authentication headers with base64-encoded credentials
        headers = {
            &quot;Authorization&quot;: f&quot;Basic {base64_credentials}&quot;
        }
    
        # Set up the JQL query parameters and specify the fields you want to retrieve
        params = {
            &quot;jql&quot;: jql_query,
            # &quot;fields&quot;: &quot;key, summary, customfield_13810, customfield_13427&quot;
        }
    
        try:
            # Make the GET request to perform the JQL search
            jql_response = requests.get(api_endpoint, headers=headers, params=params)
            api_response = jql_response.json()
            # print(api_response)
    
            if jql_response.status_code == 200:
                for issue in api_response[&quot;issues&quot;]:
                    ticket_id = issue[&quot;id&quot;]
                    ticket_number = issue[&quot;key&quot;]
                    research_type = issue[&quot;fields&quot;].get(&quot;customfield_13427&quot;, {})
                    research_type_value = research_type.get(&quot;value&quot;, &quot;N/A&quot;)
    
                    # Add ticket number and research type to the dictionary
                    # ticket_info_dict[ticket_number] = research_type_value
                    ticket_info_dict[ticket_number] = research_type_value
    
    
                # Return the dictionary with ticket numbers and research types as key-value pairs
                return ticket_info_dict
    
            else:
                # Handle errors if the JQL search request is unsuccessful
                print(f&quot;JQL Error: {jql_response.status_code}, {api_response.get(&#39;errorMessages&#39;, &#39;Unknown error&#39;)}&quot;)
                return {}
    
        except requests.exceptions.RequestException as e:
            # Handle exceptions related to the HTTP request
            print(f&quot;Request Error: {e}&quot;)
            return {}

Each time I&#39;m getting this error:

Failed to add comment to ticket GCPS-9679. Status code: 404, Response: {&quot;errorMessages&quot;:\[&quot;Issue does not exist or you do not have permission to see it.&quot;\],&quot;errors&quot;:{}}

</details>


# 答案1
**得分**: 0

你尝试过使用jira python [package](https://pypi.org/project/jira/)吗

以下是一个应该适用于你的示例用于添加[comments](https://jira.readthedocs.io/examples.html#comments):

```python
from jira import JIRA

auth_jira = JIRA(jira_url, basic_auth=('你的电子邮件', 'API令牌'))
comment = auth_jira.add_comment('JIRA编号', '新评论')
comment.update(body='更新的评论内容')
英文:

Have you tried using the jira python package?

Here is an example that should work for you for adding comments:

from jira import JIRA
auth_jira = JIRA(jira_url, basic_auth=(&#39;*your_email*&#39;, &#39;*API token*&#39;))
comment = auth_jira.add_comment(&#39;*JIRA_number*&#39;, &#39;new comment&#39;)
comment.update(body=&#39;updated comment body&#39;)

huangapple
  • 本文由 发表于 2023年8月4日 05:15:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76831643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定