Update/delete confluence page using python code
Asked Answered
K

4

7

I want to update a confluence page through the Confluence REST API. Please suggest a code snippet with which I can update the page through its "Page Title".

Assume my confluence site is https://wiki.mydomain.com, the page title is TEST and the space is TST.

Kermis answered 10/5, 2017 at 9:46 Comment(0)
W
12

You can also use the Confluence module of the Atlassian Python API to update / delete Confluence pages from Python. This is basically a wrapper for the REST API to provide a simple interface.

Installation via pip:

pip install atlassian-python-api

Usage:

from atlassian import Confluence

conf_site = 'https://wiki.mydomain.com'
conf_user = 'username'
conf_pass = 'password'

page_title = 'TEST' 
page_space = 'TST'

# connect to Confluence 
conf = Confluence(url=conf_site, username=conf_user, password=conf_pass)

# resolve page ID
page_id = conf.get_page_id(page_space, page_title)

# optonal: get current page content, in case you want to base your editing on that
page = conf.get_page_by_id(page_id, expand='body.storage')
page_content = page['body']['storage']['value']

# new page content
page_content =  '<p>This is the new updated text of the page</p>'

# update page with new content
conf.update_page(page_id, page_title, page_content)

Or, to delete:

# This method removes a page, if it has recursive flag, method removes including child pages
conf.remove_page(page_id, status=None, recursive=False)
Wichman answered 18/3, 2021 at 22:54 Comment(0)
R
3

Updating existing Wiki page on Confluence using Python 3. See this answer to know how to create a page using Python.

Make sure that ID is correct of the page you are trying to update. And if you are going to change the title, make sure that the same title does not appear on another page in the same space.

import requests
import json
from requests.auth import HTTPBasicAuth

# set auth token and get the basic auth code
auth_token = "{TOKEN}"
basic_auth = HTTPBasicAuth('{email you use to log in}', auth_token)

# Set the title and content of the page to create
page_title = 'My Existing Page'
page_html = '<p>This is the text that needs to be updated</p>'

page_id = {Page ID}
space_key = '{SPACE KEY}'

# get the confluence home page url for your organization {confluence_home_page}
url = '{confluence_home_page}/rest/api/content/{Page ID}'

# Request Headers
headers = {
    'Content-Type': 'application/json;charset=iso-8859-1',
}

# Request body
data = {
    'id': {Page ID}
    'type': 'page',
    'title': page_title,
    'space': {'key':space_key},
    'body': {
        'storage':{
            'value': page_html,
            'representation':'storage',
        }
    },
    'version': {
        'number': 2,
        'when': '2017-10-06T15:16:17.501-04:00'}
}
# the version number should be the immediate next version number of the existing document.

# We're ready to call the api
try:

    r = requests.put(url=url, data=json.dumps(data), headers=headers, auth=basic_auth)

    # Consider any status other than 2xx an error
    if not r.status_code // 100 == 2:
        print("Error: Unexpected response {}".format(r))
    else:
        print('Page Updated!')

except requests.exceptions.RequestException as e:

    # A serious problem happened, like an SSLError or InvalidURL
    print("Error: {}".format(e))
Rotter answered 20/12, 2019 at 6:43 Comment(0)
D
2

Below is the Python code for deleting a Confluence Page using Page Title.

def deletePageByTitle(title):
checkPageExistsData = requests.get("https:\wiki.mydomain.com/rest/api/content?title=" + title + "&expand=history", headers={'Content-Type':'application/json'}, auth=('yourConfluenceUser', 'yourConfluecePassword'))
    requestJson = checkPageExistsData.json()
    pageId = ''
    if requestJson["results"] != None:
        for results in requestJson["results"]:
            pageId = (results["id"])
            requests.delete("https:\wiki.mydomain.com/rest/api/content/"+pageId+"", headers={'Content-Type':'application/json'}, auth=('yourConfluenceUser', 'yourConfluecePassword'))
        print('Page deleted')
    else:
        print('Page does not exist')

For your case this function will be called like: deletePageByTitle("TEST"). Hope this helps!

Diphthong answered 26/3, 2019 at 7:57 Comment(1)
Don't you need confluence sandwiched between https:\wiki.mydomain.com and /rest/api/content?title=?Sandi
B
1

As you can see in Atlassian Documentations (here) you can update pages via following curl:

curl -u admin:admin -X PUT -H 'Content-Type: application/json' -d'{"id":"3604482","type":"page",
"title":"new page","space":{"key":"TST"},"body":{"storage":{"value":
"<p>This is the updated text for the new page</p>","representation":"storage"}},
"version":{"number":2}}' http://localhost:8080/confluence/rest/api/content/3604482 | python -mjson.tool

However it works with Page ID rather than a page Title. You can grab the id with following:

curl -u admin:admin -X GET "http://localhost:8080/confluence/rest/api/content?title=myPage%20Title
&spaceKey=TST&expand=history" | python -mjson.tool

Just as a side note since you look like a new user, here we won't provide code snippet and you need to tell us what you have tried and what is your problem actually. I would recommend you to take a look at How do I ask a good question as well :-)

Bound answered 10/5, 2017 at 14:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.