Python can't use request to upload an attachment to an issue

I am trying to use Python and Request module to upload an attachment (.PNG file, about 72KB) to an Issue by calling this REST API attachments:

    headers = {
        "X-Atlassian-Token": "no-check",
        "Content-Type": "multipart/form-data;boundary=----SILVERPEAKTESTEXECUTIONSSUMMARY"
    }

    files = {"file": open(attachment,"rb")}

    jurl = JIRA_BASE_URL + JIRA_ISSUE_PATH + JIRA_ISSUE_KEY + JIRA_ISSUE_ATTACHMENT
    result = requests.post(jurl, auth=(speakConfig["username"], speakConfig["password"]), headers=headers, files=files)
    ...

Here, jurl is https://silverpeak.atlassian.net/rest/api/2/issue/TOOL-1175/attachments

but I always get the response:

    result.status_code: 200
    result.txt: []

and this attachment is not uploaded, how to resolve this issue?

This REST API says:

  The name of the multipart/form-data parameter that contains attachments must be "file"

How should I set this parameter in Python script?

Would anyone like to give me some helps?

Any helps would be appreciated!

Thanks.

The key to getting this to work was in the multipart-encoded files:

import requests

# Parse authentication credentials
credentials  = requests.auth.HTTPBasicAuth('USERNAME','PASSWORD')

# JIRA required header
headers = { 'X-Atlassian-Token': 'no-check' }

# Setup multipart-encoded file
files = [ ('file', (filename, open('/path/to/file.txt','rb'), mime_type)) ]

# Run request
r = requests.post(url, auth=credentials, files=files, headers=headers)

https://2.python-requests.org/en/master/user/advanced/#post-multiple-multipart-encoded-files


This is basically a copy+paste of my Stack Overflow post.

1 Like