user9028316
user9028316

Reputation:

Python Key Error exception when navigating api requests

Everyone!

The API I'm using has a limit of 50 objects per request so I'm using their scroll api to get the next page, but when I navigate through the last page its X-Next-Page header parameter does not exist and it throws this error

KeyError: 'x-next-page'

The code I'm using:

        while request.headers['X-Next-Page'] is not None:
            url = "https://api-2445582011268.apicast.io%s" % request.headers['X-Next-Page']
            request = requests.get(url, headers=self.headers)
            # break if api key hit usage limit
            if request.status_code == 403:
                print("API key reached its limit")
                break

So how do I check if request.headers has X-Next-Page properly? Thank you

Upvotes: 0

Views: 781

Answers (1)

Bakhrom Rakhmonov
Bakhrom Rakhmonov

Reputation: 702

Try to use dict.get() function

while request.headers.get('X-Next-Page') is not None:
    url = "https://api-2445582011268.apicast.io%s" % request.headers['X-Next-Page']
    request = requests.get(url, headers=self.headers)
    # break if api key hit usage limit
    if request.status_code == 403:
         print("API key reached its limit")
         break

Upvotes: 3

Related Questions