4

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)?

ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
Casey
  • 2,611
  • 6
  • 34
  • 60

1 Answers1

10

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"}
ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110