Bootstrap FreeKB - Atlassian - List Confluence Spaces using Python
Atlassian - List Confluence Spaces using Python

Updated:   |  Atlassian articles

This assumes you have already created an API token and have a base 64 encoded string of the API token. Check out my article FreeKB - Atlassian - Create API token.

Using the base64 encoded string, you should now be able to submit a GET request and get JSON response. For example, to GET Confluence Spaces.

More GET request examples here => The Confluence Cloud REST API

import requests

response = requests.get(
  f"https://acme.atlassian.net/wiki/api/v2/spaces",
  headers={ "Accept": "application/json", "Authorization": "Basic <your base64 encoded API token>" }
)
print(response.json())

 

Something like this should be returned.

{
  "results": [
    {
      "spaceOwnerId": "557058:73a84e24-c4ab-4afc-b7ca-0050d3ef0f96",
      "createdAt": "2024-10-13T20:11:24.561Z",
      "authorId": "557058:73a84e24-c4ab-4afc-b7ca-0050d3ef0f96",
      "homepageId": "15335585",
      "icon": null,
      "description": null,
      "status": "current",
      "name": "my first space",
      "key": "A1",
      "id": "15335479",
      "type": "global",
      "_links": {
        "webui": "/spaces/A1"
      },
      "currentActiveAlias": "A1"
    }
  ],
  "_links": {
    "next": "/wiki/api/v2/spaces?cursor=eyJpZCI6MTUzMzU0NzksInNwYWNlU29ydE9yZGVyIjp7ImZpZWxkIjoiSUQiLCJkaXJlY3Rpb24iOiJBU0NFTkRJTkcifSwic3BhY2VTb3J0T3JkZXJWYWx1ZSI6MTUzMzU0Nzl9",
    "base": "https://acme.atlassian.net/wiki"
  }
}

 

By default, the first 25 spaces will be returned. Notice in the above output there is a "next" endpoint. The "next" endpoint can be used to return the next 25 spaces. In this scenario, it probably makes sense to use a while loop to loop through 25 spaces at a time.

import requests

def return_json(endpoint):
  response = requests.get(
    f"https://acme.atlassian.net{endpoint}",
    headers={ "Accept": "application/json", "Authorization": "Basic <your base64 encoded API token>" }
  )
  return response.json()

match = False
endpoint = "/wiki/api/v2/spaces"

while match == False:
  return_json_response = return_json(endpoint)

  # KeyError will be raised if '_links' does not contain 'next' meaning there isn't a "next" endpoint
  # In this scenario, let's set last_page to True
  try:
    endpoint = return_json_response['_links']['next']

  except KeyError:
    last_page = True
    pass  

  for item in return_json_response['results']:
    print(f"item['name'] = {item['name']}")

  if last_page == True:
    print("reached the last page")
    break

 

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 450821 in the box below so that we can be sure you are a human.