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

Twitter基础付费计划:修复用户信息查询API的400请求错误

修复Twitter API用户信息获取的400错误及connect_to_endpoint函数优化

错误根源分析

  • ids参数格式错误:你将ids设置为带方括号的字符串'[4919451, 14151086]',Twitter API无法正确解析这种格式,需改为无括号的逗号分隔字符串或直接传入ID列表。
  • user.fields参数格式错误:字段列表末尾多了一个逗号,导致API识别到空字段值,触发无效参数报错。

修改后的完整代码

import requests
import json
import config

bearer_token = config.bearer_token
url = "https://api.twitter.com/2/users"

# 修正参数格式
params = {
    'ids': "4919451,14151086",  # 也可直接传列表:[4919451, 14151086]
    'user.fields': 'name,description,location,public_metrics,username,created_at'
}


def bearer_oauth(r):
    r.headers["Authorization"] = f"Bearer {bearer_token}"
    r.headers["User-Agent"] = "v2UserLookupPython"
    return r


def connect_to_endpoint(url, params):
    # 自动修正参数格式问题
    if 'user.fields' in params and params['user.fields'].endswith(','):
        params['user.fields'] = params['user.fields'].rstrip(',')
    
    response = requests.get(url, auth=bearer_oauth, params=params)
    print(f"请求状态码: {response.status_code}")
    
    if response.status_code != 200:
        error_info = response.json()
        error_detail = error_info.get('detail', '未知错误')
        raise Exception(f"请求失败: {response.status_code} - {error_detail}")
    
    return response.json()


def main():
    # 原代码中create_url()未定义,直接使用全局url变量
    json_response = connect_to_endpoint(url, params)
    # 若你有flatten函数请确保已提前定义
    # json_response = flatten(json_response)
    d = json.dumps(json_response, indent=4, sort_keys=True)
    print(d)
    return d
    

if __name__ == "__main__":
    main()

关键修改说明

  1. 参数修正:
    • 将ids改为无括号的逗号分隔字符串,或直接传入整数列表(requests会自动转换为API兼容的格式)。
    • 删除user.fields末尾的逗号,确保所有字段均为API支持的有效取值。
  2. connect_to_endpoint函数优化:
    • 用更简洁的requests.get()替代requests.request("GET")。
    • 增加自动修正逻辑,提前处理user.fields末尾多余逗号的问题。
    • 优化错误提示,提取API返回的具体错误详情,便于快速排查问题。
  3. main函数修复:原代码中create_url()未定义,直接使用全局url变量,若你有自定义URL生成逻辑可替换回去。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:28:23