Home > Net >  Issue with referencing local variable before declaration for API GET call
Issue with referencing local variable before declaration for API GET call

Time:01-11

I'm having issue understanding how to return next_page token for my API call. It contains 100s of records and returns 30 at a time with next_page token to get the next 30... I'm able to get initial set of data and in my instance I'm just trying to return next_page tokens for the first 3 pages but so far it's just returning the same 3.

def main_request(baseUrl, header, size):
    repeat_count = 3
    while repeat_count != 0:
        response = requests.get(baseUrl   f'?page_size={size}'   f"&next_page_token={page_token}", headers=header)
        api_data = response.json()
        page_token = api_data['next_page_token']
        print('Current Token: ', page_token)
        repeat_count -= 1

With above it doesn't run because page_token hast not been declared but if I declare it at beginning and just set it to empty string, it runs but returns same 3 tokens from the first page.

JSON response if I set page_token = ''

Current Token:  TY3fkmCPZJkI4PdufKrdxlC6cblJHKZnnJ2
Current Token:  TY3fkmCPZJkI4PdufKrdxlC6cblJHKZnnJ2
Current Token:  TY3fkmCPZJkI4PdufKrdxlC6cblJHKZnnJ2

CodePudding user response:

Omit next_page from the payload to begin, then add it after each response.

def main_request(baseUrl, header, size):
    payload = {'page_size': size}
    for _ in range(3):
        response = requests.get(baseUrl, data=payload, headers=header)
        api_data = response.json()
        page_token = api_data['next_page_token']
        # Adds the first time, updates the others
        payload['next_page_token'] = page_token
        print('Current Token: ', page_token)
  • Related