1

Question 1) Do we need to do json.dumps and encode before making a Python POST request?

Usually the request is:

response = requests.post('https://httpbin.org/post', json={'key':'value'})

Question 2)

Is it advisable to do like the below instead?:

x1 = {'key':'value'}
x2 = json.dumps(x1)
x3 = x2.encode()
response = requests.post('https://httpbin.org/post', json=x3)

Question 3) When do we need to do json.dumps and encode before making a Python POST request?

variable
  • 8,262
  • 9
  • 95
  • 215
  • you can pass data in as `data` parameter in `response = requests.post('https://httpbin.org/post', data={'key':"value"})` you can also set appropriate content-type in header argument as dictionary – Yugandhar Chaudhari Oct 01 '19 at 09:59

2 Answers2

1

No, if you use the json parameter, it should be a dictionary. From the documentation:

json – (optional) A JSON serializable Python object to send in the body of the Request.

frankie567
  • 1,703
  • 12
  • 20
0

You just need to use dumps your data before making post request as given below-

url = "http://localhost:8080"
obj = {'City': 'Delhi', 'Country': 'India', 'message': 'Hello Team!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
requests.post(url, data=json.dumps(obj), headers=headers)

Note: what I've observed during testing dumps is not necessary in POST requests. It should also work with data=obj only.

IRSHAD
  • 2,855
  • 30
  • 39