python requests query params multiple values

Python Requests Query Params Multiple Values

Dealing with multiple values in query parameters is a common task in web development. In Python, the requests library provides a simple way to handle this situation.

Using the params Argument

The easiest way to pass multiple values in a query parameter is to use the params argument of the requests library's get() function. The params argument should be a dictionary where each key is the name of the parameter and each value is a list of values for that parameter. For example:


import requests

params = {'param1': ['value1', 'value2'], 'param2': ['value3']}
response = requests.get('http://example.com', params=params)

print(response.url)

This will send a GET request to http://example.com with the query parameters:

  • param1=value1
  • param1=value2
  • param2=value3

The response.url attribute will contain the full URL that was sent to the server.

Using a String with Multiple Values

Some APIs may require that multiple values be passed as a comma-separated string instead of a list. In this case, we can simply concatenate the values into a single string before passing them to the params argument. For example:


import requests

params = {'param1': 'value1,value2', 'param2': 'value3'}
response = requests.get('http://example.com', params=params)

print(response.url)

This will send a GET request to http://example.com with the query parameters:

  • param1=value1,value2
  • param2=value3

Note that we did not use a list for the 'param1' value, but instead used a string with the values separated by commas.