I am using the following in Telerik Fiddler in order to create a POST request and it is successful:
POST https://login.random.com/connect/token HTTP/1.1 Connection: Keep-Alive Content-Type: application/x-www-form-urlencoded Accept: application/json Authorization: Basic XyXyXyXyXyXyXyXyXyXyXy= Content-Length: 105 Host: login.random.com
grant_type=password&username=xxx&password=xxxx&scope=random.api.external
and now I am trying to convert that into a Python script but it fails (returns error 400):
import json
import requests
import http.client
headers = {
'Connection': 'Keep-Alive',
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': 'Basic XyXyXyXyXyXyXyXyXyXyXy=',
'Content-Length': '105',
'Host': 'login.random.com'
}
body = {
'grant_type': 'password',
'username': 'xxx',
'password': 'xxxx',
'scope': 'random.api.external'
}
response = requests.post('https://login.random.com/connect/token', headers=headers, data=body)
I have also tried including all the above in the headers and it failed (error 400).
Am I missing a library maybe? The details are correct in my script.
I have found a solution to my problem. In Telerik Fiddler you can download a Code (Convert to Python) plugin and get an idea of how the final script should look like. After amending and testing, the final script is given below:
try:
req = urllib.request.Request("https://login.random.com/connect/token")
req.add_header("Connection", "Keep-Alive ")
req.add_header("Content-Type", "application/x-www-form-urlencoded ")
req.add_header("Accept", "application/json ")
req.add_header("Authorization", "Basic XyXyXyXyXyXyXyXyXyXyXy= ")
body = b"grant_type=password&username=xxx&password=xxxx&scope=random.api.external"
response = urllib.request.urlopen(req, body)
except urllib.error.URLError as e:
if not hasattr(e, "code"):
print('False')
response = e
except:
print('False')
print('True')