Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Be one of the first to start using Fabric Databases. View on-demand sessions with database experts and the Microsoft product team to learn just how easy it is to get started. Watch now

Reply
wcwright24
Regular Visitor

Post Import through REST API using Service Principal

Hello. I am currently trying to use the Power BI REST API to automate the process of moving PBI reports between workspaces in the Power BI Service to suit our organization's DevOps requirements. To start off, I wanted to try posting a simple import of a PBIX file to a workspace through the API using a service principal. The service principal has admin access to the workspace, and we have already been successful using the API to create, edit, and embed reports, as well as fetching all kinds of metadata from the API. However, when trying to access the Import endpoints, I am getting 403 Forbidden codes no matter what I do.

 

Here is a sample of what we are trying to do (this is a modified version of our app code):

// Note we are storing our app secret in a secure location
string secret = GetAppSecret();

// Token is Acquired and the PowerBI Client is instantiated
ClientCredential credential = new ClientCredential(APP_ID, secret);
AuthenticationResult ar = await authenticationContext.AcquireTokenAsync(ResourceUrl, credential);
TokenCredentials tc = new TokenCredentials(ar.AccessToken, "Bearer");
PowerBIClient c = new PowerBIClient(new Uri(ApiUrl), tc); 

// Use the CSharp PowerBI Client to post the import to the API.
// Note here that I am simply using a test file sitting on my hard drive.
string filePath = "C:/Work/Power BI/importtest.pbix";
string workspaceId = "foo";
using (Stream s = File.Open(filePath, FileMode.Open)) {
    // Posting the import with parameters: GroupId, Stream, datasetDisplayName
    // It is at this line that the code fails and a 403 Forbidden is returned.
    Import i = c.Imports.PostImportWithFileInGroup(workspaceId, s, "importtest");
}

 

I have tried going into the app registration for the service principal and enabling the Import endpoints in the API permissions, but it does not look like they are available there. Does this mean that it is not currently possible to post imports with a service principal? If that is the case, what is the recommended code workflow to do this through the API? Please provide samples if possible.

 

Thank you,

Walker

5 REPLIES 5
Jayendran
Solution Sage
Solution Sage

Hi @wcwright24 ,

 

Using PowerBIClient SDK is the more easier method, however can you try using the API directly . Please see the code reference below

 

public static void ImportPBIX(string pbixFilePath, string importName) {
      // delete exisitng import of the same name if on exists
      DeleteImport(importName);
      // create REST URL with import name in quer string
      string restUrlImportPbix = ProgramConstants.PowerBiServiceRootUrl + "imports?datasetDisplayName=" + importName;
      // load PBIX file into StreamContent object
      var pbixBodyContent = new StreamContent(File.Open(pbixFilePath, FileMode.Open));
      // add headers for request bod content
      pbixBodyContent.Headers.Add("Content-Type", "application/octet-stream");
      pbixBodyContent.Headers.Add("Content-Disposition",
                                   @"form-data; name=""file""; filename=""" + pbixFilePath + @"""");
      // load PBIX content into body using multi-part form data
      MultipartFormDataContent requestBody = new MultipartFormDataContent(Guid.NewGuid().ToString());
      requestBody.Add(pbixBodyContent);
      // create and configure HttpClient
      HttpClient client = new HttpClient();
      client.DefaultRequestHeaders.Add("Accept", "application/json");
      client.DefaultRequestHeaders.Add("Authorization", "Bearer " + AccessToken);
      // post request
      var response = client.PostAsync(restUrlImportPbix, requestBody).Result;
      // check for success
      if (response.StatusCode.ToString().Equals("Accepted")) {
        Console.WriteLine("Import process complete: " + response.Content.ReadAsStringAsync().Result);
      }

 

You can find the full source code from the below

 

https://github.com/CriticalPathTraining/PbixInstallerForPowerBI/blob/master/PbixInstallerForPowerBI/...

 

 

RashmiRaut
Frequent Visitor

Hi ,

 

Before import have you accessed, ADMIN Power BI rest API's via service principal...  can you help me out. I am able to generate token but not able to process. it gives unauthorized access. 

 

Thanks and Regards

 

 

 Hi Jayendran,

 

Thanks for the response. Just wanted to know, when we are trying to get data from Power BI admin rest API's through postman method, we are able to view it and access it. So if its sevice principle then ideally it should not give in postaman method as well, but its giving. But its not working for Visual studio. can you please give the code image here. or whole visual studio code if possible.

 

Thanks

Rashmi raut

 

 

Helpful resources

Announcements
Las Vegas 2025

Join us at the Microsoft Fabric Community Conference

March 31 - April 2, 2025, in Las Vegas, Nevada. Use code MSCUST for a $150 discount!

Dec Fabric Community Survey

We want your feedback!

Your insights matter. That’s why we created a quick survey to learn about your experience finding answers to technical questions.

ArunFabCon

Microsoft Fabric Community Conference 2025

Arun Ulag shares exciting details about the Microsoft Fabric Conference 2025, which will be held in Las Vegas, NV.

December 2024

A Year in Review - December 2024

Find out what content was popular in the Fabric community during 2024.