Failing to use the Jira API to add attachments to an existing Jira issue

Ron Barak March 30, 2023

I'm trying to add attachments to an existing Jira issue — using the Jira API.

I followed the API documentation, but still, I get error 415 from Jira.
Any suggestions on what I may be doing wrong:

$ python3 add_attachment_to_jira_ticket_for_SO.py attachment_contents = b'This is a sample attachment, to test attachments in Jira.\n'
Error adding attachment: status code 415 ('')

This is my script (running on Python 3.4.10):

$ cat add_attachment_to_jira_ticket_for_SO.py
"""
Add attachment to an existing Jira ticket
"""

from authorisation import auth
import json
import requests


def get_json_config_data(json_config_path):
with open(json_config_path) as json_data:
dict_data = json.load(json_data)
headers = dict_data["headers"]

return headers


def add_attachment_to_jira(headers, auth, issue_key, files):
jira_api_endpoint = 'https://corp.atlassian.net/rest/api/2/issue/{issue_key}/attachments'.format(issue_key=issue_key)

response = requests.post(
jira_api_endpoint,
headers=headers,
auth=auth,
files=files,)

if response.status_code == 200:
print('Attachment added successfully!')
else:
print("Error adding attachment: status code {status_code} ('{text}')".format(status_code=response.status_code, text=response.text))


if __name__ == "__main__":
json_config_path = "json_data.json"
headers = get_json_config_data(json_config_path)

# set the issue key and comment text
issue_key = 'ONSIP-261'

file_path = "./sample_attachment_SO.txt"
file_name = "sample_attachment_SO.txt"

with open(file_path, "rb") as f:
attachment_contents = f.read()
print("attachment_contents =",attachment_contents)

files = {
"file": (file_name, attachment_contents, "application-type"),
}

# set the headers and data for the Jira API request
json_config_path = "json_data.json"
headers = get_json_config_data(json_config_path)

add_attachment_to_jira(headers, auth, issue_key, files=files)

 

 

1 answer

1 vote
Ron Barak March 30, 2023

Thanks for the pointer, @Nicolas Grossi

However, my problem was in a wrong "Content-Type" in my headers. Once I fixed that, I was able to upload attachments to Jira with the API.

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
CLOUD
PRODUCT PLAN
STANDARD
TAGS
AUG Leaders

Atlassian Community Events