query parameters in python requests

Query Parameters in Python Requests

Query parameters are additional parameters added to the end of a URL that allow us to filter or sort data from a web API. In Python requests library, we can easily add query parameters to our requests using the params parameter.

Adding Query Parameters

To add query parameters to our request, we can simply pass a dictionary of key-value pairs as the value of the params parameter. For example:


import requests

url = 'https://api.example.com/data'
params = {'sort': 'date', 'limit': 10}
response = requests.get(url, params=params)

print(response.json())
  

In the above example, we're making a GET request to https://api.example.com/data with two query parameters: sort and limit. The params parameter is set to a dictionary containing these two key-value pairs.

Modifying Query Parameters

If we need to modify existing query parameters, we can simply update the dictionary passed to the params parameter. For example:


import requests

url = 'https://api.example.com/data'
params = {'sort': 'date', 'limit': 10}
response = requests.get(url, params=params)

# Modify limit to 20
params['limit'] = 20
response = requests.get(url, params=params)

print(response.json())
  

In the above example, we're first making a GET request with limit set to 10. Then, we're updating the limit key in the dictionary to 20 and making another GET request with the updated parameters.

Encoding Query Parameters

By default, Python requests library will encode query parameter values using URL encoding (e.g. replacing spaces with %20). However, if we need to use a different encoding, we can specify it using the params parameter. For example:


import requests

url = 'https://api.example.com/data'
params = {'q': 'john doe'}
response = requests.get(url, params=params, params={'q': 'john+doe'})

print(response.json())
  

In the above example, we're making a GET request with a query parameter q set to john doe. However, we want to use the plus sign (+) instead of URL encoding for spaces. Therefore, we're passing an additional dictionary to the params parameter with the same key-value pair but with the plus sign encoding.