Hi I am generating random
data to csv file based on
Opensea API. Problem is I am limited by the list size on the API. Is there a way to get around that?
Here is my code:
r = requests.get('https://api.opensea.io/api/v1/assets?collection=bit birds&order_direction=asc&offset=' + (str(x)) + '&limit=1') jsonResponse = r.json() name = jsonResponse['assets']['name'] description = jsonResponse['assets']['description'] print('Name: ' + name) print('Description: ' + str(description))
And I get this error:
Traceback (most recent call last): File "d:generate-bitbirds-maingenerate-bitbirds-mainbird_databitbird_generation_script_w_csv4.py", line 1855, in <module> name = jsonResponse['assets']['name'] IndexError: list index out of range
When working with APIs, it is good practice to check first if the request was successful before accessing the response. You may call r.raise_for_status() first and handle the error scenario. Then before accessing the list, check first if it is not empty.
r = requests.get(...) try: r.raise_for_status() # Check if the request was successful jsonResponse = r.json() # Check if the response is in JSON format except requests.HTTPError, JSONDecodeError: # Handle error scenario else: if jsonResponse['assets']: # Check first if there are assets returned # Proceed as usual name = jsonResponse['assets']['name'] description = jsonResponse['assets']['description'] else: # This means that the assets are empty. Depending on your use case logic, handle it accordingly. # Handle empty assets scenario