query params in requests python

Query Params in Requests Python

Query params are the additional parameters that are appended to the end of the URL. These parameters are used to filter or sort the data that is being requested from an API. In Python, the requests module is used to send HTTP requests to a server and receive a response.

Using Query Params in Requests:

To include query params in a request using requests module, add the parameters to the params dictionary variable and pass it along with the request.


import requests

url = "https://example.com/api/data"
params = {"param1": "value1", "param2": "value2"}

response = requests.get(url, params=params)

print(response.content)

In the above example, we are making a GET request to the API URL https://example.com/api/data with query params param1 and param2. The requests.get() method takes two parameters: the URL and the params dictionary containing all the query parameters.

Multiple Ways to Add Query Params:

Method 1: Using Dictionary:

We can add query params to a URL by simply appending them to the URL string, like this:


url = "https://example.com/api/data?param1=value1¶m2=value2"
response = requests.get(url)

Method 2: Using params:

We can also add query params using the params parameter of the requests module, like this:


params = {"param1": "value1", "param2": "value2"}
response = requests.get("https://example.com/api/data", params=params)

Method 3: Using urlencode:

We can use the urlencode method from urllib.parse to encode the dictionary of query params into a URL-encoded string, like this:


from urllib.parse import urlencode

params = {"param1": "value1", "param2": "value2"}
url = "https://example.com/api/data?" + urlencode(params)
response = requests.get(url)

These are the three ways to add query params to a request using requests module in Python.