如何从Python请求中的嵌套JSON参数中正确生成URL参数

时间:2016-10-27 13:11:26

标签: python rest python-3.x python-requests

我正在尝试使用请求将一些条件传递给Connectwise REST API。我正在尝试生成如下所示的网址

/company/configurations/?pageSize=1000&conditions=id=83500 and type/name="Printer" and name="TEST API PRINTER"

但我似乎只能生成这个:

/company/configurations/?pageSize=1000&conditions=id&conditions=type/name&conditions=name

我的有效载荷如下所示:

parameters = {}
    parameters['conditions'] = {}
    parameters['pageSize'] = 1000
    if db_rid:
        parameters['conditions']['id'] = 83500
    if type_name:
        parameters['conditions']['type/name'] = "Printer"
    if name:
        parameters['conditions']['name'] = "TEST API PRINTER"
requests.get(APIurl, params=parameters)

我哪里错了?

2 个答案:

答案 0 :(得分:1)

如果您愿意使用urllib.urlencode -

,可以尝试一下
conditions = {"id": 83500, "type/name": "Printer", "name": "TEST API PRINTER"} 
query = {"pageSize": 1000, "conditions": conditions}
params = urllib.urlencode(query)
final_url = str(APIurl) + "&" + str(params)
response = requests.get(url=final_url)

答案 1 :(得分:0)

我创建了一个函数来为此生成条件字符串。

    def _add_condition(self, string, add_string, add_value):
    if string == '':
        if type(add_value) is not str:
            result = '{}={}'.format(add_string, add_value)
        else:
            result = '{}="{}"'.format(add_string, add_value)
    else:
        if type(add_value) is not str:
            result = '{} and {}={}'.format(string, add_string, add_value)
        else:
            result = '{} and {}="{}"'.format(string, add_string, add_value)
    print(result)
    return result