### Run the Sample App with npm Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-sample-for-your-organization_tabs=net-core This command executes the Power BI embedding sample application after all dependencies have been installed. It starts the development server, and you can access the application through your browser. ```bash npm run start ``` -------------------------------- ### Install Dependencies and Run Application (Node.js) Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-sample-for-your-organization Installs the necessary project dependencies using npm and then starts the embedded application. These commands are essential for running the sample application locally. ```bash npm install npm run start ``` -------------------------------- ### Install Node.js Dependencies and Run Project Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-sample-for-customers This section covers the installation of Node.js project dependencies using npm and how to run the embedded Power BI application. It includes commands for installation and starting the development server. ```bash npm install npm start ``` -------------------------------- ### Install Power BI Embedded Azure CLI Extension Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/azure-pbie-create-capacity_source=recommendations Install the extension for Power BI embedded capacity by running the following command. ```APIDOC ## Install Power BI Embedded Azure CLI Extension ### Description Installs the Azure CLI extension for Power BI embedded capacity management. ### Method ```azurecli az extension add ``` ### Endpoint `az extension add --name powerbidedicated` ### Parameters None ### Request Example ```azurecli az extension add --name powerbidedicated ``` ### Response No specific response details provided for installation success or failure in the source text. ``` -------------------------------- ### Install Python Dependencies and Run Project Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-sample-for-customers This section details the steps to set up a Python project for embedding Power BI content. It includes installing necessary packages using pip and running the Flask application. ```bash pip3 install -r requirements.txt flask run ``` -------------------------------- ### Install Dependencies - Python Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-sample-for-customers_source=recommendations&tabs=net-core Installs Python packages required for the 'Embed for your customers' project from the 'requirements.txt' file. Ensure you are in the correct directory before executing. ```bash pip3 install -r requirements.txt ``` -------------------------------- ### App-owns-data Hello World Example Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/dev-camp-links_tabs=app-owns-data-tutorials%2Capp-owns-data-examples A minimal .NET 5 application example for embedding Power BI reports or paginated reports using the app-owns-data model. It supports running in Visual Studio Code or Visual Studio 2019 and includes configuration details for different Power BI clouds. ```csharp /* * This is a simplified C# example for a "Hello World" Power BI embed in an App-owns-data scenario. * It assumes the Power BI .NET SDK is installed and configured. */ using Microsoft.PowerBI.Api; using Microsoft.PowerBI.Api.Models; using Microsoft.Rest; using System; using System.Threading.Tasks; public class AppOwnsDataHelloWorld { public async Task EmbedReportAsync(string accessToken, string workspaceId, string reportId) { var tokenCredentials = new TokenCredentials(accessToken, "Bearer"); var client = new PowerBIClient(new Uri("https://api.powerbi.com"), tokenCredentials); try { var report = await client.Reports.GetReportInGroupAsync(workspaceId, reportId); Console.WriteLine($"Successfully retrieved report: {report.Name}"); // In a real application, you would use the report details to generate an embed URL // and pass it to a client-side JavaScript embedder. var embedUrl = $"https://app.powerbi.com/groups/{workspaceId}/reports/{reportId}"; Console.WriteLine($"Embed URL (for client-side embedding): {embedUrl}"); } catch (Exception ex) { Console.WriteLine($"Error embedding report: {ex.Message}"); } } } ``` -------------------------------- ### Install Power BI Embedded CLI Extension Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/azure-pbie-create-capacity_tabs=portal Install the extension for Power BI embedded capacity by running the following command. ```APIDOC ## Install Power BI Embedded CLI Extension ### Description Install the extension for Power BI embedded capacity. ### Method AZ CLI ### Endpoint N/A ### Command ```azurecli az extension add --name powerbidedicated ``` ``` -------------------------------- ### Install Power BI Embedded CLI Extension Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/azure-pbie-create-capacity_source=recommendations&tabs=portal Installs the extension for Power BI embedded capacity. ```APIDOC ## Install Power BI Embedded CLI Extension ### Description Installs the extension for Power BI embedded capacity. ### Method Azure CLI Command ### Endpoint N/A ### Parameters None ### Request Example ```azurecli az extension add --name powerbidedicated ``` ### Response Success: Extension installed. Error: Extension installation failed. ``` -------------------------------- ### App-owns-data Multitenant Example Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/dev-camp-links_tabs=app-owns-data-tutorials%2Capp-owns-data-examples This example showcases using service principal profiles to manage a multitenant environment with Power BI app-owns-data embedding. It demonstrates how to isolate data and user experiences across different tenants. ```csharp /* * This is a placeholder for C# code demonstrating multitenant Power BI embedding using Service Principal Profiles. * This requires creating and managing profiles within the Power BI service. */ using Microsoft.PowerBI.Api; using Microsoft.PowerBI.Api.Models; using Microsoft.Rest; using System; using System.Threading.Tasks; public class MultitenantPowerBiService { public async Task EmbedReportForTenantAsync(string accessToken, string workspaceId, string reportId, string profileId) { var tokenCredentials = new TokenCredentials(accessToken, "Bearer"); var client = new PowerBIClient(new Uri("https://api.powerbi.com"), tokenCredentials); // To use Service Principal Profiles, you typically create a GenerateTokenRequest // and specify the profile within the request if the API supports it directly, // or manage the service principal context per profile. // Placeholder for generating token with profile context var generateTokenRequestParameters = new GenerateTokenRequest( accessLevel: "View", datasets: null, // Could specify dataset with profile context if needed reports: new[] { new EffectiveIdentity("ReportId", reportId, null, null, null) }, targetWorkspaces: null ); // The actual mechanism to apply a profile might vary. Often it involves // using a specific Service Principal for each tenant or specifying profile ID // in the API call if supported. Example assumes a hypothetical profile parameter. try { // Hypothetical call or setup to use the profile // var embedConfig = await client.Reports.GenerateTokenWithProfileAsync(workspaceId, reportId, profileId, generateTokenRequestParameters); Console.WriteLine($"Attempting to embed report '{reportId}' for tenant using profile ID '{profileId}'."); // Actual embed token generation and response handling would follow. } catch (Exception ex) { Console.WriteLine($"Error embedding report for multitenant scenario: {ex.Message}"); } } } ``` -------------------------------- ### App-owns-data Embedding with .NET 5 Tutorial Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/dev-camp-links_tabs=app-owns-data-tutorials%2Capp-owns-data-examples This tutorial guides developers in creating a .NET 5 MVC web application for app-owns-data Power BI embedding. It covers advanced topics like TypeScript integration with Node.js and programming the Power BI REST API for multi-resource access tokens. ```csharp /* * This is a placeholder for code that would be part of the .NET 5 App-owns-data embedding tutorial. * The actual code would involve setting up an MVC project, integrating Power BI SDK, * and making API calls to the Power BI service. */ using Microsoft.PowerBI.Api; using Microsoft.PowerBI.Api.Models; using Microsoft.Rest; using System.Threading.Tasks; public class PowerBiService { private readonly string _accessToken; private readonly string _workspaceId; private readonly string _reportId; public PowerBiService(string accessToken, string workspaceId, string reportId) { _accessToken = accessToken; _workspaceId = workspaceId; _reportId = reportId; } public async Task GetReportAsync() { var tokenCredentials = new TokenCredentials(_accessToken, "Bearer"); var client = new PowerBIClient(new Uri("https://api.powerbi.com"), tokenCredentials); var report = await client.Reports.GetReportInGroupAsync(_workspaceId, _reportId); return report; } } ``` ```typescript // This is a placeholder for TypeScript code that might be used on the client-side // or for Node.js integration as mentioned in the tutorial. function embedReport(token: string, embedUrl: string, id: string): void { // Logic to embed the Power BI report using the Power BI JavaScript SDK console.log(`Embedding report with ID: ${id} using token: ${token} and embed URL: ${embedUrl}`); } // Example usage: // embedReport("your_access_token", "https://app.powerbi.com/groups/...", "your_report_id"); ``` -------------------------------- ### Start Node.js Application Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-sample-for-customers_source=recommendations&tabs=net-core Starts the 'App Owns Data' Node.js project. After running this command, the application will be accessible at http://localhost:5300. ```bash npm start ``` -------------------------------- ### Install Dependencies - Node.js Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-sample-for-customers_source=recommendations&tabs=net-core Installs the necessary Node.js packages for the 'App Owns Data' Power BI embedding project. This command should be run from the project's root directory. ```bash npm install ``` -------------------------------- ### Windows and Basic Credentials Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/configure-credentials Examples for creating Windows and Basic credentials using the .NET SDK for Power BI Embedded. ```APIDOC ## Windows and Basic Credentials ### Description Examples for creating Windows and Basic credentials using the .NET SDK for Power BI Embedded. ### Method N/A (Code Examples) ### Endpoint N/A (Code Examples) ### Parameters N/A (Code Examples) ### Request Example ```csharp // Windows credentials var credentials = new WindowsCredentials(username: "john", password: "*****"); // Or // Basic credentials var credentials = new BasicCredentials(username: "john", password: "*****"); var credentialsEncryptor = new AsymmetricKeyEncryptor(publicKey); var credentialDetails = new CredentialDetails(credentials, PrivacyLevel.Private, EncryptedConnection.Encrypted, credentialsEncryptor); ``` ### Response N/A (Code Examples) ### Response Example ```csharp { "credentialData": [ {"name": "username", "value": "john"}, {"name": "password", "value": "*****"} ] } ``` ``` -------------------------------- ### Get Gateways API Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/configure-credentials_source=recommendations Retrieves a list of available gateways. This is a prerequisite step for configuring data sources, as it provides the necessary gateway ID. ```APIDOC ## GET /api/gateways ### Description Retrieves a list of all available Power BI gateways. This endpoint is used to discover gateways and obtain their unique identifiers, which are needed for subsequent operations like creating or updating data sources. ### Method GET ### Endpoint `/gateways` ### Parameters #### Query Parameters (No query parameters are specified in the provided text for this endpoint.) ### Request Example ```csharp // Assuming 'pbiClient' is an authenticated Power BI client instance var gateways = pbiClient.Gateways.GetGateways().Value; var gateway = gateways.First(); // Example of selecting the first gateway ``` ### Response #### Success Response (200) - **Value** (array of Gateway) - A list of gateway objects, each containing details like GatewayId. ``` -------------------------------- ### Key Credentials Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/configure-credentials Examples for creating Key credentials using the .NET SDK for Power BI Embedded. ```APIDOC ## Key Credentials ### Description Examples for creating Key credentials using the .NET SDK for Power BI Embedded. ### Method N/A (Code Examples) ### Endpoint N/A (Code Examples) ### Parameters N/A (Code Examples) ### Request Example ```csharp var credentials = new KeyCredentials("TestKey"); var credentialsEncryptor = new AsymmetricKeyEncryptor(publicKey); var credentialDetails = new CredentialDetails(credentials, PrivacyLevel.Private, EncryptedConnection.Encrypted, credentialsEncryptor); ``` ### Response N/A (Code Examples) ### Response Example ```json { "credentialData": [ {"name": "key", "value": "ec....LA="} ] } ``` ``` -------------------------------- ### Power BI Embedded C# SDK Examples Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/change-permissions_source=recommendations Examples demonstrating how to manage Power BI embedded applications and permissions using the Microsoft Graph SDK for C#. ```APIDOC ## C# SDK Examples for Power BI Embedded ### Description Provides C# code snippets for common tasks in Power BI embedded development, including creating applications, secrets, service principals, and retrieving permission grants. ### Code Snippets #### Create Application, Secret, and Service Principal ```csharp // Assuming 'GetGraphClient()' and 'application' are defined elsewhere var graphClient = GetGraphClient(); // Create application currentState.createdApp = await graphClient.Applications .Request() .AddAsync(application); System.Threading.Thread.Sleep(2000); // Add password credential (client secret) var passwordCredential = new PasswordCredential { DisplayName = "Client Secret Created in C#" }; currentState.createdSecret = await graphClient.Applications[currentState.createdApp.Id] .AddPassword(passwordCredential) .Request() .PostAsync(); // Create service principal var servicePrincipal = new ServicePrincipal { AppId = currentState.createdApp.AppId }; currentState.createdServicePrincipal = await graphClient.ServicePrincipals .Request() .AddAsync(servicePrincipal); ``` #### Retrieve an OAuth2PermissionGrant ```csharp // Assuming 'authProvider' is a valid authentication provider GraphServiceClient graphClient = new GraphServiceClient(authProvider); // Get a specific OAuth2PermissionGrant by its ID var oAuth2PermissionGrant = await graphClient.Oauth2PermissionGrants["{id}"] .Request() .GetAsync(); ``` ### Notes - Ensure you have the necessary Microsoft Graph SDKs installed. - Replace `{id}` with the actual ID of the OAuth2PermissionGrant you want to retrieve. - The `GetGraphClient()` method should be implemented to provide an authenticated `GraphServiceClient` instance. ``` -------------------------------- ### Get Datasources Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/configure-credentials_source=recommendations Retrieves a list of data sources for a given semantic model. This is the first step in discovering data source details required for credential configuration. ```APIDOC ## GET /api/datasets/{datasetId}/datasources ### Description Retrieves a list of data sources for a given semantic model. This is the first step in discovering data source details required for credential configuration. ### Method GET ### Endpoint /api/datasets/{datasetId}/datasources ### Parameters #### Path Parameters - **datasetId** (string) - Required - The ID of the dataset. ### Response #### Success Response (200) - **value** (array) - A list of data source objects. - **type** (string) - The type of the data source. - **connectionDetails** (string) - The connection details for the data source. - **gateway** (object) - Information about the gateway associated with the data source. - **gatewayId** (string) - The ID of the gateway. - **datasourceId** (string) - The ID of the data source. #### Response Example ```json { "value": [ { "type": "Mysql", "connectionDetails": "{\"serverName\":\"myserver.database.windows.net\", \"databaseName\":\"mydatabase\"}", "gateway": { "gatewayId": "gateway-123" }, "datasourceId": "datasource-abc" } ] } ``` ``` -------------------------------- ### Access Token Examples in C# Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-sample-for-customers-national-clouds Examples of obtaining access tokens from Microsoft Entra ID are available within the `Controllers/HomeController.cs` file of the Power BI embedded analytics samples. These tokens are required to authenticate API calls to the Power BI REST API. ```csharp // Example usage within Controllers/HomeController.cs // The actual token acquisition logic will be implemented here. // Refer to the specific file for complete implementation details. ``` -------------------------------- ### Key Credentials (.NET SDK v3) Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/configure-credentials_source=recommendations Illustrates the usage of key-based authentication with the .NET SDK v3, including creating KeyCredentials and CredentialDetails. ```csharp var credentials = new KeyCredentials("TestKey"); var credentialsEncryptor = new AsymmetricKeyEncryptor(publicKey); var credentialDetails = new CredentialDetails(credentials, PrivacyLevel.Private, EncryptedConnection.Encrypted, credentialsEncryptor); ``` -------------------------------- ### Set up the Gateway Data Source Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/sql-server-analysis-services-embed_source=recommendations&tabs=master-user%2Cmaster-user-token Configure a data source connection to the SSAS gateway. This involves providing details such as datasource name, type, server, database, and user credentials. ```APIDOC ## POST /api/gateways/datasources ### Description Add a data source connection to the SSAS gateway. ### Method POST ### Endpoint /api/gateways/datasources ### Parameters #### Request Body - **datasourceName** (string) - Required - The name for the data source. - **datasourceType** (string) - Required - The type of the data source (e.g., 'SQL Server Analysis Services'). - **server** (string) - Required - The server name or address. - **database** (string) - Required - The database name. - **username** (string) - Required - The username for authentication. - **password** (string) - Required - The password for authentication. ### Request Example ```json { "datasourceName": "MySSASDataSource", "datasourceType": "SQL Server Analysis Services", "server": "your_ssas_server.yourdomain.com", "database": "SSASDatabase", "username": "your_username", "password": "your_password" } ``` ### Response #### Success Response (200) - **datasourceId** (string) - The unique identifier of the created data source. #### Response Example ```json { "datasourceId": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### API Request with Profile ID Header (REST) Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/service-principal-profile-sdk_source=recommendations Example of a REST API GET request to retrieve groups. It includes the 'Authorization' header for authentication and the 'X-PowerBI-profile-id' header to specify the service principal profile. ```rest GET https://powerbiapi.analysis-df.windows.net/v1.0/myorg/groups Authorization: Bearer eyJ0eXAiO.....5U_g X-PowerBI-profile-id: 81f24a6d-7ebb-4478-99c7-2c36f7870a26 ``` -------------------------------- ### Check Authorization Header and Refresh Token (Console) Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/troubleshoot-rest-api_source=recommendations This snippet shows an example of a GET request to a Power BI Analysis Services cluster, including an Authorization header with a Bearer token. It also illustrates a typical 403 Forbidden response with an error message indicating a token expiration, suggesting the need to refresh the access token before calling the GenerateToken API. ```console GET https://wabi-us-north-central-redirect.analysis.windows.net/metadata/cluster HTTP/1.1 Host: wabi-us-north-central-redirect.analysis.windows.net ... Authorization: Bearer eyJ0eXAiOi... ... HTTP/1.1 403 Forbidden ... {"error":{"code":"TokenExpired","message":"Access token has expired, resubmit with a new access token"}} ``` -------------------------------- ### Power BI Embedded Showcases - GitHub Repository Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/power-bi-playground_source=recommendations The showcases provide interactive examples of Power BI API features within applications. The source code for these showcases is publicly available on GitHub, enabling developers to study and adapt them for their own projects. ```GitHub https://github.com/microsoft/PowerBI-Embedded-Showcases/ ``` -------------------------------- ### GET Request for Power BI Groups with Profile Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-multi-tenancy This example demonstrates how an ISV app calls Power BI REST APIs using a service principal Microsoft Entra token and a profile ID to retrieve groups. The Authorization header contains the bearer token, and the X-PowerBI-Profile-Id header specifies the profile for the request. ```HTTP GET https://api.powerbi.com/v1.0/myorg/groups HTTP/1.1 Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUz.....SXBwasfg X-PowerBI-Profile-Id: 5f1aa5ed-5983-46b5-bd05-999581d361a5 ``` -------------------------------- ### Get Workspace ID using Get Groups API Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-organization-app_source=recommendations Retrieve the Workspace ID programmatically by calling the Get Groups API. This is useful when you need to automate the process of finding workspace identifiers. ```HTTP GET https://api.powerbi.com/v1.0/myorg/groups ``` -------------------------------- ### Power BI PowerShell Tutorial Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/dev-camp-links This tutorial provides student files for learning Power BI with PowerShell. It enables automation of Power BI tasks, management of datasets, reports, and workspaces, and interaction with the Power BI service through scripting. ```PowerShell # This is a placeholder for PowerShell commands related to the Power BI PowerShell tutorial. # It would typically involve using the "MicrosoftPowerBIMgmt" PowerShell module. # Example: Connecting to Power BI service # Import-Module MicrosoftPowerBIMgmt # Connect-PowerBIRestService -Environment "common" # Example: Getting all workspaces # Get-PowerBIWorkspace # Example: Getting all reports in a workspace # Get-PowerBIReport -Scope "Workspace" -WorkspaceId "" # Example: Importing a PBIX file and publishing it as a dataset # Publish-PowerBIDataset -Path "C:\path\to\your\report.pbix" -Name "MyNewDataset" -WorkspaceId "" # Example: Refreshing a dataset # Start-PowerBIRefresh -ObjectId "" -ObjectType "Dataset" -WorkspaceId "" # Note: Actual commands and parameters would be detailed in the tutorial files. Write-Host "PowerShell commands for Power BI management can be executed here." ``` -------------------------------- ### Basic Credentials (.NET SDK v3) Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/configure-credentials_source=recommendations Demonstrates how to use basic username and password authentication with the .NET SDK v3. It involves creating a WindowsCredentials object and then a CredentialDetails object with an encryptor. ```csharp var credentials = new WindowsCredentials(username: "john", password: "*****"); // Or // Basic credentials var credentials = new BasicCredentials(username: "john", password: "*****"); var credentialsEncryptor = new AsymmetricKeyEncryptor(publicKey); var credentialDetails = new CredentialDetails(credentials, PrivacyLevel.Private, EncryptedConnection.Encrypted, credentialsEncryptor); ``` -------------------------------- ### Get Report ID using Get Reports In Group API Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-organization-app_source=recommendations Obtain the Report ID programmatically by utilizing the Get Reports In Group API. This allows for fetching report identifiers within a specific workspace. ```HTTP GET https://api.powerbi.com/v1.0/myorg/groups/{groupId}/reports ``` -------------------------------- ### App-owns-data and Row-Level Security (RLS) Example Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/dev-camp-links_tabs=app-owns-data-tutorials%2Capp-owns-data-examples This example demonstrates a .NET 5 web application using Power BI app-owns-data embedding, specifically focusing on implementing a security authorization model with EffectiveIdentity and row-level security (RLS). ```csharp /* * This is a placeholder for C# code demonstrating App-owns-data embedding with RLS. * It involves creating an EffectiveIdentity when generating the embed token. */ using Microsoft.PowerBI.Api; using Microsoft.PowerBI.Api.Models; using Microsoft.Rest; using System; using System.Threading.Tasks; public class RlsPowerBiService { public async Task EmbedReportWithRlsAsync(string accessToken, string workspaceId, string reportId, string rlsUsername, string rlsRole) { var tokenCredentials = new TokenCredentials(accessToken, "Bearer"); var client = new PowerBIClient(new Uri("https://api.powerbi.com"), tokenCredentials); var effectiveIdentity = new EffectiveIdentity { Username = rlsUsername, Roles = new[] { rlsRole }, DatasetId = "YOUR_DATASET_ID" // Specify the Dataset ID associated with the report }; var generateTokenRequestParameters = new GenerateTokenRequest( accessLevel: "View", datasets: new[] { effectiveIdentity }, reports: new[] { new EffectiveIdentity("ReportId", reportId, null, null, null) }, // Report embedding requires ReportId in EffectiveIdentity targetWorkspaces: null ); try { var embedConfig = await client.Reports.GenerateTokenForUserAsync(reportId, generateTokenRequestParameters); // Use GenerateTokenForUser for RLS Console.WriteLine($"Successfully generated embed token for user '{rlsUsername}' with role '{rlsRole}'. Embed Token: {embedConfig.Token}"); } catch (Exception ex) { Console.WriteLine($"Error generating RLS embed token: {ex.Message}"); } } } ``` -------------------------------- ### Configure Data Source for Data Gateway Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/configure-credentials_source=recommendations Guides through the process of configuring a new data source for a data gateway, including retrieving gateway information, building credential details, and creating the data source. ```APIDOC ## POST /api/gateways/{gatewayId}/datasources ### Description Creates a new data source entry for a specified Power BI gateway. This involves providing the gateway ID, the type of data source, connection details, credential information, and a name for the data source. ### Method POST ### Endpoint `/gateways/{gatewayId}/datasources` ### Parameters #### Path Parameters - **gatewayId** (string) - Required - The unique identifier of the gateway. #### Request Body - **dataSourceType** (string) - Required - The type of the data source (e.g., "SQL"). - **connectionDetails** (string) - Required - A JSON string representing the connection details for the data source (e.g., server and database). - **credentialDetails** (CredentialDetails) - Required - An object containing the credential information, potentially encrypted. - **dataSourceName** (string) - Required - The name to assign to the new data source. ### Request Example ```csharp // Assuming 'pbiClient' is an authenticated Power BI client instance // and 'gateway' is a Gateway object with an Id property // and 'credentialDetails' is a CredentialDetails object built with encrypted credentials var request = new PublishDatasourceToGatewayRequest( dataSourceType: "SQL", connectionDetails: "{\"server\":\"myServer\",\"database\":\"myDatabase\"}", credentialDetails: credentialDetails, dataSourceName: "my sql datasource"); pbiClient.Gateways.CreateDatasource(gateway.Id, request); ``` ### Response #### Success Response (200) Indicates that the data source has been successfully created and added to the gateway. #### Response Example (No specific response body is detailed in the provided text for a successful creation, typically an empty body or a success status.) ``` -------------------------------- ### Embed Power BI Item Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embedded-performance-best-practices_source=recommendations Embeds a Power BI report, dashboard, or tile into a specified HTML element using the provided configuration. Ensure the embed URL is obtained via Power BI REST APIs (Get Reports, Get Dashboards, Get Tiles) for optimal performance. ```APIDOC ## POST /api/powerbi/embed ### Description Embeds a Power BI report, dashboard, or tile into a specified HTML element. It's recommended to use embed URLs obtained from Power BI REST APIs and provide appropriate permissions (e.g., 'View' if not editing) to enhance performance. ### Method POST ### Endpoint /api/powerbi/embed ### Parameters #### Request Body - **element** (HTMLElement) - The HTML element where the Power BI content will be embedded. The element must be part of the DOM and not hidden using 'display: none'. - **config** (object) - Configuration object for embedding. - **type** (string) - Type of the item to embed (e.g., 'report', 'dashboard', 'tile'). - **id** (string) - The ID of the Power BI item. - **embedUrl** (string) - The embed URL obtained from Power BI APIs (e.g., Get Reports, Get Dashboards, Get Tiles). The 'config' parameter in the URL can be used for performance improvements. - **token** (string) - Access token for embedding. - **permissions** (string) - Permissions for embedding. Use 'View' if edit mode is not required. - **filters** (array, optional) - Filters to apply to the report. Applying filters during embed can affect performance if not saved with the report. - **bookmarks** (object, optional) - Bookmarks to apply to the report. - **slicers** (array, optional) - Slicers to apply to the report. - **settings** (object, optional) - Embedding settings. - **filterPaneEnabled** (boolean, optional) - Whether the filter pane is enabled. - **navPaneEnabled** (boolean, optional) - Whether the navigation pane is enabled. ### Request Example ```json { "element": "#reportContainer", "config": { "type": "report", "id": "anotherReportId456", "embedUrl": "https://app.powerbi.com/reportEmbed?reportId=...&config=...", "token": "accessToken789", "permissions": "View", "filters": [ { "$schema": "http://powerbi.com/product/schema#basic", "target": {"table": "Sales", "column": "Region"}, "operator": "In", "values": ["North America"] } ], "settings": { "filterPaneEnabled": true, "navPaneEnabled": true } } } ``` ### Response #### Success Response (200) Indicates that the embedding operation has started successfully. #### Response Example ```json { "status": "Embedding initiated" } ``` ``` -------------------------------- ### App-owns-data Custom Web API Example Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/dev-camp-links_tabs=app-owns-data-tutorials%2Capp-owns-data-examples This example features a .NET 5 custom web API with a JavaScript SPA client for app-owns-data embedding. The API interacts with the Power BI service as a service principal, providing embedding data and tokens to the client, and includes telemetry for performance monitoring. ```csharp /* * This is a placeholder for a .NET 5 Web API controller that serves Power BI embedding data. * It would typically use service principal authentication. */ using Microsoft.AspNetCore.Mvc; using Microsoft.PowerBI.Api; using Microsoft.PowerBI.Api.Models; using Microsoft.Rest; using System; using System.Threading.Tasks; [Route("api/[controller]")] public class PowerBIController : Controller { // Assume authentication and client initialization happens here private readonly PowerBIClient _powerBIClient; public PowerBIController(PowerBIClient powerBIClient) { _powerBIClient = powerBIClient; } [HttpGet("embedinfo/{workspaceId}/{reportId}")] public async Task GetEmbedInfo(string workspaceId, string reportId) { try { var report = await _powerBIClient.Reports.GetReportInGroupAsync(workspaceId, reportId); var embedUrl = $"https://app.powerbi.com/groups/{workspaceId}/reports/{reportId}"; // In a real scenario, you'd generate an embed token using GenerateToken or similar. // For simplicity, we'll return a placeholder token. var embedToken = "placeholder_embed_token"; return Ok(new { EmbedUrl = embedUrl, EmbedToken = embedToken }); } catch (Exception ex) { return StatusCode(500, ex.Message); } } } ``` ```javascript // This is a placeholder for JavaScript code in a Single Page Application (SPA) // to consume the Web API and embed a Power BI report. async function loadReport(workspaceId, reportId) { try { const response = await fetch(`/api/PowerBI/embedinfo/${workspaceId}/${reportId}`); const data = await response.json(); // Use Power BI JavaScript SDK to embed the report // const config = { // type: "report", // id: reportId, // embedUrl: data.embedUrl, // accessToken: data.embedToken // }; // const embedContainer = document.getElementById("reportContainer"); // const report = powerbi.embed(embedContainer, config); console.log("Report data received:", data); console.log("Initiating Power BI report embedding..."); } catch (error) { console.error("Error loading Power BI report:", error); } } // Example usage: // loadReport("your_workspace_id", "your_report_id"); ``` -------------------------------- ### Configure Startup for Microsoft.Identity.Web Authentication (C#) Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-organization-app Configures the application's startup class to enable server-side authentication with Microsoft.Identity.Web. This includes setting up token acquisition for downstream APIs, configuring in-memory token caches, and registering the PowerBiServiceApi class for dependency injection. ```csharp using Microsoft.Identity.Web; using Microsoft.Identity.Web.TokenCacheProviders; using Microsoft.Identity.Web.TokenCacheProviders.InMemory; using Microsoft.Identity.Web.UI; using UserOwnsData.Services; namespace UserOwnsData { public class Startup { public Startup (IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices (IServiceCollection services) { services .AddMicrosoftIdentityWebAppAuthentication(Configuration) .EnableTokenAcquisitionToCallDownstreamApi(PowerBiServiceApi.RequiredScopes) .AddInMemoryTokenCaches(); services.AddScoped (typeof (PowerBiServiceApi)); var mvcBuilder = services.AddControllersWithViews (options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add (new AuthorizeFilter (policy)); }); mvcBuilder.AddMicrosoftIdentityUI(); services.AddRazorPages(); } } } ``` -------------------------------- ### Power BI PowerShell Tutorial Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/dev-camp-links_tabs=app-owns-data-tutorials%2Capp-owns-data-examples This provides student files for a tutorial on using Power BI PowerShell cmdlets. It's designed to help users automate Power BI tasks and manage resources via PowerShell scripts. ```powershell # This is a placeholder for PowerShell commands related to Power BI. # The actual code would use the PowerBI PowerShell module. # Example: Connecting to Power BI Service # Import-Module -Name MicrosoftPowerBIMgmt # Connect-PowerBIServiceAccount -TenantId "YOUR_TENANT_ID" # Example: Getting reports in a workspace # Get-PowerBIReport -WorkspaceId "YOUR_WORKSPACE_ID" Write-Host "Power BI PowerShell examples would go here." ``` -------------------------------- ### Run Flask App from PowerShell/Command Prompt Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-sample-for-customers_source=recommendations&tabs=net-core This snippet demonstrates how to navigate to the application's directory and run the Flask development server. It assumes the user is in the correct environment and has the Flask application set up. ```shell cd Python/Embed for your customers/AppOwnesData flask run ``` -------------------------------- ### Running the Power BI Embedded Application (Command Line) Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-sample-for-customers_tabs=net-core These commands show how to run the Power BI embedded sample application after configuration. It involves navigating to the application's directory in PowerShell or Command Prompt and executing the Flask development server. ```powershell # Navigate to the application directory cd "Python\Embed for your customers\AppOwnesData" # Run the Flask development server flask run ``` ```cmd # Navigate to the application directory cd "Python\Embed for your customers\AppOwnesData" # Run the Flask development server flask run ``` -------------------------------- ### Windows and Basic Credentials for Power BI Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/configure-credentials Demonstrates how to create Windows and Basic credentials using the Power BI .NET SDK. It shows the instantiation of WindowsCredentials and BasicCredentials, along with the setup for credential encryption with an AsymmetricKeyEncryptor. ```csharp // Windows credentials var credentials = new WindowsCredentials(username: "john", password: "*****"); // Or // Basic credentials var credentials = new BasicCredentials(username: "john", password: "*****"); var credentialsEncryptor = new AsymmetricKeyEncryptor(publicKey); var credentialDetails = new CredentialDetails(credentials, PrivacyLevel.Private, EncryptedConnection.Encrypted, credentialsEncryptor); ``` ```csharp var credentials = "{\"credentialData\":[{\"name\":\"username\", \"value\":\"john\"},{\"name\":\"password\", \"value\":\"*****\"}]}"; ``` -------------------------------- ### OAuth2 Credentials (.NET SDK v3) Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/configure-credentials_source=recommendations Demonstrates how to implement OAuth2 authentication with the .NET SDK v3, including token-based credentials and encryption. ```csharp var credentials = new OAuth2Credentials("TestToken"); var credentialsEncryptor = new AsymmetricKeyEncryptor(publicKey); var credentialDetails = new CredentialDetails(credentials, PrivacyLevel.Private, EncryptedConnection.Encrypted, credentialsEncryptor); ``` -------------------------------- ### Get Workspace ID Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-customer-app_source=recommendations Instructions to find the Workspace ID from the Power BI service URL or via the Get Groups API. ```APIDOC ## Get Workspace ID ### Description Retrieve the Workspace ID GUID, which is required to identify the Power BI workspace containing the report. ### Method Manual retrieval from Power BI service URL or programmatic using Get Groups API ### Endpoint N/A (for manual) `/groups` (for API) ### Parameters None (for manual) ### Request Example N/A (for manual) ```json { "filter": "" } ``` (for API) ### Response **Workspace ID**: GUID ### Response Example `"yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"` ``` -------------------------------- ### Get Report ID Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-customer-app_source=recommendations Instructions to find the Report ID from the Power BI service URL or via the Get Reports In Group API. ```APIDOC ## Get Report ID ### Description Retrieve the Report ID GUID, which uniquely identifies the Power BI report to be embedded. ### Method Manual retrieval from Power BI service URL or programmatic using Get Reports In Group API ### Endpoint N/A (for manual) `/groups/{groupId}/reports/{reportId}` (for API) ### Parameters None (for manual) ### Request Example N/A (for manual) ```json { "groupId": "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy" } ``` (for API) ### Response **Report ID**: GUID ### Response Example `"zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz"` ``` -------------------------------- ### Get Semantic Model Users Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/datasets-permissions Use GET APIs to retrieve a list of principals (users or groups) that have access to a specified semantic model. ```APIDOC ## GET /datasets/{datasetId}/users ### Description Returns a list of principals that have access to the specified semantic model. ### Method GET ### Endpoint /datasets/{datasetId}/users ### Parameters #### Path Parameters - **datasetId** (string) - Required - The ID of the semantic model. ### Response #### Success Response (200) - **value** (array) - A list of user access details. - **userPrincipalEmail** (string) - The email address of the user. - **accessLevel** (string) - The permission level granted. - **displayName** (string) - The display name of the user. - **type** (string) - The type of principal (e.g., 'User', 'Group'). #### Response Example ```json { "value": [ { "userPrincipalEmail": "user1@example.com", "accessLevel": "Read", "displayName": "User One", "type": "User" }, { "userPrincipalEmail": "group@example.com", "accessLevel": "Read", "displayName": "Example Group", "type": "Group" } ] } ``` ``` ```APIDOC ## GET /groups/{groupId}/datasets/{datasetId}/users ### Description Returns a list of principals that have access to the specified semantic model within a specified group. ### Method GET ### Endpoint /groups/{groupId}/datasets/{datasetId}/users ### Parameters #### Path Parameters - **groupId** (string) - Required - The ID of the group. - **datasetId** (string) - Required - The ID of the semantic model. ### Response #### Success Response (200) - **value** (array) - A list of user access details. - **userPrincipalEmail** (string) - The email address of the user. - **accessLevel** (string) - The permission level granted. - **displayName** (string) - The display name of the user. - **type** (string) - The type of principal (e.g., 'User', 'Group'). #### Response Example ```json { "value": [ { "userPrincipalEmail": "user2@example.com", "accessLevel": "Reshare", "displayName": "User Two", "type": "User" } ] } ``` ``` -------------------------------- ### Import Items - Reports and Semantic Models Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/migration-to-sp-profiles_source=recommendations Automate the process of importing reports and semantic models into customer workspaces using the Import API. ```APIDOC ## POST /api/groups/{groupId}/imports ### Description Imports items (like reports or semantic models) into a specified workspace. ### Method POST ### Endpoint /api/groups/{groupId}/imports ### Parameters #### Path Parameters - **groupId** (string) - Required - The ID of the target workspace. #### Request Body - **fileContent** (string) - Required - The content of the file to import (e.g., .pbix, .pbit). - **datasetDisplayName** (string) - Optional - The display name for the imported dataset. - **reportDisplayName** (string) - Optional - The display name for the imported report. ### Request Example ```json { "fileContent": "base64_encoded_pbix_content", "datasetDisplayName": "Sales Data Model", "reportDisplayName": "Sales Performance Report" } ``` ### Response #### Success Response (200 OK) Indicates the import operation has started. #### Response Example ```json { "status": "Importing" } ``` ``` -------------------------------- ### Deploy Power BI Embedded Capacity using ARM Template Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/azure-pbie-create-capacity_source=recommendations Deploys a Power BI Embedded capacity using an Azure Resource Manager (ARM) template. ```APIDOC ## Deploy Power BI Embedded Capacity using ARM Template ### Description Deploys a Power BI Embedded capacity resource using a declarative ARM JSON template. ### Method Deployment via Azure CLI or PowerShell using the template. ### Endpoint N/A (Template deployment) ### Parameters #### Request Body (ARM Template Structure) ```json { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "name": { "type": "string", "metadata": { "description": "The capacity name, which is displayed in the Azure portal and the Power BI admin portal" } }, "location": { "type": "string", "defaultValue": "[resourceGroup().location]", "metadata": { "description": "The location where Power BI is hosted for your tenant" } }, "sku": { "type": "string", "allowedValues": [ "A1", "A2", "A3", "A4", "A5", "A6" ], "metadata": { "description": "The pricing tier, which determines the v-core count and memory size for the capacity" } }, "admin": { "type": "string", "metadata": { "description": "A user within your Power BI tenant, who will serve as an admin for this capacity" } } }, "resources": [ { "type": "Microsoft.PowerBIDedicated/capacities", "apiVersion": "2021-01-01", "name": "[parameters('name')]", "location": "[parameters('location')]", "sku": { "name": "[parameters('sku')]" }, "properties": { "administration": { "members": [ "[parameters('admin')]" ] } } } ] } ``` ### Request Example (for deployment) ```bash # Example using Azure CLI to deploy the template az deployment group create --resource-group --template-file --parameters name= sku= admin= ``` ### Response #### Success Response (200 or 201) Details of the deployment operation and the created capacity resource. ```