Hello,
I am currently trying to retrieve data from an API. The rate limit is 100 requests per minute.
I am currently using the following code:
import requests
import time
import json
def get_data(url):
headers = {
'Accept': 'application/json'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
print(f"Failed to fetch data from API. Status code: {response.status_code}")
return None
def fetch_data_with_rate_limit(url):
all_data = []
while True:
response_data = get_data(url)
if response_data:
all_data.append(response_data)
time.sleep(0.6) # Pause for 0.6 seconds between requests (100 requests per minute)
else:
break
return all_data
def save_data_to_json(data, filename):
with open(filename, 'w') as json_file:
json.dump(data, json_file)
api_url = "https://www.api-url.com/"
all_data = fetch_data_with_rate_limit(api_url)
save_data_to_json(all_data, 'data.json')
My problem is, if I just fetch once I get only 100 dictionaries containing data. But using the provided code it looks like I get the same data over and over, which results in an infinite loop.
Can someone help me with a hint, how I can solve this issue? The data should consist of multiple thousands of data points and I want to retrieve all of them.
I hope this does not violate rules, since I want to overcome the api rate limit. But since I am currently waiting for 0.6 seconds per requests this should be fine.