Working with Power BI APIs

Một phần của tài liệu Applied microsoft power bi Bring your data to life (Trang 381 - 386)

Now that you know about the Power BI REST APIS and how to configure custom

applications for OAuth, let’s practice what’s you’ve learned. Next, I’ll walk you through a sample application that will help you get started with Power BI programming. While I was considering writing a sample from scratch, as it turned out Microsoft has already provided a sample app.

Implemented as a .NET console application, the PBIGettingStarted application

demonstrates how a native client can authenticate and integrate with Power BI. You can download it from GitHub at https://github.com/PowerBI/getting-started-for-

dotnet/tree/master/PBIGettingStarted, or by clicking the Sample link on the Power BI Developer Center. For your convenience, I included the version I worked with in the

\Source\ch11 folder. To run the sample, you’ll need Visual Studio 2010 or a higher version (and valid Power BI credentials).

11.3.1 Implementing Authentication

Let’s start with understanding how the application uses OAuth2 to authenticate the user before she makes calls to Power BI. As a prerequisite, you’ll need to register a native client application in Azure AD.

Configuring the application

Before running the application, you need to change a few class-level variables to reflect your setup.

1.Open the PBIGettingStarted application in Visual Studio.

2.In Solution Explorer, double click Program.cs to open it.

3.Change the following variables:

private static string clientID = “<client_id>”;

private static string redirectUri = “https://login.live.com/oauth20_desktop.srf”;

private static string datasetName = “SalesMarketing”;

private static string groupName = “Finance”;

Replace the clientID variable with the Client ID of your application when you register it with Azure AD (see Figure 11.14 again). Replace the redirectUri variable with the Redirect URI of your application or leave it set to

https://login.live.com/oauth20_desktop.srf if this is the Redirect URI that you register.

One of the tasks that the application demonstrates is programmatically creating a new

“SalesMarketing” dataset. If the dataset name isn’t what you want, change it accordingly.

The application demonstrates working with groups. To try this feature, use Power BI Service to create a workspace group, such as “Finance”. Then change the groupName variable to the name of the group. If you use Power BI Free, which doesn’t support groups, you can just skip this part of the application.

Implementing OAuth

Every API invocation calls the AccessToken method, which performs the actual

authentication. Figure 11.17 shows the DatasetRequest method that is used by all dataset- related examples, such as when the application lists datasets (the GetDatasets method).

The DatasetRequest method creates a web request object as required by the Power BI API specification. It adds an Authorization header with a Bearer property that specifies the access token. In case you’re wondering, the access token is a base64-encoded hash that looks something like this “eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1N…”.

Figure 11.17 The AccessToken method performs the OAuth authentication flow.

Remember that you need the access token to authenticate successfully with OAuth. The application obtains the token by calling the AccessToken method. Line 551 constructs a .NET AuthenticationContext class, passing the URL of the Azure AD Token Endpoint and an instance of a TokenCache class. I separated the original code to call AcquireToken into two lines, so you can gain a better understanding what happens next. Line 553 calls

AcquireToken. It passes the URL of the resource that needs to be authorized. In your case, the resource is Power BI and its resource URI is https://analysis.windows.net/powerbi/api.

The code also passes the Client ID and the redirect URI.

When the application calls AcquireToken, you’ll be required to sign in to Power BI.

Once you type in your credentials and Power BI authenticates you successfully, you’ll get back an instance of the AuthenticationResult class. AuthenticationResult encapsulates important details, including the access token, its expiration date, and refresh token. On line 554, the application stores the access token so that it can pass it with subsequent API calls

without going through the authentication flow again. As it stands, the application doesn’t use the refresh token flow, but you can enhance it to do so. For example, you can check if the access token is about to expire and then call the

authContext.AquireAccessTokenByRefreshToken method.

11.3.2 Invoking the Power BI APIs

Once the application authenticates the interactive user, it’s ready to call the Power BI APIs. The next sample demonstrates calling various APIs to create a dataset, adding and deleting rows to and from a dataset table, changing the dataset table schema, and getting the groups that the user belongs to. I’ll walk you through the PBIGettingStarted code for creating datasets and loading a dataset table with data.

Creating datasets

A custom application can create a Power BI dataset to store data from scratch. The sample application demonstrates this with the CreateDataset method (see Figure 11.18). Line 213 constructs the API method signature for creating datasets by using the POST verb. Line 216 calls the GetDatasets method (not shown in Figure 11.18), which in turns calls the

“List all datasets” Power BI API.

Figure 11.18 The CreateDataset method demonstrates how to programmatically create a dataset.

Then the code checks if the dataset with the name specified in the datasetName variable (the default name is “SalesMarketing”) already exists. If it doesn’t exist, line 221 calls the PostRequest method to create the dataset. The PostRequest method is a helper method that wraps the HttpWebRequest class. The request must specify the dataset definition in a

JSON format, which must include at least one table. The application defines a Product

object whose definition will be used for the dataset table schema.

Line 221 passes an instance of the Product object, and it serializes the object to the JSON format. As a result, the request body contains the JSON representation of a dataset that has a single table called Product with five columns (ProductName, Name, Category, IsComplete, and ManufacturedOn). Once the call completes, you should see the

SalesMarketing dataset in the Power BI Service navigation bar.

At this point, the dataset Product table contains no data. However, I recommend you take a moment now to create a table report for it, and then pin a visualization from the report to a dashboard. This will allow you to see in real time the effect of loading the dataset with data. Next, the code loads some data.

Loading data

The custom application can programmatically push rows to a dataset table. This scenario is very useful because it allows you to implement real-time dashboards, similar to the one we’ve implemented with Azure Stream Analytics Service in the previous chapter. The difference is that in this case, it’s your application that pushes the data and you have full control over the entire process, including how the data is shaped and how often it pushes data to Power BI. The AddRows method demonstrates this (see Figure 11.19).

Figure 11.19 The AddRows method demonstrates how your custom app can load a dataset table.

On line 380, the code creates the API method signature for creating rows using the POST verb. Then the code creates a list collection with three products. This collection will be used to add three rows to the dataset. On line 393, the code calls the PostRequest method and passes the collection (serialized as JSON). This JSON output will be included in the request body. Once this method completes, three rows will be added to the Product table in the SalesMarketing dataset. If you watch the Power BI dashboard, you should see its tile

data updating in real time. Now you have a real-time BI solution!

Một phần của tài liệu Applied microsoft power bi Bring your data to life (Trang 381 - 386)

Tải bản đầy đủ (PDF)

(447 trang)