Home > Software design >  Making a POST request with python fails while making the same request with curl succeeds. What am I
Making a POST request with python fails while making the same request with curl succeeds. What am I

Time:12-22

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.

CodePudding user response:

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
  • Related