Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading