Add_models_to_collection method improvement

Hi,
add_models_to_collection method in v3 API documents does not work well because of the response code 429. I have added the sleep and retry function in the script then it works. I want share you the following script. I’m not a professional of python so please rewrite something wrong part when you use it.

"""Sample script that shows how to list models, and various operations with them (comments,
collections...) using the V3 api and the requests library.

20221223 Memento. sleep and retry function added in "add_model_to_collection" method.
"""

import json
import pandas as pd
from sys import exit
from time import sleep
import requests
from requests.exceptions import RequestException

SKETCHFAB_API_URL = 'https://api.sketchfab.com/v3'
API_TOKEN = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' # insert your API token
MAX_RETRIES = 60
RETRY_TIMEOUT = 60  # seconds

dirpath = str(r"I:\models")
uidlist = pd.read_excel(dirpath + r'\url.xlsx', header=0,index_col=0)   # import uidlist excel file. you have to have prepared uid_list of your models.

def _get_request_payload(*, data=None, files=None, json_payload=False):
    """Helper method that returns the authentication token and proper content type depending on
    whether or not we use JSON payload."""
    data = data or {}
    files = files or {}

    headers = {'Authorization': 'Token {}'.format(API_TOKEN)}

    if json_payload:
        headers.update({'Content-Type': 'application/json'})
        data = json.dumps(data)

    return {'data': data, 'files': files, 'headers': headers}

def list_my_models():   # this method work strangely it lists only 24 models. 
    my_models_endpoint = f'{SKETCHFAB_API_URL}/me/models'
    payload = _get_request_payload()

    try:
        response = requests.get(my_models_endpoint, **payload)
    except RequestException as exc:
        print(f'An API error occured: {exc}')
    else:
        data = response.json()

        if not len(data['results']) > 0:
            print('You don\'t seem to have any model :(')

        return data['results']

def get_collection():
    my_collections_endpoint = f'{SKETCHFAB_API_URL}/me/collections'
    payload = _get_request_payload()

    try:
        response = requests.get(my_collections_endpoint, **payload)
    except RequestException as exc:
        print(f'An API error occured: {exc}')
        exit(1)

    data = response.json()

    if not data['results']:
        print('You don\'t seem to have any collection, let\'s create one!')
        return
    else:
        return data['results'][0]

def create_collection(name, model):
    collections_endpoint = f'{SKETCHFAB_API_URL}/collections'
    data = {'name': name, 'models': [model['uid']]}
    payload = _get_request_payload(data=data, json_payload=True)

    try:
        response = requests.post(collections_endpoint, **payload)
    except RequestException as exc:
        print(f'An API error occured: {exc}')
    else:
        # We created our collection \o/
        # Now retrieve the data
        collection_url = response.headers['Location']
        response = requests.get(collection_url)

        return response.json()

def add_model_to_collection(modeluid, collection):  # response code 429 occar frequently. so, "sleep and retry" method added.
    collection_model_endpoint = f'{SKETCHFAB_API_URL}/collections/{collection["uid"]}/models'

    payload = _get_request_payload(data={'models': [modeluid]}, json_payload=True)
    #payload = _get_request_payload(data={'models': [model['uid']]}, json_payload=True)
    retry = 0
    
    while (retry < MAX_RETRIES):
        try:
            response = requests.post(collection_model_endpoint, **payload)
        except RequestException as exc:
            print(f'An API error occured: {exc}')
        else:
            if response.status_code == requests.codes.created:
                print(f'uid:{modeluid} successfully added to collection!')
                break
            elif response.status_code == 429:   # this code insists "HTTP 429 Too Many Requests"
                retry += 1
                print(f"retry in {RETRY_TIMEOUT} seconds. ({retry} of {MAX_RETRIES})")
                sleep(RETRY_TIMEOUT)
                continue
            else:
                print('Model does not added the collection with some reason')
                print('status code is {response.status_code}')
                break
    else:
        print("TIMEOUT!!!")
        exit()

if __name__ == '__main__':
    print(uidlist["uid"])
    collection = get_collection()

    # List your collections, create one if you don't have any
    collection = get_collection()

    new_collection = 'NEW COLLECTION'   # insert the name of new collection

    if not collection:
        collection = create_collection(new_collection, uidlist['uid'][0])

    for i in range(len(uidlist)):
        add_model_to_collection(uidlist["uid"][i], collection)

Hi @Memento - our dev team (in fact the whole Sketchfab team) are off for a winter break, returning on 3rd Jan 2023.

I suggest that you bump your post with a new reply then and someone will take a look then :+1: