Fetch all Azure Users via MsGraph and a Recursive Query in a Workflow

Hello Everyone,

I wanted to share a personal win for others that might also be using Azure and the MsGraph API as a resource.

Here is a way to get all users, by utilizing server-side pagination and the returned @odata.nextLink

Step 1

  • Make a function that uses the MsGraph as a resource. (Mine is GetUsers <- Note this for step 2)

image

  • Add skipToken as a parameter
  • You can change your $top amount to whatever (less than 999 I think)
  • $skipToken will be {{ typeof skipToken === "string" ? skipToken : "" }}
    • This will allow the first fetch to pass with no token

Step 2

  • Create a code block with this content
const users = [];

let token = null;

do {
  // This is your function 👇🏻 from step 1
  const res = (await GetUsers(token)).data;
  users.push(...res.value);

  if (!res?.["@odata.nextLink"]) {
    // No more "nextLink"s so we are done
    token = null
  } else {
    // Extract the "nextLink"s skipToken to use for next loop
    const url = new URL(res?.["@odata.nextLink"]);
    const params = new URLSearchParams(url.search);
    token = params.get("$skipToken");
  }
} while (typeof token === "string")

return users;
  • This will call the function with no token, and then loop until there is no more nextLinks and then return.

Cheers :tada:

1 Like