Reputation: 9
I am trying to retrive information, that is accessible via Rest API. But I am not sure how to pass authentication credentials.
GET endpoint doesn't have any place to insert username and password.
When I try to get this info through browser it asks for credentials. But how can I call GET request with python and pass credentials that are required to log in into server?
Here is how it looks via browser
@EDIT Ok here is what I found:
It works with powershell:
$root = 'http://<server>:8080/local/people-counter/.api?live-sum.json'
$user = "user"
$pass= "pass"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$result = Invoke-RestMethod $root -Credential $credential
$result
This gives me a proper response:
serial : <string>
name : <string>
timestamp : 20210422114954
in : 6
out : 6
But how do I translate this to python? I already tried:
import requests
from requests.auth import HTTPBasicAuth
response = requests.get('http://<server>:8080/local/people-counter/.api?live-sum.json', auth=HTTPBasicAuth('user', 'pass'))
print(response)
But response is always:
<Response [401]>
Upvotes: 1
Views: 895
Reputation: 81
You can use HTTP Client
.
Her's more: https://api.flutter.dev/flutter/dart-io/HttpClient-class.html
import 'dart:convert';
import 'dart:developer' as developer;
import 'package:http/http.dart' as http;
main() async {
var client = http.Client();
String username = 'example';
String password = 'example123';
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
String url =
'https://example.com/api';
print(basicAuth);
var response = await client.get(contacts_url,
headers: <String, String>{'authorization': basicAuth});
print(response.statusCode);
developer.log(response.body);
}
Upvotes: 0