Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python request gives 415 error while post data

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)
like image 924
Mitra Mishra Avatar asked Sep 07 '18 06:09

Mitra Mishra


People also ask

How do I fix error code 415?

A couple of things to look out for when trying to resolve 415 errors include: Ensure that you are sending the proper Content-Type header value. Verify that your server is able to process the value defined in the Content-Type header. Check the Accept header to verify what the server is actually willing to process.

How do you request a post in Python?

To create a POST request in Python, use the requests. post() method. The requests post() method accepts URL. data, json, and args as arguments and sends a POST request to a specified URL.

What does requests post return in Python?

post() Python's requests module comes with a method for making a “post” request to a web server; it returns a response object.


1 Answers

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)
like image 74
Giorgos Myrianthous Avatar answered Sep 23 '22 21:09

Giorgos Myrianthous