python requests module query parameters

Python Requests Module Query Parameters

When working with APIs, it is often necessary to send additional information along with your request. One common way to do this is by using query parameters. The Python Requests module makes it easy to add query parameters to your requests.

Adding Query Parameters

To add query parameters to a request, simply pass a dictionary of key-value pairs to the params parameter of the get() method. For example:

import requests

payload = {'q': 'python requests module', 'page': 2}
r = requests.get('https://www.example.com/search', params=payload)

print(r.url)

In this example, we are searching for "python requests module" on the second page of results. The resulting URL will be:

https://www.example.com/search?q=python+requests+module&page=2

As you can see, the query parameters have been added to the URL.

Multiple Ways to Add Query Parameters

In addition to passing a dictionary to the params parameter, you can also add query parameters using a string or a list of tuples.

  • String: If you have a string of key-value pairs in the format key1=value1&key2=value2, you can pass it directly to the params parameter.
  • List of Tuples: If you have a list of tuples in the format [('key1', 'value1'), ('key2', 'value2')], you can pass it to the params parameter.

For example:

import requests

# Using a string
payload = 'q=python+requests+module&page=2'
r = requests.get('https://www.example.com/search', params=payload)

# Using a list of tuples
payload = [('q', 'python requests module'), ('page', 2)]
r = requests.get('https://www.example.com/search', params=payload)

Conclusion

The Python Requests module makes it easy to add query parameters to your requests. By passing a dictionary, string, or list of tuples to the params parameter of the get() method, you can include additional information with your request.