Request

Response

    Load a Large Team (First Sync)

    This topic shows you how to read or update a large team without reaching the rate limit. A team allows 60 requests per UTC minute, shared by every app and administrator, so a first sync of a large team needs planning. At the end, you run a complete example that reads the product pools, users, and assignments of one team.

    You need a three-legged access token. See Get Started.

    By the end of this topic, you will be able to:

    • Estimate how long a large load takes.
    • Pace your requests and spread work across teams.
    • Order the work, so that you use the fewest requests.
    • Resume a sync after a failure or a rate limit block.
    • Run a first sync of one team.

    Plan for the time it takes

    A team allows 60 requests per UTC minute, about 3,600 an hour. Estimate your load before you start:

    • Reading 2,000 users with limit=100 takes 20 requests, which fits in under a minute.
    • Assigning a product to 2,000 users takes 2,000 requests, which takes at least 34 minutes.

    Reads and writes count the same, so a load that both reads and writes uses the allowance for both. For the limits, see Rate Limits.

    Pace your requests

    Aim for about one request per second per team, and don’t send requests in a burst. When a response includes X-RateLimit-Remaining, pause when it reaches 0, and resume after the time in X-RateLimit-Reset.

    Work on teams side by side

    Each team has its own allowance, so a sync of several teams can handle them in parallel. Parallel requests to one team reach its limit sooner, because they share one allowance. List Teams has a separate limit per APS client ID, so it applies across all your teams.

    Order the work

    Read what you can reuse first, and read the rest in the fewest requests:

    1. List the product pools once, and reuse the product IDs. Seat counts change between requests, so don’t rely on an old count.
    2. List the users, with limit=100. To find one user, use the email filter.
    3. List the assignments. List Assignments isn’t paginated, so one request without filters returns every assignment on the team. To read one user’s assignments, use the userId filter.

    Assignment changes can take a while to appear in team-wide results, so a sync that runs right after a change might not show it. For how pages and cursors work, see Pagination. The worked example follows this order.

    Checkpoint and resume

    Record your progress, such as the last cursor you used and the last user you processed. After a failure or a rate limit block, resume from that point instead of starting over.

    A cursor expires. If a request with a saved cursor returns 410, start that list again without a cursor. The worked example saves its progress after every page.

    Run again safely

    Add Team User and Assign Product are idempotent, so repeating them after a failure is safe. Unassign Product isn’t: a repeat returns 404 or 422. For the details, see Retry a write safely.

    Share the allowance

    Other apps and administrators use the same team allowance while your load runs. Schedule large loads for off-hours, and leave headroom instead of planning to use all 60 requests each minute.

    When you get blocked

    A 429 response includes a Retry-After header. Wait that many seconds, and then retry. Don’t retry sooner. If you keep receiving 429 responses after you wait, stop instead of looping. For how to retry each status code, see Error Handling.

    Worked example: sync one team

    The following example reads the product pools, the users, and the assignments of one team. It paces itself at one request per second, saves its progress to a file, and resumes from that file when you run it again.

    Before you begin:

    • Get a three-legged access token. See Get Started.
    • Save the call function from Retry example in a file named retry_example.py, in the same folder as the script below.
    • Replace <YOUR_ACCESS_TOKEN> and <YOUR_TEAM_ID>.
    import json
    import os
    import time
    
    from retry_example import call
    
    BASE = "https://developer.api.autodesk.com/team-admin/v1"
    TOKEN = "<YOUR_ACCESS_TOKEN>"
    TEAM_ID = "<YOUR_TEAM_ID>"
    CHECKPOINT = "sync_checkpoint.json"
    
    # Load progress from an earlier run, if there is one.
    state = {"pools": [], "pools_cursor": None, "pools_done": False,
             "users": [], "users_cursor": None, "users_done": False,
             "assignments": None}
    if os.path.exists(CHECKPOINT):
        with open(CHECKPOINT) as f:
            state = json.load(f)
    
    
    def save():
        with open(CHECKPOINT, "w") as f:
            json.dump(state, f)
    
    
    def get(path, **params):
        time.sleep(1)    # About one request per second.
        r = call("GET", f"{BASE}{path}", TOKEN, params=params)
        if r.headers.get("X-RateLimit-Remaining") == "0":
            # The allowance is used up: wait until it resets.
            reset = int(r.headers.get("X-RateLimit-Reset", 0))
            time.sleep(max(0, reset - time.time()))
        return r
    
    
    def read_pages(path, items, cursor_key, done_key=None):
        """Read every page of a list, saving the cursor after each page."""
        while True:
            params = {"limit": 100}
            if state[cursor_key]:
                params["cursor"] = state[cursor_key]
            r = get(path, **params)
            if r.status_code == 410:    # The saved cursor expired: start again.
                state[cursor_key] = None
                items.clear()
                continue
            r.raise_for_status()
            body = r.json()
            items.extend(body["data"])
            state[cursor_key] = body["pagination"]["cursor"]
            save()
            if not body["pagination"]["hasMore"]:
                if done_key:
                    state[done_key] = True
                    save()
                return
    
    
    # 1. Product pools: list them once and reuse the product IDs.
    if not state["pools_done"]:
        read_pages(f"/teams/{TEAM_ID}/product-pools", state["pools"], "pools_cursor", "pools_done")
    
    # 2. Users: 100 per page.
    if not state["users_done"]:
        read_pages(f"/teams/{TEAM_ID}/users", state["users"], "users_cursor", "users_done")
    
    # 3. Assignments: one request returns all of them.
    if state["assignments"] is None:
        r = get(f"/teams/{TEAM_ID}/assignments")
        r.raise_for_status()
        state["assignments"] = r.json()["data"]
        save()
    
    print(f"{len(state['pools'])} product pools, {len(state['users'])} users, "
          f"{len(state['assignments'])} assignments")
    
    Show More

    The script has three parts:

    • state and save(): state holds everything the script has read, and save() writes it to sync_checkpoint.json after every page.
    • read_pages(): reads a paginated list at limit=100, saves the items and the cursor after each page, and restarts the list if a saved cursor returns 410.
    • get(): waits one second before each request, and waits for the allowance to reset if X-RateLimit-Remaining reaches 0.

    If the script stops, run it again. It skips the lists it has already read, and it continues a partly read list from the saved cursor. Delete sync_checkpoint.json to start over.

    A long load can outlast your access token. If a request returns 401, get a new access token, put it in the script, and run it again. It resumes from the checkpoint.

    For 2,000 users, the script sends about 20 requests for the users, one for the product pools, and one for the assignments, so it finishes in about half a minute.

    Next: assign products from your sync

    The example only reads. To assign a product, use a productId from the product pools you read, and send one Assign Product request per user. Add the following function to the script, after get():

    QUOTA_EXHAUSTED = "https://developer.api.autodesk.com/problems/reassignment-quota-exhausted"
    
    
    def assign(user_id, product_id):
        time.sleep(1)    # About one request per second.
        r = call("POST", f"{BASE}/teams/{TEAM_ID}/assignments", TOKEN,
                 json={"userId": user_id, "productId": product_id})
        if r.status_code == 422 and r.json().get("type") == QUOTA_EXHAUSTED:
            # The reassignment quota is used up: stop until it resets.
            reset = r.json().get("data", {}).get("nextQuotaResetDate")
            raise SystemExit(f"Reassignment quota exhausted. Try again after {reset}.")
        r.raise_for_status()
        if r.json().get("reassignmentQuotaNearingLimit"):
            print("The team has used at least 80% of its reassignment quota for this pool.")
        return r.status_code    # 201: created. 200: the assignment already existed.
    
    Show More

    Warning: Assign Product assigns a seat to a real user. Test with a team that is safe to change.

    Use state["assignments"] to skip users who already hold the product. Assigning to 2,000 users takes 2,000 requests, so plan for at least 34 minutes, and save your progress after each user as the example does for pages. If the script stops, run it again: repeating Assign Product for a user who already holds the product is safe.

    When a successful response has reassignmentQuotaNearingLimit set to true, the team has used at least 80% of its reassignment quota for that pool. The request still succeeds. Slow down, or plan to stop. If the quota is used up, Assign Product rejects the request with 422 and the problem type reassignment-quota-exhausted. Don’t retry that request until the time in data.nextQuotaResetDate.

    See also