I have been using Python requests to get data from an API, but I want to speed it up by running asynchronously with requests_futures. I am only allowed 200 API requests per minute, so I have to check for this and wait a specified number of seconds before retrying. This number is returned in the Retry-After header. Here is the original working code:
session = requests.Session()
for id in ticketIds:
url = 'https://colorfront.zendesk.com/api/v2/tickets/' + str(id) + '/comments.json'
req = requests.get(url, auth=zd_secret)
if req.status_code == 429:
time.sleep(int(req.headers['Retry-After']))
req = requests.get(url, auth=zd_secret)
comments += req.json()['comments']
The following asynchronous code works until it hits a rate limit, then all the requests after that fail.
session = FuturesSession()
futures = {}
for id in ticketIds:
url = 'https://colorfront.zendesk.com/api/v2/tickets/' + str(id) + '/comments.json'
futures[id] = session.get(url, auth=zd_secret)
for id in ticketIds:
comments += futures[id].result().json()['comments']
When I hit the rate limit, I need a way to retry only the requests which failed. Does requests_futures have some built-in way to handle this?
Update: The requests_futures library does not have anything built-in for this. I found this related open issue: https://github.com/ross/requests-futures/issues/26. I'll try to pace the requests up front since I know the API limit, but that won't help if another user from my organization is simultaneously hitting the same API.