如何通过Redmine REST API获取聚合后的工时条目?
首先得明确:Redmine的内置工时报表端点(/time_entries/report)并不是为REST API设计的,它默认面向Web界面访问,所以即使携带API密钥或基础认证,也会跳转到登录页,这是你遇到问题的核心原因。下面是几个可行的解决思路,按推荐优先级排序:
1. 用官方time_entries API获取数据后本地聚合(最可靠)
虽然你提到优先用内置聚合,但官方的/time_entries.json端点是稳定支持API密钥认证的,而且可以通过过滤参数减少返回数据量,之后在本地做轻量聚合完全可行。
示例请求(过滤指定日期的工时)
curl -X GET \ 'https://my_redmine/time_entries.json?spent_on=2020-01-01' \ -H 'X-Redmine-API-Key: my_api_key'
如果需要范围日期,可以用spent_on=><2020-01-01|2020-01-31这样的格式,更多过滤参数可参考Redmine官方文档。
本地聚合示例(Python)
拿到返回的JSON后,按用户+日期维度求和很简单:
import json import requests api_key = "your_api_key" url = "https://my_redmine/time_entries.json?spent_on=2020-01-01" headers = {"X-Redmine-API-Key": api_key} response = requests.get(url, headers=headers) time_entries = response.json()["time_entries"] # 按用户ID和日期分组聚合 aggregated_data = {} for entry in time_entries: user_id = entry["user"]["id"] spent_date = entry["spent_on"] key = (user_id, spent_date) if key not in aggregated_data: aggregated_data[key] = { "user": user_id, "hours": 0.0, "spent_on": spent_date } aggregated_data[key]["hours"] += entry["hours"] # 转换为列表格式输出 result = list(aggregated_data.values()) print(json.dumps(result, indent=2))
这个方案的优点是完全基于官方支持的API,认证稳定,不受Redmine版本更新影响;如果数据量很大,记得用page参数分页获取(Redmine默认每页25条)。
2. 模拟Web会话获取内置聚合报表(临时方案)
如果一定要用Redmine内置的聚合结果,可以先模拟Web登录获取会话Cookie,再请求CSV报表:
步骤1:获取登录Cookie
curl -X POST \ 'https://my_redmine/login' \ -d 'username=your_username&password=your_password' \ -c cookies.txt
步骤2:用Cookie请求CSV报表
curl -X GET \ 'https://my_redmine/time_entries/report.csv?columns=day&criteria[]=user' \ -b cookies.txt
注意:这种方式依赖Redmine的Web登录机制,版本更新可能会失效,而且用用户名密码登录不如API密钥安全,不推荐作为长期解决方案。
3. 安装Redmine插件扩展API聚合能力(长期进阶方案)
有些第三方Redmine插件会扩展API功能,支持直接返回聚合后的工时数据。比如部分时间跟踪类插件或自定义报表插件,你可以在Redmine的插件市场找合适的插件,安装后使用其提供的API端点来获取聚合数据。
这个方案的优点是不用自己处理聚合逻辑,但需要有Redmine服务器的管理权限来安装插件,且依赖插件的维护状态。
内容的提问来源于stack exchange,提问作者Pierre de LESPINAY

