Home > OS >  Trying to loop an API call until condition is met
Trying to loop an API call until condition is met

Time:12-20

Background - I am trying to create a function that continues to call an API (response = api_response) whilst a condition is true. When the condition is False, the function should instead return api_response.

Function - this is my function in it's current form. I have completely confused myself, and therefore written some notes, so you can 'try' and understand my thought process:

def api_call():
#   Getting required variables by calling other functions
    key, secret, url = ini_reader()
    endpoint_url = endpoint_initializer()
    
#   In these 3x lines of code I'm trying to ensure the API is called.
    while True:
        response = requests.get(url = endpoint_url, auth = HTTPBasicAuth(key, secret), headers = {"My-firm": "482"})
        api_response = json.loads(response.text)

#       I am now trying to take the returned 'api_response' and see if a condition is met / trying extract certain key pair values,
#       which tell me the data isn't available. If the condition is met (keys are in the response / data isn't available), I am expecting
#       the API to continue being called again and the loop continues to iterate until the condition is not met, at which point I am expecting to simply have 'api_response' returned.  
    try:
            id_value = "id"
            res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
            id_value = "".join(res1)
            percent_value = "percent_complete"
            res2 = (tuple(api_response["data"]["attributes"].get("percent_complete", '') for key, val in api_response.items()))
            print(f' Your data requested, associated with ID: {id_value} is {res2} complete!')
            time.sleep(5)
#       If the above condition isn't met, then return 'api_response', which includes the data.
        except:
            return api_response
api_call()

Issue - currently, I can't seem to get my loop to function properly, in that it calls the API once and then dies. Can anyone put me right, with the correct loop to implement?

CodePudding user response:

Thanks to a useful user comment, I identified the try statement wasn't testing anything and would infinitely loop, Instead, I used while True to start and infinite loop, and captured the API response, before using a try statement to test a condition (if "meta not in api_response). If that condition is true, then the loop would continue to call the API for data and print a message (taking data such as percent_complete) from the API and print a message to the user on the API response progress.

Finally, once elif "meta in api_response: (meaning the API response is now returning data), then I return api_respone, ready to be used by another function.

Complete function -

def api_call():

    key, secret, url = ini_reader()
    endpoint_url = endpoint_initializer()
    
    date = dt.datetime.today().strftime("%Y-%m-%d")
    print("-------------------------------------\n","API URL constructed for:", date, "\n-------------------------------------")
    print("-------------------------------------------------------------\n","Endpoint:", endpoint_url, "\n-------------------------------------------------------------")

    while True:
        response = requests.get(url = endpoint_url, auth = HTTPBasicAuth(key, secret), headers = {"Vendor-firm": "443"})
        api_response = json.loads(response.text)
        if "meta" not in api_response:
            id_value = "id"
            res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
            id_value = "".join(res1)
            percent_value = "percent_complete"
            res2 = (tuple(api_response["data"]["attributes"].get("percent_complete", '') for key, val in api_response.items()))
            print(f' Your data requested, associated with ID: {id_value} is {res2} complete!')
            time.sleep(5)
        elif "meta" in api_response:
            return api_response
api_call()
  • Related