query params in python requests

Query Params in Python Requests

When making HTTP requests using Python's requests library, we often need to add query parameters to the URL. Query parameters are used to provide additional information to the server about the request being made. For example, when searching for a product on an e-commerce website, the search query can be passed as a query parameter.

Add Query Params to URL

We can add query parameters to the URL by passing them as a dictionary to the `params` parameter of the `get()` method.


import requests

url = 'https://example.com/search'
params = {'q': 'python'}

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

print(response.url)
# Output: https://example.com/search?q=python
    

Multiple Query Params

We can pass multiple query parameters by adding them to the dictionary.


import requests

url = 'https://example.com/search'
params = {'q': 'python', 'lang': 'en'}

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

print(response.url)
# Output: https://example.com/search?q=python&lang=en
    

Customizing Query Param Separator

By default, requests use the `&` character as the separator for query parameters. We can customize it using the `separator` parameter.


import requests

url = 'https://example.com/search'
params = {'q': 'python', 'lang': 'en'}

response = requests.get(url, params=params, separator=';')

print(response.url)
# Output: https://example.com/search?q=python;lang=en