python requests kwargs

Python Requests kwargs

If you are working with Python requests library and want to add additional arguments (key-value pairs) to the request, you can pass them as keyword arguments (kwargs) in the request method.

Syntax:


import requests

response = requests.get(url, **kwargs)

Here, **kwargs unpacks the dictionary of keyword arguments and passes them as individual arguments to the request method.

Example:


import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
params = {'q': 'Python'}
proxies = {'http': 'http://10.10.1.10:3128', 'https': 'http://10.10.1.10:1080'}
timeout = 5

response = requests.get('https://www.google.com/search', headers=headers, params=params, proxies=proxies, timeout=timeout)

print(response.status_code)

In this example, we are making a GET request to Google search with the specified headers, query parameters, proxies, and timeout values. All these arguments are passed as kwargs in the get() method.

You can pass any valid argument that the request method supports as a keyword argument.

Alternative:

Alternatively, you can also pass the arguments as a dictionary using the params and headers parameters of the request method.


import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
params = {'q': 'Python'}
proxies = {'http': 'http://10.10.1.10:3128', 'https': 'http://10.10.1.10:1080'}
timeout = 5

response = requests.get('https://www.google.com/search', params=params, headers=headers, proxies=proxies, timeout=timeout)

print(response.status_code)

This method is also equivalent to passing the arguments as kwargs.