Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary type params in query string

I'm trying to feed the following URL structure into requests:

https://inventory.data.gov/api/action/datastore_search?resource_id=8ea44bc4-22ba-4386-b84c-1494ab28964b&filters={"City":"Las Vegas","State":"NV"}

I wanted to break up the URL into params, but am having a terrible time getting the filters portion to work properly. I ended up using the below code:

url = 'https://inventory.data.gov/api/action/datastore_search?' \
        'resource_id=8ea44bc4-22ba-4386-b84c-1494ab28964b&' \
        'filters={"City":"' + city + '","State":"' + state + '"}'

resp = requests.get(url=url)
print resp.url

Does anybody know how I can modify this to work with requests like requests.get(url=url, params=params)?

like image 262
Casey Avatar asked Jul 22 '26 15:07

Casey


1 Answers

That looks like JSON data. You can convert a Python object to a JSON string with the json module:

import json
import requests

city = 'Las Vegas'
state = 'NV'

filters = {
    'City': city,
    'State': state
}
params = {
    'resource_id': '8ea44bc4-22ba-4386-b84c-1494ab28964b',
    'filters': json.dumps(filters)
}

response = requests.get('http://www.example.com/', params=params)

This sends a request to:

http://www.example.com/?filters=%7B%22City%22%3A+%22Las+Vegas%22%2C+%22State%22%3A+%22NV%22%7D&resource_id=8ea44bc4-22ba-4386-b84c-1494ab28964b

where

%7B%22City%22%3A+%22Las+Vegas%22%2C+%22State%22%3A+%22NV%22%7D

is the URL-encoded version of

{"City": "Las Vegas", "State": "NV"}
like image 80
ThisSuitIsBlackNot Avatar answered Jul 25 '26 06:07

ThisSuitIsBlackNot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!