Forum Discussion

Zawadowski's avatar
Zawadowski
New Member
2 years ago

Get PowerBi Audience users via REST API?

Hi,

 

I've got a report showing all applications and users having access to these applications. Some of the applications have multiple audiences with different users assigned.

 

When querying PBI Service with GetAppUsersAsAdmin API call I am receiving a list of users but there is no audience name. In result, it seems like these users have access to all reports in the application which is obviously not correct.

 

Is this possible to somehow get app audience and associated users? Thanks!

14 Replies

  • anwarbham's avatar
    anwarbham
    Frequent Visitor

    Well i managed to extract the audiance data via the API you have to set a timer after each rest call for 2.5 seconds to avoid the "Too Many requests error"

    Code Below if anyone finds it usefull.

    def GET_GROUPS(WorkspaceId):    
        Token = 'Bearer TOKEN HERE'
    
        url = 'https://wabi-north-europe-l-primary-redirect.analysis.windows.net/metadata/appmodel/apps/'+WorkspaceId+'?requestDataType=7&access-control-allow-credentials=true';
        headers = {"Accept":"application/json","Authorization":Token}
    
        response = requests.get(url, headers = headers)
        if response.status_code == 200:
            return response.json()
        else:
            print("Error: ", response.status_code)
        return response.json()

    then you have to ge the Audience data.

    def Clean_Result(df,Group):
        #Create empty dataframe
        df_empty = pd.DataFrame(columns=['Group','providerId','AppId','AppDisplayName','AudienceName','reportId','Users','AdName'],dtype='string')
    
        #fill the empty dataframe with the values from the json file
    
        try:
            for i in range(len(df['appViewDetails'][0])):
                for j in range(len(df['appViewDetails'][0][i]['reportIds'])):
                    for k in range(len(df['appViewDetails'][0][i]['contentProviderPermissions']['adUserMetadataList'])):
                        new_row = pd.DataFrame({"Group": [Group], 
                                "providerId": [df['providerId'][0]]
                                ,"AppId": [df['providerKey'][0]]
                                ,"AppDisplayName": [df['displayText'][0]]
                                ,"AudienceName":[df['appViewDetails'][0][i]['viewName']]
                                ,"reportId":[df['appViewDetails'][0][i]['reportIds'][j]]
                                ,"Users":[df['appViewDetails'][0][i]['contentProviderPermissions']['adUserMetadataList'][k]['userPrincipalName']]
                                ,"AdName":[df['appViewDetails'][0][i]['contentProviderPermissions']['adUserMetadataList'][k]['displayName']]})
                        df_empty = df_empty.append(new_row)
    
            dfs['vw_Audience_tmp'] = pandas_to_spark(df_empty)
            return dfs['vw_Audience_tmp'] 
           
        except:
            print("No data for this group")
            return dfs['vw_Audience_tmp']

     

    stick this in a loop 

    with a timer

    for each in dfs['vw_Groups'].collect(): 
        time.sleep(2.5)       
        df = pd.json_normalize(GET_GROUPS(each['Id']))
        df2 = Clean_Result(df,each['Id'])
    
        if not df2.isEmpty():
            df3 =  df3.union(df2)
    
    dfs['vw_Audience2'] = df3
    
    dfs['vw_Audience2'].createOrReplaceTempView('vw_Audience2')

    its not perfect but it does the job untill MS decide to get an official API 

  • anwarbham's avatar
    anwarbham
    Frequent Visitor

    Hi there is an undocumented method but i cannot seem to get it working 

    if you make a get call to 

    https://wabi-north-europe-l-primary-redirect.analysis.windows.net/metadata/appmodel/apps/WoprkspaceORGroupID?requestDataType=7&access-control-allow-credentials=true 

     

    but you need a bearer token and our bearer token that can access other PBI api does not work.

    must be a permission issue .

    but if you copy a bearer token from when you log in to power bi via f12 developer mode it does work.

    i get a json response with the app and audiance name and members .

     

    if anyone can help me how to get the correct bearer token i would appreciate this.

     

     

    below is an extract 

     

     

     

     

  • Sabarivel's avatar
    Sabarivel
    Regular Visitor

    anwarbham , Thanks for sharing the unique information. Please let me know how to get the Report/Dashboard GUID and the visibilty for the Target Audiance group.
    The report id in the output of ['appViewDetails'] is '2202319' where as the actual report GUID is different. How to map and get the actual report id. I am trying to collect ist of Target Audiance Group, associated user/AD Group, List of visible reports.
    Appreciate your help.

    • anwarbham's avatar
      anwarbham
      Frequent Visitor

      Hi

      providerKey is the App ID ,
      if you use the power bi api reportsasadmin
      you have the reports linked to each app
      in my case it was 
      with reports as
      (
      select
      distinct
      appId,
      id,
      name
      from
      reportsasadmin
      )
      select distinct
      audience.AudienceName,
      audience.providerId,
      audience.AppId,
      audience.AppDisplayName,
      audience.Users,
      audience.AdName,
      audience.`Group`,
      reports.id as ReportId,
      reports.name as ReportName
       
      from audience
      left join reports on reports.appid = audience.AppId
       
      order by AudienceName, Users asc

       

      • Sabarivel's avatar
        Sabarivel
        Regular Visitor

        anwarbham thanks for the explaination. Here I am trying to get the list of reports the traget audiance group has access to. The reportIds[] array has list of visibile reports for each target audiance group. This array dosent have actual report GUID.Instead it has '2202319'.So how can I get the reports for each target audiance group?

        Please advise. 




  • Hi @

    Why you don’t see audience info in GetAppUsersAsAdmin

    • The GetAppUsersAsAdmin endpoint only returns the flattened list of principals (users, groups, service principals) who can access the app.

      1. Use workspace access as a proxy
        If your app audiences mirror workspace role assignments, you can query GetWorkspaceUsersAsAdmin. But this usually won’t be precise, since audiences are finer-grained than workspace roles.

      2. Maintain your own “audience-to-user” mapping
        Many organizations store the intended mapping in Azure AD groups. If each audience = one AAD group, then your app audience definition is just those groups. You can query group membership directly from Microsoft Graph.

        Manual extraction
        Right now, the only source of truth is the Power BI Service UI. If you need this data programmatically, it unfortunately requires manual export (or automation via UI scraping / Selenium, which is brittle and unsupported).

        To answer directly

        Is it possible to get app audience and associated users via API?

        ❌ Not currently. The Power BI REST API does not return audience-level membership for apps. You only get the union of all users with any audience access.

        Did I answer your question? Mark my post as a solution! Appreciate your Kudos !!

      3. It does not return which audience those users belong to. That’s why in your results, it looks as if every user can see all app content, even though in the UI they are scoped to audiences.

        This isn’t a bug in your call — it’s a documented gap: audience membership is not exposed by the Admin APIs today.

        What’s available today

        Via the Power BI REST APIs, there is no public endpoint to list app audiences or to enumerate users per audience.

        Microsoft’s docs for audiences (e.g. Power BI audiences overview) are end-user focused; no corresponding admin API exists.

        WorkaroundsIn the Service UI (Apps → Manage audiences), you can clearly see the mapping of audiences to users/groups.

    • anwarbham's avatar
      anwarbham
      Frequent Visitor

      sure but its been 3 years and no update from ms if this will be a available

  • anwarbham's avatar
    anwarbham
    Frequent Visitor

    one thing to note there is a new permission group that MS have includes Workspaceusers in audiances by default. 

    anyone who has access to the Workspace has access to the apps in the audiance group . 

    my solution cannot see this user group , i guess its because its propagated from the workspaces.  but having good governance will allow you to include these users.