Passing Parameters In URLs

You often want to send some sort of data in the URL’s query string. If you were constructing the URL by hand, this data would be given as key/value pairs in the URL after a question mark, e.g. httpbin.org/get?key=val. Requests allows you to provide these arguments as a dictionary, using the params keyword argument. As an example, if you wanted to pass key1=value1 and key2=value2 to httpbin.org/get, you would use the following code:

  1. >>> payload = {'key1': 'value1', 'key2': 'value2'}
  2. >>> r = requests.get('http://httpbin.org/get', params=payload)

You can see that the URL has been correctly encoded by printing the URL:

  1. >>> print(r.url)
  2. http://httpbin.org/get?key2=value2&key1=value1

Note that any dictionary key whose value is None will not be added to the URL’s query string.

You can also pass a list of items as a value:

  1. >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
  2. >>> r = requests.get('http://httpbin.org/get', params=payload)
  3. >>> print(r.url)
  4. http://httpbin.org/get?key1=value1&key2=value2&key2=value3