alexa tang
alexa tang

Reputation: 115

how to write a while loop to call API using the next page token (python)

I am new to python and using while loops. I am trying to use a while loop to check if the response json contains a token. If it does then continue calling the API with the new token and save that data. The problem with my code below is I have created an infinite loop.

HERE IS MY CODE:

`

if __name__ == '__main__':
    # get all types
    df = pd.read_csv('business_type.csv')

    # loop thru each type
    for type in df['business_type']:

        token_exists = True
        token = ''

        while token_exists:
             # this calls the google api
            response = make_google_api_call(type, token)

            if "next_page_token" in response:
                 # this saves the data to a csv file
                save_data(response)
                token = response['next_page_token']
            else:
                token_exists = False;`

Here is the json response i get back from google api if response['next_page_token'] exists

{
    "html_attributions": [],
    "next_page_token": "ARywPAKrjG1gF4GUTymheyzijYQ3j-nkHI50999W8VBK39VJQ3HOifU7y062pZB0xX1dxIdZEgtPxWrbtVI1StbmQ-p9KQSmxVbk2_zMWmFZOFJoDIk_l1aOkkQQAO8jZUoPpDH1-2l5O43gLxEegRxvM59fs2oXhT4I9HB7dI5D4WEHus0CFT_DGzU2uBEwcEPNiklhRMJg9rdHh-uw7pytSwHIgnFWMbV_r0JagGt-sjA_HYL_oej4Skh6n4q0NS46BYU8ORaTA6JOyndNecm_w0O8BEFAFru6Oy2IZLo3ZRXrJK3REC1kL5z-SBQiLqRLD6zKsMA8OURBfuBjsTfsLI1wbkYup1iSO9XZaYtkFsfqa73m-fPNc2QjS8gUF2Uzbviu1_H6J2D1J1vDIDvE2ARPVx_gyrzRfl9vmX-pllHVeC_fILuGowNI",
    "results": [...]
}

Upvotes: 0

Views: 710

Answers (1)

Xrayman
Xrayman

Reputation: 165

You have to provide more infos but let's try to add these lines before the else statement:

if token == '':
    token_exists = False;`

In this way you break the loop if next_page_token exists but is null

Upvotes: 1

Related Questions