Join us at FabCon Atlanta from March 16 - 20, 2026, for the ultimate Fabric, Power BI, AI and SQL community-led event. Save $200 with code FABCOMM.
Register now!The Power BI Data Visualization World Championships is back! Get ahead of the game and start preparing now! Learn more
Hello,
I was wondering if anyone has experiance to use the Power BI API in C#?
I have created a C# .NET Console App using the PowerBI API Library to connect to the Power BI API to get a list of groups, reports, etc. I would like to use the application I am creating to access the Power BI API and get data so I can automate the analyze and audit processes.
Prior to programming I went into Azure and set up the App Registration per this document: https://www.vahiddm.com/post/call-power-bi-rest-api-with-power-automate
My C# application, I can get the token but then I get a 401 Un-authorized error. Here is the error information I get:
Non-admin groups: 0
Status: 401 Unauthorized
Response content:
Pragma: no-cache
Transfer-Encoding: chunked
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Frame-Options: deny
X-Content-Type-Options: nosniff
RequestId: 2ad55907-50ad-49e8-964b-9a7d9de14eef
Access-Control-Expose-Headers: RequestId
Cache-Control: no-store, must-revalidate, no-cache
Date: Tue, 06 Jan 2026 21:01:31 GMT
Content-Type: application/octet-stream
Here is my code that I am using:
class PowerBI
{
public async System.Threading.Tasks.Task getPowerBIWorkspaceData()
{
//instantiate the api object
API api = new API();
string accessToken = await api.getPowerBIAccessToken();
Console.WriteLine(accessToken);
var credentials = new TokenCredentials(accessToken, "Bearer");
var apiUrl = "https://[Removed]"; // Base URL for the Power BI Service API
using (var client = new PowerBIClient(new Uri(apiUrl), credentials))
{
try
{
var g = await client.Groups.GetGroupsAsync();
Console.WriteLine($"Non-admin groups: {g.Value?.Count ?? 0}");
// Example: Get a list of workspaces (groups)
var workspaces = await client.Groups.GetGroupsAsAdminAsync(top: 500);
Console.WriteLine($"Found {workspaces.Value?.Count ?? 0} workspaces.");
// You can now call other APIs, e.g., to get reports in a specific workspace
if (workspaces.Value.Count > 0)
{
var groupId = workspaces.Value[0].Id;
var reports = await client.Reports.GetReportsInGroupAsync(groupId);
Console.WriteLine($"Workspace has {reports.Value.Count} reports.");
}
}
catch (Microsoft.Rest.HttpOperationException ex)
{
Console.WriteLine($"Status: {(int)ex.Response.StatusCode} {ex.Response.StatusCode}");
Console.WriteLine("Response content:");
Console.WriteLine(ex.Response.Content);
// If headers exist, print them (sometimes the key clue is here)
if (ex.Response.Headers != null)
{
foreach (var h in ex.Response.Headers)
Console.WriteLine($"{h.Key}: {string.Join(",", h.Value)}");
}
throw;
}
}
}
}
Any help would be appreciated.
Thanks,
Tim
Thank you @Ahmed-Elfeel and @v-veshwara-msft for you help.
I followed the information you sent me. After reviewing, I couldn't find anything wrong so I went to this page: https://learn.microsoft.com/en-us/rest/api/power-bi/admin/groups-get-groups-as-admin?tryIt=true&sour...
I copied the Bearer Token from the page and then pasted it into my C# app and got this message:
Non-admin groups: 2
Found 238 workspaces.
Status: 401 Unauthorized
Response content:
X-PowerBI-Error-Info: GroupNotAccessible
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Frame-Options: deny
X-Content-Type-Options: nosniff
Access-Control-Expose-Headers: RequestId,X-PowerBI-Error-Info
request-redirected: true
home-cluster-uri: https://wabi-germany-west-central-primary-redirect.analysis.windows.net/
RequestId: 49a16e45-e847-4323-a0b1-04f97ae4111f
Date: Thu, 08 Jan 2026 00:43:37 GMT
Content-Length: 0
You can see that worked and it returned 238 workspaces.
That leads me to believe that I am getting the wrong token when I call my API my getToken Method.
Here is my code for getting the token:
class API
{
public async Task<string> getPowerBIAccessToken()
{
var tenantId = "removed";
var clientId = "removed";
var clientSecret = "removed";
// The Power BI API scope
var scopes = new[] { "https://analysis.windows.net/powerbi/api/.default" };
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
.Build();
var authResult = await app.AcquireTokenForClient(scopes).ExecuteAsync();
return authResult.AccessToken;
}
}It returns a token but obvisouly an invalid one. Any help would be appreciated to tell me why I am getting a token that doesn't work and how to get one that works.
Thanks,
Tim
Hi @bigmac025 ,
I am not sure which of the API calls fails for you, I can see 2 at least different ones in the code you've shared:
var workspaces = await client.Groups.GetGroupsAsAdminAsync(top: 500);
var reports = await client.Reports.GetReportsInGroupAsync(groupId);
If the service principal is a tenant admin then the first one should work.
For the second one to work the service principal need to be at least a viewer in the workspace. Not every admin user can call this API for any workspace in the tenant. Can this be the reason?
Hi @bigmac025 ,
Thanks for sharing the additional details and for testing with the token from the Try It experience.
The AcquireTokenForClient call and the scope you are using are correct, and the token itself is being accepted by the Power BI service.
The important clue is the response header X-PowerBI-Error-Info: GroupNotAccessible. This indicates an authorization issue at the workspace level, not a problem with the token.
In the code you shared, GetGroupsAsync() is still being executed. This API is user scoped and is not supported when using service principal (app only) authentication.
Enable service principal authentication for admin APIs - Microsoft Fabric | Microsoft Learn
You are also calling non admin APIs such as GetReportsInGroupAsync. For these calls, the service principal must be explicitly granted access to the workspace, either directly or via an Entra ID security group, with at least Viewer permissions. Without workspace access, Power BI will return 401 or 403 even with a valid token.
For tenant wide discovery using a service principal, GetGroupsAsAdminAsync() is the supported approach. For any workspace scoped operations, ensure the service principal has access to the target workspace.
So the issue is caused by a mismatch between the API being called and the authorization context, rather than an invalid or expired token.
Hope this helps. Please reach out for further assistance.
Thank you.
Hi @bigmac025 ,
Just wanted to check if the responses provided were helpful. If further assistance is needed, please reach out. Also thanks @AmosHersch for sharing your insights.
Thank you.
Hi @bigmac025,
Your Code almost fine and the 401 error is caused due to authentication configuration (not the Power BI SDK itself)
Also the two biggest issues I see are token audience and admin or service principal permissions that caused this issue.
Keep in mind even if you successfully get a token....Power BI will return 401 if the token was issued for the wrong resource So when using client credentials the token must be requested with this scope:
https://analysis.windows.net/powerbi/api/.default
var apiUrl = "https://api.powerbi.com/";
Also you need to know that GetGroupsAsAdminAsync() requires admin or service principal setup
The token belongs to a Power BI / Fabric Admin user or you are using a service principal (and Allow service principals to use Power BI APIs is enabled in Power BI Admin Portal)
client.Groups.GetGroupsAsync()
Otherwise Power BI will return 401 or 403, even with a valid token)
Hi @bigmac025 ,
Thanks for reaching out to Microsoft Fabric Community and for sharing the document reference.
When using GetGroupsAsAdminAsync() with service principal authentication, Power BI validates tenant level settings and admin role assignment rather than delegated scopes. In the Power BI Admin portal, ensure that Allow service principals to use Power BI APIs is enabled under Tenant settings, and that your service principal or the security group containing it is added to the allowed list. The service principal must also have Fabric Admin role assigned. If any of these are missing, the API returns 401 even with a valid token.
This behavior is documented here:
Embed Power BI content in an embedded analytics application with service principal and an applicatio...
Admin - Groups GetGroupsAsAdmin - REST API (Power BI Power BI REST APIs) | Microsoft Learn
Enable service principal authentication for admin APIs - Microsoft Fabric | Microsoft Learn
There are also similar community threads where the same issue was resolved by updating tenant settings or admin role assignment:
Solved: Re: Power Bi REST API - 401 Authorization error wh... - Microsoft Fabric Community
Solved: Re: Unauthorized 401 when accessing Power BI Admin... - Microsoft Fabric Community
Once the service principal is enabled in the tenant settings and has the required admin role, the existing API calls should work as expected.
Hope this helps. Please reach out for further assistance.
Thank you.
The Power BI Data Visualization World Championships is back! Get ahead of the game and start preparing now!
| User | Count |
|---|---|
| 3 | |
| 3 | |
| 2 | |
| 2 | |
| 1 |
| User | Count |
|---|---|
| 5 | |
| 5 | |
| 4 | |
| 4 | |
| 3 |