简体   繁体   中英

Python REST POST with basic auth

I am trying to get a POST request working with Python 3 which will submit a json payload to a platform which uses basic auth. I am getting a 405 status error and believe it may be resulting from the formatting of my payload. I'm learning Python as I go and still unsure about when to use ' vs ", objects vs arrays and the syntax of some requests. Searching, I haven't been able to find similar issues posting an array with basic auth. Here's what I've got at the moment:

import requests
import json

url = 'https://sampleurl.com'
payload = [{'value': '100','utcRectime': '09/23/2018 11:59:00 PM','comment': "test",'correctionValue': '0.0','unit': 'C'}]
headers = {'content-type': 'application/json'}

r = requests.post(url, auth=('username','password'), data=json.dumps(payload), headers=headers)


print (r)

Testing in the API swagger, the CURL contains the following formatting:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '[{"value": "100","utcRectime": "9/23/2018 11:59:00 PM","comment": "test","correctionValue": "0.0","unit": "C"}]' 

I don't think you want to dump the list to a string. requests will beat the python data structure into the right payload. The requests library is also smart enough to generate the proper headers if you specify the json keyword argument.

You can try:

r = requests.post(url, auth=('username','password'), json=payload)

Furthermore, sometimes sites block unknown user agents. You can try to pretend you're a browser by doing:

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
r = requests.post(url, auth=('username','password'), json=payload, headers=headers)

HTH.

From requests 2.4.2 ( https://pypi.python.org/pypi/requests ), the "json" parameter is supported. No need to specify "Content-Type". So the shorter version:

requests.post('https://sampleurl.com', auth=(username, password), json={'value': '100','utcRectime': '09/23/2018 11:59:00 PM','comment': "test",'correctionValue': '0.0','unit': 'C'})

Details:

import requests
import json

username = "enter_username"
password = "enter_password"

url = "https://sampleurl.com"
data = open('test.json', 'rb')

r = requests.post(url, auth=(username, password), data=data)

print(r.status_code) 
print(r.text)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM