AidenWebb
AidenWebb

Reputation: 599

How can I properly generate URL parameters from nested JSON parameters in Python requests

I'm trying to use requests to pass a number of conditions to the Connectwise REST api. I'm trying to generate a URL like below

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

but I only seem to be able to generate this:

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

My payload looks like this:

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)

Where am I going wrong?

Upvotes: 0

Views: 4700

Answers (2)

AidenWebb
AidenWebb

Reputation: 599

I created a function to generate the conditions string for this.

    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

Upvotes: 0

Gaurav Ojha
Gaurav Ojha

Reputation: 1177

You could give this a try, if you are open to using 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)

Upvotes: 2

Related Questions