How to upload files to Confluence via Python API

Joe Osborne
Contributor
July 20, 2021

I am attempting to upload zip files to Confluence via Python, but no matter what request I send, I keep getting an error 502 response.  

 

data = {"comment": "This is data"}

files = {'file': open('File.zip', 'rb')}

content = session.post('https://site.com/rest/api/content/2229443766/child/attachment ', data=data, files=files)

print(content.status_code)
print(content.text)

3 answers

1 accepted

1 vote
Answer accepted
Joe Osborne
Contributor
July 20, 2021

Needed to add a header:

 

headers = {"X-Atlassian-Token": "nocheck"}

0 votes
Timo Drost
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
April 30, 2024

Hi Claudio,

I have something like this: (it includes a response to your terminal)

def upload_file_as_attachment(page_id, file_path, auth):
    """ Uploads a file as an attachment to a Confluence page, with enhanced error handling. """
    url = f"https://YOURURL.atlassian.net/wiki/rest/api/content/{page_id}/child/attachment"
    headers = {"X-Atlassian-Token": "no-check"}
    try:
        with open(file_path, 'rb') as file_data:
            mime_type = mimetypes.guess_type(file_path)[0] or 'application/octet-stream'
            files = {'file': (os.path.basename(file_path), file_data, mime_type)}
            response = requests.post(url, headers=headers, files=files, auth=auth)
            if response.status_code == 200:
                print(f"Attachment uploaded successfully with ID {response.json()['results'][0]['id']}")
            else:
                print(f"Failed to upload attachment: {response.status_code} {response.text}")
    except IOError:
        print(f"Error: File not found - {file_path}")
    except Exception as e:
        print(f"An unexpected error occurred: {str(e)}")
0 votes
Claudio Andres Torres Burgos
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
April 19, 2023

Could you upload your full solution, please?

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events