Python request gives 415 error while post data

Mitra Mishra picture Mitra Mishra · Sep 7, 2018 · Viewed 21.7k times · Source

I am getting 415 error while posting data to server. This is my code how can i solve this problem. Thanks in advance!

import requests
import json
from requests.auth import HTTPBasicAuth
#headers = {'content-type':'application/javascript'}
#headers={'content-type':'application/json', 'Accept':'application/json'}
url = 'http://IPadress/kaaAdmin/rest/api/sendNotification'
data = {"name": "Value"}
r = requests.post(url, auth=HTTPBasicAuth('shany.ka', 'shanky1213'),json=data)
print(r.status_code)

Answer

Giorgos Myrianthous picture Giorgos Myrianthous · Sep 7, 2018

According to MDN Web Docs,

The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format.

The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly.

In your case, I think you've missed the headers. Uncommenting

headers={
    'Content-type':'application/json', 
    'Accept':'application/json'
}

and including headers in your POST request:

r = requests.post(
    url, 
    auth=HTTPBasicAuth('shany.ka', 'shanky1213'),
    json=data,
    headers=headers
)

should do the trick


import requests
import json
from requests.auth import HTTPBasicAuth


headers = {
    'Content-type':'application/json', 
    'Accept':'application/json'
}
url = 'http://IPadress/kaaAdmin/rest/api/sendNotification'
data = {"name": "Value"}

r = requests.post(
    url, 
    auth=HTTPBasicAuth('shany.ka', 'shanky1213'), 
    json=data, 
    headers=headers
)
print(r.status_code)