pass query params in python requests

hljs.highlightAll();

Pass Query Params in Python Requests

When making HTTP requests using Python, you may need to pass query parameters along with the request. Query parameters are used to filter or sort the data that is returned from the requested resource.

Using the 'params' parameter in requests.get()

The easiest way to pass query parameters in Python Requests is by using the 'params' parameter in the requests.get() method. This parameter should be set to a dictionary of key-value pairs where the key is the name of the parameter and the value is its value.


	import requests

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

	print(response.url)
	

In this example, we are passing two query parameters, 'param1' and 'param2', with values 'value1' and 'value2', respectively. The requests.get() method builds the URL with these parameters and makes the request to the API endpoint. The response object contains the response data returned by the API.

Using urlencode() to build the query string

You can also use the urllib.parse.urlencode() function to build the query string and append it to the URL.


	import requests
	from urllib.parse import urlencode

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

	print(response.url)
	

In this example, we are using the urllib.parse.urlencode() function to build the query string and append it to the URL. The resulting URL is then used to make the request using requests.get().

Using requests.Request() and requests.Session()

You can also use the requests.Request() class to create a request object and pass it to the requests.Session() object to execute the request. This method allows you to build a more complex request with headers, cookies, and other options.


	import requests

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

	req = requests.Request('GET', url, params=params)
	prepped = req.prepare()

	session = requests.Session()
	response = session.send(prepped)

	print(response.url)
	

This example demonstrates how to use the requests.Request() class to create a request object, which is then prepared using req.prepare(). The resulting prepared request is then passed to the requests.Session() object using session.send() to make the request.