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

Python处理GET请求大JSON:获取指定记录并存入MongoDB

实现方案

1. 核心逻辑说明

你需要先完成两步操作:

  1. 利用接口返回的next分页地址循环拉取所有页的数据,直到next为null即可拿到全部5000条活动记录
  2. 拉取完全量数据后,通过pymongo将数据写入MongoDB即可

2. 依赖安装

首先安装需要的第三方库:

pip install requests pymongo

3. 完整实现代码

import requests
from pymongo import MongoClient

# 原有鉴权类保留
class BearerAuth(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        r.headers["authorization"] = "Bearer " + self.token
        return r

# 配置参数
API_TOKEN = "myTokenWhichIsHiddenHere" # 替换为自己的接口token
INITIAL_URL = "https://api.predicthq.com/v1/events/?q=collections"
MONGO_URI = "mongodb://localhost:27017/" # 本地MongoDB默认地址,如有自定义可修改
MONGO_DB = "event_database"
MONGO_COLLECTION = "concert_events"

# 分页拉取全量数据
all_events = []
current_url = INITIAL_URL
while current_url:
    resp = requests.get(current_url, auth=BearerAuth(API_TOKEN))
    resp.raise_for_status() # 请求失败时自动抛出异常,方便排查问题
    resp_json = resp.json()
    # 合并当前页的活动记录
    all_events.extend(resp_json.get("results", []))
    # 获取下一页地址,无下一页时循环终止
    current_url = resp_json.get("next")

# 此时all_events已存储全部5000条记录,要访问第1000条直接取 all_events[999] 即可(索引从0开始)

# 写入MongoDB
mongo_client = MongoClient(MONGO_URI)
db = mongo_client[MONGO_DB]
collection = db[MONGO_COLLECTION]
insert_res = collection.insert_many(all_events)
print(f"成功写入{len(insert_res.inserted_ids)}条记录到MongoDB")

注意事项

  • 若接口存在请求频率限制,可在循环末尾添加time.sleep(1)做延迟,使用前需导入time模块
  • 若需要保存接口返回的完整JSON结构而非仅活动记录,可将每次请求的resp_json存入列表后再写入MongoDB
  • 终端打印长内容自动截断是Python的默认行为,全量数据拉取完成后直接通过索引即可访问对应位置的记录,无需依赖终端打印全量内容

内容的提问来源于stack exchange,提问作者Bruce B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:36:02