The requests
library in Python allows you to send HTTP requests using methods like get
, post
, put
, delete
, etc. Two of the parameters that you can use when sending requests are json
and data
. These parameters are used to specify the content that you want to send to the server. Here's the difference between them:
data
parameter:
- Usage: The
data
parameter is used when you want to send form-encoded data (content typeapplication/x-www-form-urlencoded
) to the server. This is the kind of data that is typically sent from HTML forms. - Format: When using the
data
parameter, you can pass a dictionary, a list of tuples, or a bytes object. If you pass a dictionary or a list of tuples,requests
will form-encode it for you. Example:
import requests payload = {'key1': 'value1', 'key2': 'value2'} # Dictionary payload r = requests.post('https://httpbin.org/post', data=payload) print(r.text) # List of tuples payload payload_tuples = [('key1', 'value1'), ('key2', 'value2')] r = requests.post('https://httpbin.org/post', data=payload_tuples) print(r.text) # Bytes payload payload_bytes = 'key1=value1&key2=value2'.encode('utf-8') r = requests.post('https://httpbin.org/post', data=payload_bytes) print(r.text)
json
parameter:
- Usage: The
json
parameter is used when you want to send JSON data to the server. The content type for this request will be set toapplication/json
. - Format: When using the
json
parameter, you should pass a JSON-serializable Python object (usually a dictionary).requests
will automatically serialize the Python object to JSON. Example:
import requests payload = {'key1': 'value1', 'key2': 'value2'} # JSON payload r = requests.post('https://httpbin.org/post', json=payload) print(r.text)
When you use the json
parameter, requests
sets the Content-Type
header to application/json
and serializes the Python object to a JSON string. On the other hand, when you use the data
parameter with a dictionary or list of tuples, the Content-Type
header is set to application/x-www-form-urlencoded
, and the dictionary or list of tuples is encoded as a form submission.
It's important to choose the right parameter based on the API you're interacting with and the format it expects for the request data.