如何在Python中使用requests库传递JSON查询获取API响应?
解决requests传递JSON查询参数的问题
问题根源
- 使用
requests.post时,你将JSON序列化后的字符串传给了params参数,这会把它解析为URL查询参数,而非请求体中的JSON数据,导致服务器无法识别你的查询条件。 - 使用
requests.get时,params会把嵌套字典转为扁平的URL键值对,格式不符合API对JSON查询的解析要求,因此也无法生效。
正确的POST请求实现
Postman能成功,说明API接受POST请求并以请求体传递JSON查询。直接使用requests的json参数传入字典即可,requests会自动完成JSON序列化并设置正确的Content-Type(也可保留自定义headers):
import requests query_params = { "query": { "exists": { "field": "user_id" } }, "size": 10000 } headers = {"X-API-Key": api_key} response = requests.post(url, json=query_params, headers=headers) print(response.json())
如果需要手动序列化JSON,需将序列化后的字符串传给data参数而非params:
import json import requests # 定义query_params和headers response = requests.post(url, data=json.dumps(query_params), headers=headers)
若API支持GET请求传递JSON查询
部分API允许将JSON字符串作为特定URL参数的值传递(比如?q=<JSON字符串>),此时需手动序列化后传入:
import json import requests query_params = { "query": { "exists": { "field": "user_id" } }, "size": 10000 } headers = {"X-API-Key": api_key, "Content-Type": "application/json"} response = requests.get(url, params={"q": json.dumps(query_params)}, headers=headers) print(response.json())
注:这种GET传递复杂JSON的场景较少见,多数API会要求用POST请求处理复杂查询。
内容的提问来源于stack exchange,提问作者Rumi
相关产品推荐
相关产品推荐

