Requests: passing the same query parameter using params

Question:

As explained in the requests documentation, we can use a dict to provide query parameters to a GET request, in order to not format the url manually.

However, the API I use requires to pass the same argument several time, for example, writing queries like endpoint/?department=92&department=93.

Of course, I can’t build a dict with duplicate key. But I don’t want to bother to format my query manually.

Any best practice for this?

Asked By: David Dahan

||

Answers:

as specified at the doc you provided , you can do that by putting the multiple values of the same parameter as a value of your specific key, like :

import requests

test_params = {'param1': ['VALUES1', 'VALUE2']}
r = requests.get('https://httpbin.org/get', params=test_params)

print(r.url)

output :

https://httpbin.org/get?param1=VALUES1&param1=VALUE2
Answered By: mrCopiCat

Having checked the source code I have established that the documentation isn’t aligned with the comments in the source and the actual behaviour.

You could actually pass a list of tuples like this:

params = [('department', 92), ('department', 93)]

requests.get(URL, params=params)
Answered By: Vlad