在python GET(Method)请求中发送Json(包含布尔值/数字)数据

问:是否可以通过GET请求发送json数据?

我想传递一些过滤器参数以从数据库读取结果

params = {'is_coming_soon': False, 'is_paid': True, 'limit': 100, 'skip': 0}
headers = {'content-type': 'application/json'}
response = requests.get(url=url, headers=headers, params=params)

在服务器端,我将所有值作为字符串接收,

我该如何请求获取正确的布尔值而不是字符串一.

最佳答案

要发送json有效负载,请使用data或json参数而不是params.首先使用json.dumps将字典转换为json,然后根据需要仔细检查转换:

import json

payload = json.dumps(params)
print(payload)  # '{"is_coming_soon": false, "is_paid": true, "limit": 100, "skip": 0}'

response = requests.get(url=url, headers=headers, data=payload)

另外,您可以像这样调试请求调用:

import requests
import logging

from http.client import HTTPConnection
# from httplib import HTTPConnection  # Python 2

HTTPConnection.debuglevel = 1

logging.basicConfig() 
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

response = requests.get(url=url, headers=headers, data=payload)