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

使用aiohttp请求GraphQL API返回productClientOnlyProduct errors错误求助

问题

我正在学习aiohttp/asyncio相关技术,编写了如下代码尝试获取GraphQL API的响应(因篇幅移除了cookies、headers和query内容),但始终收到错误提示,而使用requests库执行相同请求却能正常运行。

代码示例

import aiohttp
import asyncio

async def fetch_data():
    url = 'https://apionline.homedepot.com/federation-gateway/graphql'
    params = {'opname': 'productClientOnlyProduct'}
    cookies = {

    }
    
    headers = {

    }
    
    json_data = {
        'operationName': 'productClientOnlyProduct',
        'variables': {
            'skipSubscribeAndSave': False,
            'skipFavoriteCount': False,
            'skipPaintDetails': True,
            'skipSpecificationGroup': False,
            'skipInstallServices': True,
            'skipKPF': False,
            'itemId': '203077142',
            'storeId': '504',
            'zipCode': '78664',
        },
        'query': ''
    }

    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(url, params=params, cookies=cookies, headers=headers, json=json_data, timeout=30) as response:
                if response.status != 200:
                    print(f"Error: HTTP status code {response.status}")
                    print(await response.text())
                    return None
                return await response.text()
        except aiohttp.ClientError as e:
            print(f"An error occurred: {e}")

async def main():
    response_text = await fetch_data()
    if response_text is not None:
        print(response_text)

if __name__ == '__main__':
    asyncio.run(main())

错误信息

Error: HTTP status code 206
{
   "data":{
      "productClientOnlyProduct":null
   },
   "error":[{
      "message":"productClientOnlyProduct errors"
   }]
}
解决建议
  • 补全GraphQL查询语句:代码中query字段为空字符串,这是核心问题。GraphQL API必须接收完整的查询语句才能执行操作,把requests中使用的完整query内容填入该字段。
  • 对齐请求头参数:requests和aiohttp的默认请求头存在差异(比如User-Agent、Accept、Accept-Encoding等),将requests中使用的所有请求头完整复制到aiohttp的headers字典中,尤其是User-Agent字段,很多API会做校验。
  • 核对cookies完整性:确保aiohttp的cookies字典包含requests中使用的所有cookie键值对,格式完全一致,无遗漏或拼写错误。
  • 排查206状态码原因:206代表“部分内容”,可能是请求头中的Accept范围设置不符。尝试显式设置headers['Accept'] = '*/*',对齐requests的Accept配置。
  • 对比请求细节:开启aiohttp的调试日志,查看发送的完整请求内容(头、cookie、请求体),和requests的请求做逐字段对比,定位差异点。添加日志代码:
    import logging
    logging.basicConfig(level=logging.DEBUG)
    
  • 检查请求体格式:确认aiohttp发送的JSON结构和requests完全一致,比如variables中的字段是否有多余逗号(Python允许但JSON不允许,不过aiohttp会自动处理,但仍需注意)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 22:25:13