Making a POST request with python fails while making the same request with curl succeeds. What am I missing?

Question:

I have the following python code

import requests

url = 'http://example.com/endpoint'

data = {
  "doc": "This is my doc.",
  "date": "2022-12-02"
}

headers = {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "id": "12345",
    "key": "67890"
}

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

which fails with a code 400. However, when I test the same request with curl

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'id: 12345' --header 'key: 67890' -d '{  
   "doc": "This is my doc.",  
   "date": "2022-12-02"  
 }' 'http://example.com/endpoint'

it succeeds. I must be overlooking something simple but I can’t seem to find it.

I have tried using json in the request rather than a dictionary. Nothing seems to work.

Asked By: SomberHombre

||

Answers:

You can try to use json= parameter:

import requests

url = "http://example.com/endpoint"

data = {"doc": "This is my doc.", "date": "2022-12-02"}

headers = {
    "id": "12345",
    "key": "67890",
}

response = requests.post(
    url, json=data, headers=headers
)  # <-- use json= parameter

print(response.json())  # <-- to get result use .json() method
Answered By: Andrej Kesely
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.