I am using a Python script to extract Confluence cloud space and permission data via the API

Steve Test January 23, 2024

Hi, I have a requirement to extract all space data and group permissions for all global confluence spaces on my instance. I have written a Python script, from various sources on the internet but I cannot get it to work. I would really appreciate if someone could cast an eye over it and let me have any feedback on where I am going wrong.

I need the script to:

  • Pull in Space data for all global spaces
  • Pull in group permission data for each one
  • Print the results to a csv file

Here is my script so far:

import requests
import csv
import base64

# Confluence API credentials and domain
api_token = 'my api token'
email = 'my email'
domain = 'my domain'

# Basic Authentication
auth_string = f'{email}:{api_token}'
token = base64.b64encode(auth_string.encode()).decode('utf-8')
headers = {
'Authorization': f'Basic {token}',
'Accept': 'application/json'
}

# Get space data
def get_global_spaces():
url = f'https://{domain}/wiki/api/v2/spaces?type=global'

response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()['results']
else:
print(f"Failed to fetch spaces: {response.status_code}")
return []

# Get permissions data for each space
def get_group_permissions(space_id):
url = f'https://{domain}/wiki/api/v2/spaces/{space_id}/permissions'

response = requests.get(url, headers=headers)

if response.status_code == 200:
permissions = response.json()['permissions']

return [perm for perm in permissions if perm['principal']['type'] == 'group']
else:
print(f"Failed to fetch permissions for space ID {space_id}: {response.status_code}")
return []

# Write the results
def main():
spaces = get_global_spaces()
data = []

for space in spaces:
space_id = space['id']
space_name = space['name']
group_permissions = get_group_permissions(space_id)
for perm in group_permissions:
data.append([space_id, space_name, perm['operation']['key'], perm['operation']['operation']])

with open('confluence_spaces_group_permissions.csv', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['Space ID', 'Space Name', 'Group Name', 'Permission'])
writer.writerows(data)

print("Data exported to confluence_spaces_group_permissions.csv")

if __name__ == "__main__":
main()

1 answer

0 votes
Mohamed Benziane
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
August 31, 2024

Hi,

do you have an error message ?

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
CLOUD
PERMISSIONS LEVEL
Product Admin
TAGS
AUG Leaders

Atlassian Community Events