'Python requests not sending {"Content-Type":"application/json"} header or is just ignoring body in HTTP POST
I'm writing some Python to communicate with an API, that uses RESTful. I've managed many successful GET commands, however, am having difficulties with POST. The HTTP POST is going through and I'm getting a 200 OK response and data but the Body I'm sending with the POST isn't being read.
import requests
url = "http://example.co.uk/dir"
body = {"obj1":1, "obj2":2}
headers = {"Accept":"application/json"}
s = requests.Session()
req = requests.Request("POST", url, json=body, headers=headers)
prepped = req.prepare()
print(prepped.headers)
response = s.send(prepped)
print(response.request.headers)
Result of the print(prepped.headers)
show:
{"Accept": "application/json","Content-Length":"19","Content-Type":"application/json"}
However, results of the print(response.request.headers)
only shows:
{"Accept": "application/json"}
I have also tried using the method:
request.post(url, json=body, headers=headers)
and also tried manually creating "Content-Type" and using data=body and the json module:
headers = {"Accept":"application/json", "Content_Type":"application/json"}
body = json.dumps(body)
request.post(url, data=body, headers=headers)
Every time I recieve the 200 OK Status and some data in the right format but as if the API has ignored the body. Any help or pointers would be greatly appreciated.
Solution 1:[1]
In your example you're using HTTP. Make sure to use HTTPS request as that can be an issue depending on the API you're dealing with.
import requests
s = requests.session()
s.headers = headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
https = s.post("https://reqbin.com/echo/post/json", json={"foo": "bar"})
print(https.status_code)
print(https.request.headers)
http = s.post("http://reqbin.com/echo/post/json", json={"foo": "bar"})
print(http.status_code)
print(http.request.headers)
Results in
200
{'Accept': 'application/json', 'Content-Type': 'application/json', 'Content-Length': '14'}
405
{'Accept': 'application/json'}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rwy__ |