使用jira的api获取jql结果

Posted by Tesla9527 on April 20, 2022

需求背景: 所在公司,员工的任务和工时都登记在jira上,每个季度需要拉取数据。

接口说明

实现如下:

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
import requests
from requests.auth import HTTPBasicAuth
import json
import copy
import pandas as pd

url = "https://your-domain/rest/api/2/search"

auth = HTTPBasicAuth("your-account", "your-password")

headers = {"Accept": "application/json", "Content-Type": "application/json"}

users = ['zhangsan', 'lisi']

payload = {
  "expand": ["names", "schema", "operations"],
  "jql": "created >= 2022-01-01 AND created <= 2022-03-31 AND assignee in (user) ORDER BY created DESC",
  "maxResults": 1000,
  # "fieldsByKeys": False,
  "fields": [
    "issuetype",
    "summary",
    "key",
    "assignee",
    "timespent"
  ],
  "startAt": 0
}

print('开始获取数据...')

issues_total = []
for i in users:
   tmp = copy.deepcopy(payload)
   tmp['jql'] = tmp['jql'].replace('user', i)
   response = requests.post(url, data=json.dumps(tmp), headers=headers, auth=auth)
   # print(response.text)
   
   issues = list(map(lambda x: {'issuetype': x['fields']['issuetype']['name'],
   'summary': x['fields']['summary'],
   'key': x['key'],
   'assignee': x['fields']['assignee']['displayName'],
   'timespent': round(x['fields']['timespent'] / 3600, 2) if x['fields']['timespent'] is not None else 0}, 
   json.loads(response.text)['issues']))
   print(issues)
   issues_total += issues
print(len(issues_total))


final_df = pd.DataFrame(issues_total, columns=['issuetype','summary','key', 'assignee', 'timespent'])
final_df.to_excel("统计.xlsx")

备注:

使用该接口,一次最多只能返回1000条数据。哪怕jql查出来的数据超过了1000个。 如果遇到超过1000个的情况,比如2000个,可以分2次来下载,类似于分页。

第1次:

1
2
  "maxResults": 2000,
  "startAt": 0

第2次:

1
2
  "maxResults": 2000,
  "startAt": 1000