英文:
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'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'm trying to get this completed through the code below instead.
I'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):
"""
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.
"""
# 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"{jira_url}/rest/api/3/issue/{ticket_number}/comment"
# Encode credentials for authentication
credentials = f"{jira_username}:{api_token}"
base64_credentials = base64.b64encode(credentials.encode()).decode()
headers = {
"Authorization": f"Basic {base64_credentials}",
"Content-Type": "application/json",
}
# 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 = {
"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:
# 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"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:
# Handle exceptions related to the HTTP request
print(f"Error: {e}")
return False
else:
# If the research type is not found in the documentation dictionary, add a generic comment
generic_comment = f"This ticket has a research type of '{research_type}' but no documentation links are available for this type."
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):
"""
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 = {} # Dictionary to store ticket number and research type
# Set up the API endpoint for JQL search
api_endpoint = f"{jira_url}/rest/api/3/search"
# Encode credentials for authentication
credentials = f"{jira_username}:{api_token}"
base64_credentials = base64.b64encode(credentials.encode()).decode()
# Set up the authentication headers with base64-encoded credentials
headers = {
"Authorization": f"Basic {base64_credentials}"
}
# Set up the JQL query parameters and specify the fields you want to retrieve
params = {
"jql": jql_query,
# "fields": "key, summary, customfield_13810, customfield_13427"
}
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["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")
# 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"JQL Error: {jql_response.status_code}, {api_response.get('errorMessages', 'Unknown error')}")
return {}
except requests.exceptions.RequestException as e:
# Handle exceptions related to the HTTP request
print(f"Request Error: {e}")
return {}
Each time I'm getting this error:
Failed to add comment to ticket GCPS-9679. Status code: 404, Response: {"errorMessages":\["Issue does not exist or you do not have permission to see it."\],"errors":{}}
</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=('*your_email*', '*API token*'))
comment = auth_jira.add_comment('*JIRA_number*', 'new comment')
comment.update(body='updated comment body')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论