ArMonk
ArMonk

Reputation: 366

Python Post - keep getting response 400, but curl works

I have a simple python 3 script that send a post request to delete a project in SonarQube. While I am keep getting in my python script, a simple curl commands works... any idea what is wrong with my python script?

import requests

headers = {
    'Authorization': 'Basic YWRtaW46YWRtaW4=',
}

files = [
    ('key', 'com.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-view'),
]

r = requests.post('http://devsonar/api/projects/delete', headers=headers, files=files)
print(r)

The following curl command works fine:

curl -X POST -H "Authorization: Basic YWRtaW46YWRtaW4=" -F "key=com.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-view" "http://devsonar/api/projects/delete"

Upvotes: 1

Views: 702

Answers (2)

Mani
Mani

Reputation: 5648

Python requests is really a good library. Files option in post is used to upload file and I don't think com.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-view is a file if so, you have to read the file in binary mode and then send it like files = {'key': open(filename, 'rb')}. so the code should be:

import requests
files = {'key': open(filename, 'rb')}
headers = {'Authorization': 'Basic YWRtaW46YWRtaW4='}
response=requests.post(url,files=files)

check this for details on uploading files using requests library in python.

If it is not a file you can send the payload directly as a dictionary like this:

import requests
headers = {'Authorization': 'Basic YWRtaW46YWRtaW4='}
data = {'key': 'com.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-view'}
response=requests.post(url,data=data,headers=headers)

check this for details on sending payload.

Upvotes: 2

ArMonk
ArMonk

Reputation: 366

You should have used data, not files, as an input to the python script, this should work:

import requests

headers = {
    'Authorization': 'Basic YWRtaW46YWRtaW4=',
}

files = [
    ('key', 'com.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-view'),
]

r = requests.post('http://devsonar/api/projects/delete', headers=headers, data=files)

Upvotes: 0

Related Questions