I would like to write a simple function (I’m beginner), in my script, to check and test user’s API KEY from VirusTotal.
That’s my idea:
Firstly, I would like to check if user type his API KEY in code or field is empty.
Secondly, I would like to check if API KEY is correct. I had no idea how to check it the easiest way, so I use the simplest query I found on VirusTotal and check if the response code is 200.
But I have problem when API Key field is empty and user type wrong API Key. After that, my function ends. I would like to return to the previous if condition and check if this time the api key is correct.
When user type correct API KEY, function print proper message.
This is my code:
import requests
import json
def auth_vt_apikey():
"""This function test VirusTotal's Api Key"""
api_key = ''
if api_key == '':
api_key = str(input("Please enter your VirusTotal's API Key: "))
else:
None
url = 'https://www.virustotal.com/vtapi/v2/url/report'
params = {'apikey': api_key}
response = requests.get(url, params=params)
if response.status_code == 200:
print('Your Api Key is correct')
else:
api_key = str(input("Your Api Key is incorrect. Please re-type your Api Key: "))
auth_vt_apikey()
Can you explain to me what I’m doing wrong here and what is worth adding? I will also be grateful for links to guides, so that I can educate myself on this example.
>Solution :
I think you want to achieve this:
import requests
import json
def auth_vt_apikey():
"""This function test VirusTotal's Api Key"""
url = 'https://www.virustotal.com/vtapi/v2/url/report'
api_key = ''
msg = "Please enter your VirusTotal's API Key: "
while api_key == '':
api_key = str(input(msg))
params = {'apikey': api_key}
response = requests.get(url, params=params)
if response.status_code == 200:
print('Your Api Key is correct')
else:
api_key = ''
msg = "Your Api Key is incorrect. Please re-type your Api Key: "
auth_vt_apikey()