python requests module params

Python Requests Module Params

Python Requests module is used to send HTTP requests using Python. Params is an optional parameter in the requests module, which is used to send a dictionary or list of parameters and values to the URL.

Syntax:


        response = requests.get(url, params={'key1': 'value1', 'key2': 'value2'})
    

Here, the params parameter is a dictionary with key-value pairs, which will be appended to the URL. If the URL already has some parameters, then it will be appended with '&' separator.

Example:


        import requests
        
        base_url = "https://jsonplaceholder.typicode.com/posts"
        params = {'userId': 1}
        
        response = requests.get(base_url, params=params)
        
        print(response.url)
    

This will return the following URL: https://jsonplaceholder.typicode.com/posts?userId=1

Multiple ways to use Params:

  • Using a string: Instead of using a dictionary, we can also pass a string as a parameter.
  • Using a list of tuples: We can also send a list of tuples as a parameter.

Here is an example of using a list of tuples:


        import requests
        
        base_url = "https://jsonplaceholder.typicode.com/comments"
        
        params = [('postId', 1), ('id', 1)]
        
        response = requests.get(base_url, params=params)
        
        print(response.url)
    

This will return the following URL: https://jsonplaceholder.typicode.com/comments?postId=1&id=1