VASK API LogIn with python script. log in Error

58 views Asked by At

I want to log in into VASK API with a python script but is does not work. This is my Code, maybe you may help me.

import requests

VAST = 'https://xx.xxx.xxx.xx/api/latest'
username = 'xxxxxx'
password = "xxxxxxxxxxx"

def login(username, password):
    url = f'{VAST}'
    data = {
        'username': username,
        'password': password
    }
    response = requests.post(url, data=data)
    return response.json()

if __name__ == "__main__":
    auth_response = login(username, password)
    if auth_response and 'token' in auth_response:
        print('connected')
        print(f'Authentifizierungs-Token: {auth_response["token"]}')
    else:
        print('error')
1

There are 1 answers

0
Ömer Sezer On

I think that your missing part is the headers:

def login(username, password):
    ...
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.post(url, json=data, headers=headers)
    ...

You can even test on your local machine:

Dummy LocalServer (run on the terminal, python local_server.py):

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/api/latest/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if username == 'your_username' and password == 'your_password':
        return jsonify({'token': 'your_test_token'}), 200
    else:
        return jsonify({'error': 'Invalid username or password'}), 401

if __name__ == '__main__':
    app.run(debug=True)

Your VAST Login requester (run on another terminal with and without headers):

import requests

VAST_API = 'http://127.0.0.1:5000/api/latest'
username = 'your_username'
password = 'your_password'

def login(username, password):
    url = f'{VAST_API}/login'
    data = {
        'username': username,
        'password': password
    }
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.post(url, json=data, headers=headers)

    if response.status_code == 200:  # successful HTTP status 
        return response.json()
    else:
        print(f'Error: {response.status_code}')
        return None

if __name__ == "__main__":
    auth_response = login(username, password)
    if auth_response and 'token' in auth_response:
        print('Connected')
        print(f'Authentication Token: {auth_response["token"]}')
    else:
        print('Error')

Output (no error):

Connected
Authentication Token: your_test_token