How to return to earlier (if statement) loop in python

Question:

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.

Asked By: k1np3r

||

Answers:

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()
Answered By: Asi

You can use a while loop, like this:

import requests
import json

def auth_vt_apikey():
    """This function test VirusTotal's Api Key"""
    ...


api_key = ''
api_key_valid = False
while (not api_key_valid):
    if api_key == '':
        api_key = str(input("Please enter your VirusTotal's API Key: "))

    url = 'https://www.virustotal.com/vtapi/v2/url/report'
    params = {'apikey': api_key}
    response = requests.get(url, params={'apikey': api_key})

    if response.status_code == 200:
        print('Your Api Key is correct')
        api_key_valid = True
    else:
        print("Your Api Key is incorrect.", end=" ")
        
auth_vt_apikey()
Answered By: DoubleFelix

First: all of the code that’s supposed to be inside your function needs to be indented.

In the initial code that asks for the API key:

api_key = ''

if api_key == '':
    api_key = str(input("Please enter your VirusTotal's API Key: "))
else:
    None

the if api_key == '' is entirely unnecessary (it will always be true since you just set api_key = ''), as is the str() around input() (it always returns a str anyway). Just do:

api_key = input("Please enter your VirusTotal's API Key: ")

When you do the request to test the 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: "))

you should do it in a loop if you want to actually retry with the new key:

while True:
    response = requests.get(url, params={'apikey': api_key})

    if response.status_code == 200:
        print('Your Api Key is correct')
        return api_key  # ends the loop and returns the valid key to the caller

    api_key = input("Your Api Key is incorrect. Please re-type your Api Key: ")
    # loop continues until the API key is correct
Answered By: Samwise
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.