params in get request python

Params in GET Request Python

A GET request is one of the HTTP methods used to retrieve data from a server. It is used to request data from a specified resource. Params in GET requests are used to pass information from the client to the server. In Python, we can pass parameters in the URL using the requests module.

Passing Parameters in GET Request using requests Module

To pass parameters in GET request using the requests module, we need to use the "params" keyword argument. We can pass a dictionary containing the key-value pairs of parameters to it.


import requests

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

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

print(response.content)
    

In the above example, we are passing two parameters "param1" and "param2" with their respective values "value1" and "value2". The URL will be formed as "https://example.com/api?param1=value1¶m2=value2".

Passing Multiple Values for a Parameter

We can pass multiple values for a parameter by creating a list of values and passing it as the value of the parameter.


import requests

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

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

print(response.content)
    

In the above example, we are passing two values "value1" and "value2" for the parameter "param1". The URL will be formed as "https://example.com/api?param1=value1¶m1=value2¶m2=value3".

Using urlencode Function to Encode Parameters

We can use the "urlencode" function from the "urllib.parse" module to encode the parameters in a URL-safe format.


import requests
from urllib.parse import urlencode

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

encoded_params = urlencode(params)
full_url = url + '?' + encoded_params

response = requests.get(full_url)

print(response.content)
    

In the above example, we are using the "urlencode" function to encode the parameters and then appending them to the URL. The URL will be formed as "https://example.com/api?param1=value1¶m2=value2".