0%

interact with jira/confluence rest api with python

How to interact Jira/Confluence REST API with Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import requests
import json

# Jira API endpoint and authentication
jira_url = "https://your-jira-instance/rest/api/2/search"
jira_token = "your-jira-personal-access-token"

# Confluence API endpoint and authentication
confluence_url = "https://your-confluence-instance/rest/api/content"
confluence_token = "your-confluence-personal-access-token"

# Step 1: Get stories from Jira
jira_headers = {
"Authorization": f"Bearer {jira_token}",
"Content-Type": "application/json"
}

jira_params = {
"jql": "labels = release",
"maxResults": 100
}

response = requests.get(jira_url, headers=jira_headers, params=jira_params)
jira_stories = response.json()["issues"]

# Step 2: Create a new Confluence page
confluence_headers = {
"Authorization": f"Bearer {confluence_token}",
"Content-Type": "application/json"
}

confluence_payload = {
"type": "page",
"title": "Release Stories",
"space": {
"key": "your-space-key"
},
"body": {
"storage": {
"value": "<h2>Release Stories</h2>",
"representation": "storage"
}
}
}

response = requests.post(confluence_url, headers=confluence_headers, json=confluence_payload)
confluence_page_id = response.json()["id"]

# Step 3: Add the stories to the Confluence page
for story in jira_stories:
story_title = story["fields"]["summary"]
story_description = story["fields"]["description"]

confluence_payload["body"]["storage"]["value"] += f"<h3>{story_title}</h3><p>{story_description}</p>"

response = requests.put(f"{confluence_url}/{confluence_page_id}", headers=confluence_headers, json=confluence_payload)

# Step 4: Verify the response
if response.status_code == 200:
print("Page created successfully!")
else:
print("Failed to create the page.")

Here is another example with Excel export support

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import requests
from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill, Font
import datetime
from datetime import timedelta

start_date = '2021-05-29'

def get_issue_list():
headers = {
'Authorization': 'Basic YOUR_TOKEN'}
project = 'YOUR_PROJECT'
issue_type = 'Story'
sprint = 'YOUR_SPRINT_ID'
order_by = 'key'
order_by_type = 'ASC'
jql = f'project = {project} AND issuetype = {issue_type} AND Sprint = {sprint} AND created >= {start_date} ORDER BY {order_by} {order_by_type}'
params = {
'jql': jql,
'fields': ['summary', 'created', 'status', 'priority']
}
url = f'https://jira.xxx.com/rest/agile/1.0/sprint/{sprint}/issue'
r = requests.get(url, headers=headers, params=params)
return r.json()


def parse_response(response):
issue_list = []
i = 1
for issue in response['issues']:
created = str(issue['fields']['created']).split('T')[0]
due_date = datetime.date.fromisoformat(created) + timedelta(2)
issue_item = {'id': i, 'issue key': issue['key'],
'summary': issue['fields']['summary'],
'status': issue['fields']['status']['name'],
'priority': issue['fields']['priority']['name'],
'created': created,
'due date': due_date}
issue_list.append(issue_item)
i += 1
return issue_list


def issue_mapping(issue_list):
new_issue_list = []

priority_mapping = {
'Low': 'Minor',
'Medium': 'Minor',
'High': 'Major',
}

status_mapping = {
'To Do': 'Open',
}

for issue in issue_list:
if issue['priority'] in priority_mapping:
issue['priority'] = priority_mapping[issue['priority']]
if issue['status'] in status_mapping:
issue['status'] = status_mapping[issue['status']]
new_issue_list.append(issue)
return new_issue_list


def write_to_excel(issue_list):
issue_list = issue_mapping(issue_list)
workbook = Workbook()
sheet = workbook.active
sheet.title = 'jira issue'
sheet.append(['id', 'issue key', 'summary', 'status', 'priority', 'created', 'due date'])

# set color for header
for rows in sheet.iter_rows(min_row=1, max_row=1):
for cell in rows:
cell.fill = PatternFill(fgColor="002060", fill_type="solid")
cell.font = Font(color="FFFFFF")

for issue in issue_list:
sheet.append(list(issue.values()))
# fill in color
my_red = Color(rgb='00B050')
my_fill = PatternFill(patternType='solid', fgColor=my_red)
for row_cells in sheet.iter_rows(min_row=1, max_row=sheet.max_row):
if row_cells[3].value == 'Done':
row_cells[3].fill = my_fill

file_name = 'report_issue_list_' + start_date + '.xlsx'
workbook.save(file_name)


response = get_issue_list()
issue_list = parse_response(response)
write_to_excel(issue_list)
print("Done")

Reference:

https://developer.atlassian.com/cloud/jira/platform/rest/v3/intro/

The Jira Software Cloud REST API

JIRA 7.12.0