python requests query string parameters

Python Requests Query String Parameters

In Python, Requests is a popular HTTP library used to send HTTP requests and handle responses. It provides a simple and elegant way to interact with APIs and web services. With Requests, we can easily add query string parameters to our HTTP requests.

Adding Query String Parameters using the params Parameter

The simplest way to add query string parameters is by passing them as a dictionary to the params parameter of the request methods like get() or post().


import requests

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://example.com/api', params=payload)

print(response.url)
  

In the above example, we are sending a GET request to the URL https://example.com/api with two query string parameters: key1 and key2. We passed them as a dictionary to the params parameter of the get() method. The resulting URL will be https://example.com/api?key1=value1&key2=value2.

Adding Query String Parameters to URL Directly

We can also add query string parameters directly to the URL. For example:


import requests

response = requests.get('https://example.com/api?key1=value1&key2=value2')

print(response.url)
  

In the above example, we added the query string parameters key1 and key2 directly to the URL. The get() method will send a GET request to the URL with the query string parameters.

Encoding Query String Parameters

When we add query string parameters, Requests will automatically encode them properly. For example:


import requests

payload = {'space char': 'text with spaces'}
response = requests.get('https://example.com/api', params=payload)

print(response.url)
  

In the above example, we added a query string parameter with a space character in its name. Requests will encode it properly as %20.