You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在API返回字典列表时循环分页并追加结果

如何处理Atlassian API分页,合并所有字典列表结果

我在Python中调用Atlassian的API,接口返回的response.json()是字典列表格式,但受分页机制限制,每次只能通过startAt参数获取最多50条结果。尝试循环追加结果失败,之前仅处理过返回单个字典的API,不熟悉字典列表的处理方式。

初始代码:

import requests
from requests.auth import HTTPBasicAuth
import json
import datetime
from datetime import date    

url = "https://xxxxx.atlassian.net/rest/api/3/users/search?startAt=0"
auth = HTTPBasicAuth("Email ID", "API Token")
headers = {"Accept": "application/json"}
response = requests.request("GET", url, auth=auth, headers=headers)
data = response.json()
type(data)

接口返回结果示例:

[
  {"AccountID": 12345, "Status": "Open"},
  {"AccountID": 456, "Status": "Open"},
  {"AccountID": 898, "Status": "Open"}
]

解决方案

核心思路是初始化空列表存储所有结果,循环请求不同偏移量的分页数据,将每页的字典列表合并到总列表中,直到无更多数据返回。

完整实现代码:

import requests
from requests.auth import HTTPBasicAuth

# 基础配置
base_url = "https://xxxxx.atlassian.net/rest/api/3/users/search"
auth = HTTPBasicAuth("你的邮箱ID", "你的API Token")
headers = {"Accept": "application/json"}

all_users = []  # 存储所有用户数据的总列表
start_at = 0
page_size = 50  # Atlassian API默认每页50条,可通过maxResults调整

while True:
    # 构造分页请求参数
    request_params = {"startAt": start_at, "maxResults": page_size}
    response = requests.get(base_url, auth=auth, headers=headers, params=request_params)
    response.raise_for_status()  # 捕获HTTP请求错误
    
    current_page_data = response.json()
    if not current_page_data:  # 当前页无数据,结束循环
        break
    
    all_users.extend(current_page_data)  # 合并当前页数据到总列表
    start_at += page_size  # 更新偏移量,获取下一页

# 验证结果
print(f"总计获取到 {len(all_users)} 条用户数据")
print("前3条数据示例:", all_users[:3])

关键细节说明

  • 列表合并方式:使用extend()而非append(),前者会把当前页的每个字典元素加入总列表,后者会把整个当前页列表作为单个元素插入,这是之前循环追加失败的常见原因。
  • 分页终止条件:当接口返回空列表时,说明已获取全部数据,直接跳出循环。
  • 参数规范:通过params字典传递分页参数,比直接拼接URL更安全,避免字符编码问题。
  • 错误处理:response.raise_for_status()会在请求返回4xx/5xx状态码时抛出异常,便于排查权限、URL错误等问题。

内容的提问来源于stack exchange,提问作者Data Analyst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 04:13:19