如何在Python中从URL获取GraphQL JSON数据?
解决GraphQL请求构造与查询问题
一、确认端点是否支持GraphQL
- 直接在浏览器访问目标URL:若为GraphQL端点,通常会返回GraphQL Playground/GraphiQL交互式界面,或返回
{"errors":[{"message":"Must provide query string."}]}这类JSON提示,说明是合法的GraphQL接口。 - 若返回404或非GraphQL相关内容,说明当前URL错误,需确认正确接口地址(多数服务会用
/graphql后缀,比如https://example.com/graphql)。
二、调整请求头与请求结构
你的基础请求框架没问题,但需注意几个细节:
- 请求头:
- 部分服务要求身份验证头(如
Authorization: Bearer <token>),若目标接口需要权限,必须添加对应认证信息。 - 你的代码中已设置
Content-Type: application/json和Accept: application/json,这部分符合标准GraphQL请求要求。
- 部分服务要求身份验证头(如
- 请求参数:
- 确保POST请求的JSON体为
{"query": "你的查询语句"};若需传递变量,需额外添加variables字段,示例:# 带变量的请求示例 query = """ query GetRace($raceId: ID!) { race(id: $raceId) { id name date } }""" variables = {"raceId": "123"} response = requests.post(url, json={'query': query, 'variables': variables}, headers=headers)
- 确保POST请求的JSON体为
三、编写有效的GraphQL查询
- 获取接口Schema:
- 若有GraphQL Playground,直接查看左侧的Schema文档(点击"Docs"按钮),里面会列出所有可查询字段、类型、参数。
- 若无Playground,可发送自省查询获取完整Schema:
introspection_query = """ query IntrospectionQuery { __schema { queryType { name } mutationType { name } types { name kind fields { name type { name kind ofType { name kind } } } } } }""" response = requests.post(url, json={'query': introspection_query}, headers=headers) print(response.json())
- 验证查询语法:
- 查询必须严格匹配Schema定义:字段名称要一致,嵌套结构正确,参数类型对应。比如你写的
races查询,若Schema要求分页参数(如first: 10),必须补充参数否则会报错。
- 查询必须严格匹配Schema定义:字段名称要一致,嵌套结构正确,参数类型对应。比如你写的
四、调试技巧
- 打印完整响应内容:即使状态码为200,也可能返回
errors字段,需针对性排查:if response.status_code == 200: data = response.json() if 'errors' in data: print("查询错误:", data['errors']) else: print(data) else: print("请求失败,状态码:", response.status_code) print("响应内容:", response.text) - 先用Postman等工具测试:手动构造POST请求并验证能获取数据后,再转成Python代码,降低调试难度。
内容的提问来源于stack exchange,提问作者Mary
相关产品推荐
相关产品推荐

