python requests get pass parameters

Python requests get pass parameters

Passing parameters in Python requests is a common task when working with APIs or websites that require additional information. The GET method is typically used to retrieve data from a server, and it allows the inclusion of parameters in the URL.

Using the params parameter

The easiest way to pass parameters in a GET request using Python requests is using the params parameter. This parameter takes a dictionary of key-value pairs that represent the parameters to be included in the URL.


import requests

url = "https://example.com/api"
params = {"param1": "value1", "param2": "value2"}

response = requests.get(url, params=params)

In this example, we create a dictionary params that contains two parameters: param1 and param2. We then pass this dictionary to the params parameter of the requests.get() function. The resulting URL will be:

https://example.com/api?param1=value1¶m2=value2

Passing a list of values for a single parameter

Sometimes, you may need to pass a list of values for a single parameter, such as when filtering data. In this case, you can pass a list as the value for the parameter key in the params dictionary.


import requests

url = "https://example.com/api"
params = {"filter": ["value1", "value2"]}

response = requests.get(url, params=params)

The resulting URL will be:

https://example.com/api?filter=value1&filter=value2

Note that the same parameter key is used twice in the URL, with a different value each time.

Using a string as the value for a parameter

In some cases, you may need to pass a parameter with a value that is not a string. For example, you may need to include a boolean value or an integer. In this case, you can convert the value to a string and include it in the params dictionary.


import requests

url = "https://example.com/api"
params = {"param1": str(123), "param2": str(True)}

response = requests.get(url, params=params)

The resulting URL will be:

https://example.com/api?param1=123¶m2=True

Using a tuple as the value for a parameter key

If you need to pass multiple values for a single parameter, you can use a tuple as the value for the parameter key in the params dictionary.


import requests

url = "https://example.com/api"
params = {"param1": ("value1", "value2", "value3")}

response = requests.get(url, params=params)

The resulting URL will be:

https://example.com/api?param1=value1¶m1=value2¶m1=value3

Note that the same parameter key is used three times in the URL, with a different value each time.

These are some of the ways you can pass parameters in Python requests. Depending on the API or website you are working with, you may need to use one or more of these methods to include all the necessary information in your GET request.