Python REST POST with basic auth
Solution 1
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.
Solution 2
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)
Related videos on Youtube
TheDOSandDONTS
Updated on June 04, 2022Comments
-
TheDOSandDONTS about 2 years
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"}]'
-
TheDOSandDONTS almost 6 yearsThanks for the suggestion. I've tried removing the dump and then running it both with and without the header that you suggested but unfortunately still returning a 405 status.