이 빠른 시작에서는 Power BI 인증하고, 의미 체계 모델에 대해 DAX 쿼리를 실행하고, 화살표 응답을 로컬 데이터 구조로 역직렬화합니다.
사전 요구 사항
- 하나 이상의 의미 체계 모델이 있는 Power BI 작업 영역입니다.
- 의미 체계 모델에 대한 빌드 및 읽기 권한입니다.
- Microsoft Entra 앱 등록(또는 테스트에 대화형 인증 사용).
1 - 인증
https://analysis.windows.net/powerbi/api/.default 범위로 전달자 토큰을 획득합니다.
from msal import PublicClientApplication
client_id = "YOUR_APP_CLIENT_ID"
authority = "https://login.microsoftonline.com/YOUR_TENANT_ID"
scopes = ["https://analysis.windows.net/powerbi/api/.default"]
app = PublicClientApplication(client_id, authority=authority)
result = app.acquire_token_interactive(scopes=scopes)
access_token = result["access_token"]
using Microsoft.Identity.Client;
var clientId = "YOUR_APP_CLIENT_ID";
var tenantId = "YOUR_TENANT_ID";
var scopes = new[] { "https://analysis.windows.net/powerbi/api/.default" };
var app = PublicClientApplicationBuilder
.Create(clientId)
.WithAuthority(AzureCloudInstance.AzurePublic, tenantId)
.WithRedirectUri("http://localhost")
.Build();
var result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
var accessToken = result.AccessToken;
$clientId = "YOUR_APP_CLIENT_ID"
$tenantId = "YOUR_TENANT_ID"
$scopes = @("https://analysis.windows.net/powerbi/api/.default")
$token = Get-MsalToken -ClientId $clientId -TenantId $tenantId -Scopes $scopes -Interactive
$accessToken = $token.AccessToken
2 - DAX 쿼리 실행
간단한 EVALUATE 문을 사용하여 쿼리 실행 화살표 엔드포인트에 POST 요청을 보냅니다.
import io
import pyarrow as pa
import requests
group_id = "YOUR_WORKSPACE_ID"
dataset_id = "YOUR_DATASET_ID"
url = (f"https://api.powerbi.com/v1.0/myorg/groups/{group_id}"
f"/datasets/{dataset_id}/executeDaxQueries")
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
}
body = {"query": "EVALUATE TOPN(5, 'DimProduct')"}
response = requests.post(url, headers=headers, json=body)
response.raise_for_status()
reader = pa.ipc.open_stream(io.BytesIO(response.content))
table = reader.read_all()
df = table.to_pandas()
print(df)
using System.Net.Http.Headers;
using Apache.Arrow;
using Apache.Arrow.Ipc;
var groupId = "YOUR_WORKSPACE_ID";
var datasetId = "YOUR_DATASET_ID";
var url = $"https://api.powerbi.com/v1.0/myorg/groups/{groupId}"
+ $"/datasets/{datasetId}/executeDaxQueries";
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
var body = new StringContent(
"""{"query": "EVALUATE TOPN(5, 'DimProduct')"}""",
System.Text.Encoding.UTF8,
"application/json");
var response = await client.PostAsync(url, body);
response.EnsureSuccessStatusCode();
using var stream = await response.Content.ReadAsStreamAsync();
using var reader = new ArrowStreamReader(stream);
var batch = await reader.ReadNextRecordBatchAsync();
Console.WriteLine($"Rows: {batch.Length}, Columns: {batch.ColumnCount}");
$groupId = "YOUR_WORKSPACE_ID"
$datasetId = "YOUR_DATASET_ID"
$url = "https://api.powerbi.com/v1.0/myorg/groups/$groupId" +
"/datasets/$datasetId/executeDaxQueries"
$headers = @{
"Authorization" = "Bearer $accessToken"
"Content-Type" = "application/json"
}
$body = @{ query = "EVALUATE TOPN(5, 'DimProduct')" } | ConvertTo-Json
$response = Invoke-WebRequest -Uri $url -Method Post -Headers $headers -Body $body
# Save the binary Arrow stream to a file for inspection
$arrowFile = "result.arrow"
[System.IO.File]::WriteAllBytes($arrowFile, $response.Content)
Write-Host "Arrow stream saved to $arrowFile ($($response.Content.Length) bytes)"
3 - 결과 검사
# Print the Arrow schema (column names and types)
print(table.schema)
# Show the first few rows as a pandas DataFrame
print(df.head())
# Access a specific column
print(table.column("ProductName").to_pylist()[:5])
// Print the schema (column names and types)
for (var i = 0; i < batch.Schema.FieldsList.Count; i++)
{
var field = batch.Schema.FieldsList[i];
Console.WriteLine($" {field.Name}: {field.DataType}");
}
// Print the first row's values
for (var i = 0; i < batch.ColumnCount; i++)
{
var column = batch.Column(i);
Console.Write($"{batch.Schema.FieldsList[i].Name}=");
Console.Write(column.GetType().GetMethod("GetValue")?.Invoke(column, new object[] { 0 }));
Console.Write(" ");
}
# Use Python with pyarrow to read the saved Arrow file
python -c @"
import pyarrow as pa
reader = pa.ipc.open_stream('result.arrow')
table = reader.read_all()
print(table.schema)
print(table.to_pandas().head())
"@
자원을 정리하세요
테스트용으로만 Microsoft Entra 앱 등록을 만든 경우 Azure 포털 이동하여 삭제합니다. 액세스 토큰은 자동으로 만료되며 수동 해지가 필요하지 않습니다.
관련 콘텐츠