Python Requests Query Params List
When working with APIs, we often need to pass query parameters to filter or modify the results returned. In Python, the requests
library is commonly used for making HTTP requests to APIs. Here, we will explore how to pass query parameters using requests
in Python.
Passing Query Parameters as a Dictionary
The easiest way to pass query parameters is by using a dictionary. We can pass this dictionary as the params
argument in the requests.get
method as shown below:
import requests
url = 'https://api.example.com/search'
params = {'q': 'python', 'limit': 10}
response = requests.get(url, params=params)
print(response.json())
In the above example, we pass a dictionary {'q': 'python', 'limit': 10}
as query parameters to the https://api.example.com/search
endpoint. The response returned by the API will be in JSON format.
Passing Query Parameters as a List of Tuples
We can also pass query parameters as a list of tuples. Each tuple should contain the parameter key and value as shown below:
import requests
url = 'https://api.example.com/search'
params = [('q', 'python'), ('limit', 10)]
response = requests.get(url, params=params)
print(response.json())
In the above example, we pass a list of tuples [('q', 'python'), ('limit', 10)]
as query parameters to the https://api.example.com/search
endpoint. The response returned by the API will be in JSON format.
Passing Query Parameters with Special Characters
Sometimes, the query parameters may contain special characters such as spaces, commas, or slashes. In such cases, we need to ensure that the special characters are properly encoded. We can use the urllib.parse
library to encode the query parameters as shown below:
import requests
import urllib.parse
url = 'https://api.example.com/search'
params = {'q': 'python requests', 'limit': 10}
# encode query parameters
query_params = urllib.parse.urlencode(params)
# append encoded query parameters to URL
request_url = f"{url}?{query_params}"
response = requests.get(request_url)
print(response.json())
In the above example, we encode the query parameters using urllib.parse.urlencode
and append them to the URL using string formatting. The response returned by the API will be in JSON format.
Conclusion
That's it! We have explored how to pass query parameters using requests
in Python. Whether you prefer passing query parameters as a dictionary or a list of tuples, always ensure that any special characters are properly encoded.