-1

I am new to Python. I am using 'requests' library to send post request. I am able to send post request without headers but when giving headers I am getting HTTP 400 error.

import requests

API_ENDPOINT = "https://reqres.in/api/users"

data = {"name": "Name1", "job": "job1"}
headers = {'Content-Type': 'application/json'}

# sending post request and saving response as response object
full_output = requests.post(url = API_ENDPOINT, headers=headers,  data = data)
print("response status", full_output.status_code)
print("response", full_output.text)

Output:

response status 400

response <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Bad Request</pre>
</body>
</html>

It is working if I pass empty headers in the code

headers = {}

Not sure why it is not working. Request your help. Thanks.

3
  • 1
    try json=data or you need to dump your data dict to JSON first before if you use that json string with data=. Note that json=data will set the headers Content-Type for you, so you can skip that as well. Commented Jun 27, 2022 at 8:15
  • Does this answer your question? Difference between data and json parameters in python requests package Commented Jun 27, 2022 at 8:20
  • Hi @buran , yes after doing json=data it resolved my issue. Thank you for the suggestion. Commented Jun 27, 2022 at 9:12

1 Answer 1

1

You are sending python dict where the api is expecting json string, to which you need to encode your dict. You can go for either of them:

full_output = requests.post(url = API_ENDPOINT, headers=headers,  data = json.dumps(data))

full_output = requests.post(url = API_ENDPOINT, json = data)
Sign up to request clarification or add additional context in comments.

3 Comments

I have tried with the first one and it is working. Thanks.
With 2nd approach, you don't have to set the content-type explicitly as it automatically sets Content-Type header to application/json, and also encodes the data to json
yes but I think I cannot use 2nd approach as I might have other headers as well apart from Content-Type. Say auth header, some custom header etc. I need to pass those headers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.