how to pass params in python requests

How to Pass Params in Python Requests

If you are working on web scraping or API requests, passing parameters to the HTTP request is a common requirement. Python requests library provides an easy way to pass parameters to an HTTP request. Here are some ways to do it:

Passing Query String Parameters

If you want to pass query string parameters in the URL, you can use the params parameter of the requests.get() method.


import requests

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

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

print(response.url)
  

The above code will send a GET request to the URL 'https://api.example.com?key1=value1&key2=value2'.

Passing Form Data Parameters

If you want to send form data in the body of the HTTP request, you can use the data parameter of the requests.post() method.


import requests

url = 'https://api.example.com'
data = {'key1': 'value1', 'key2': 'value2'}

response = requests.post(url, data=data)

print(response.text)
  

The above code will send a POST request to the URL 'https://api.example.com' with form data in the request body.

Passing JSON Parameters

If you want to send JSON data in the body of the HTTP request, you can use the json parameter of the requests.post() method.


import requests
import json

url = 'https://api.example.com'
data = {'key1': 'value1', 'key2': 'value2'}

response = requests.post(url, json=json.dumps(data))

print(response.text)
  

The above code will send a POST request to the URL 'https://api.example.com' with JSON data in the request body.