Python Requests Query Params
When making HTTP requests using Python, it is common to pass query parameters in the URL. These parameters are used to filter, sort or manipulate the data that is returned from the server. The Python Requests library makes it easy to include query parameters in your requests.
Using the params parameter
The simplest way to include query parameters in a request is by using the params
parameter of the requests function. The params
parameter accepts a dictionary object where the keys are the parameter names and the values are the parameter values.
import requests
params = { 'param1': 'value1', 'param2': 'value2' }
response = requests.get('https://example.com/api', params=params)
print(response.url)
In the example above, we are passing two query parameters, 'param1' and 'param2', with values 'value1' and 'value2' respectively. The requests.get
function adds these parameters to the URL as a query string.
Passing multiple values for a parameter
Sometimes, you may need to pass multiple values for a single parameter. In this case, you can use a list or tuple as the value of the parameter key in the dictionary.
import requests
params = { 'param1': ['value1', 'value2'], 'param2': 'value3' }
response = requests.get('https://example.com/api', params=params)
print(response.url)
In the example above, we are passing two values for parameter 'param1'. The resulting URL contains the query string param1=value1¶m1=value2¶m2=value3
.
Encoding query parameters
The Python Requests library automatically encodes query parameters in a URL-safe format. This means that special characters, such as spaces or ampersands, are replaced with their corresponding percent-encoded values.
import requests
params = { 'search': 'hello world' }
response = requests.get('https://example.com/api', params=params)
print(response.url)
In the example above, the search parameter contains a space character. The Python Requests library automatically replaces this with its percent-encoded value, resulting in the query string search=hello%20world
.
Conclusion
Passing query parameters in Python Requests is a simple and effective way to filter, sort or manipulate data returned from a server. By using the params
parameter, you can easily include query parameters in your requests and encode them correctly. Remember that query parameters are case-sensitive, so make sure to use the correct parameter names when making requests.