Python Requests Library Query Parameters
If you are working with APIs or web scraping, you may come across situations where you need to send query parameters along with your requests. The Python Requests library makes it easy to add query parameters to your requests.
Query parameters are used to filter, sort or paginate the results. They are typically added to the end of the URL after a "?" character, followed by key-value pairs separated by "&" characters.
Adding Query Parameters
import requests
url = "https://api.example.com/users"
params = {"page": 1, "per_page": 10}
response = requests.get(url, params=params)
print(response.url)
In this example, we are making a GET request to the "https://api.example.com/users" endpoint with two query parameters: "page" and "per_page". The params argument is a dictionary where the keys represent the parameter names and the values represent the parameter values.
The requests library automatically adds the query parameters to the URL as a string, so you can see the full URL by printing the response.url attribute. In this case, the full URL would be "https://api.example.com/users?page=1&per_page=10".
Passing Multiple Values for a Single Parameter
Sometimes you may need to pass multiple values for a single parameter. For example, if you are filtering by multiple values:
import requests
url = "https://api.example.com/users"
params = {"role": ["admin", "moderator"]}
response = requests.get(url, params=params)
print(response.url)
In this example, we are filtering users by the "admin" and "moderator" roles. To pass multiple values for a single parameter, you can use a list as the value for that parameter.
Encoding Query Parameters
The requests library automatically encodes query parameters in the URL using percent encoding. For example, if you have a query parameter with a space or special character:
import requests
url = "https://api.example.com/search"
params = {"q": "python requests"}
response = requests.get(url, params=params)
print(response.url)
In this example, we are searching for results that contain the phrase "python requests". The requests library automatically encodes the space as "%20", so the full URL would be "https://api.example.com/search?q=python%20requests".
Conclusion
The Python Requests library makes it easy to add query parameters to your requests using the params argument. You can pass multiple values for a single parameter using a list, and the library automatically encodes query parameters using percent encoding.