python REST basic connection

Viewed 36

I have been on this site and cannot find a suitable resolution to this problem.

I can connect to my system via Powershell using the following;

$auth = '{"username":' + '"' + $user + '","password":' + '"' + $Pass + '"}'  
$body = $auth
$hdrs = @{}
$hdrs.Add("X-API-KEY", "???")

$r = Invoke-RestMethod -Uri http://$URLSystem/login -Method Post -Body $body -ContentType 'application/json' -Headers $hdrs

I get a response back of 200 and I can get session keys etc...

I have tried a number of things in Python to connect to the same system. I tried this basic approach;

import requests
from requests.auth import HTTPBasicAuth

basic = HTTPBasicAuth('user1','pass1')

r = requests.get("http://URLSystem/login", auth=basic)

print(r.headers)
print(r) 

I get a 405 response code. I have tried changing the get to a POST and get a 415 error response.

I am new to Python and having a little difficulty getting this going. Any help would be greatly appreciated.

1 Answers

Thank you for the response.

I will look at the resources you pointed out - this was helpful.

Yes, I thought I should be using request.post(...) but could not get the right format for headers and params to use.

I did find this post @this web site and it worked for me with some slight modification, so I am good for now...

Posting the solution here for anyone else if they have similar issues.

import requests
import json

URL = 'http://your-url'

headers = {
"accept": "application/json", 
"Content-Type": "application/json"
}

params = { 
"username": "yourusername", 
"password": "yourpassword" 
}

resp = requests.post(URL, headers = headers ,data=json.dumps(params))
session = json.loads(resp.text)['SessionToken']

if resp.status_code != 200:
    print('error: ' + str(resp.status_code))
else:
    print('Response Code: ' + str(resp.status_code) + ', Session-Token: ' + str(session))
Related