Description:
You often want to send some sort of data in the URL%u2019s 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 of strings, 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:
Code:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('https://httpbin.org/get', params=payload)
print(r.url)
Output:
>>>https://httpbin.org/get?key1=value1&key2=value2
- Note that any dictionary key whose value is
None
will not be added to the URL%u2019s query string. - You can also pass a list of items as a value:
For example:
Code:
import requests
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('https://httpbin.org/get', params=payload)
print(r.url)
Output:
>>>https://httpbin.org/get?key1=value1&key2=value2&key2=value3
Comments