You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Power BI中调用带Bearer Token的Azure REST API并实现自动刷新?

在Power BI中自动获取Azure Recommendations API数据并实现每日刷新

1. 构建自动获取Azure AD Bearer Token的自定义函数

在Power BI Desktop中进入编辑查询界面,创建自定义函数实现令牌自动获取,使用服务主体信息(租户ID、客户端ID、客户端密钥)完成无人工干预的令牌请求:

let
    GetAzureADToken = (tenantId as text, clientId as text, clientSecret as text) as text =>
        let
            tokenUrl = "https://login.microsoftonline.com/" & tenantId & "/oauth2/v2.0/token",
            body = "grant_type=client_credentials&client_id=" & clientId & "&client_secret=" & clientSecret & "&scope=https://management.azure.com/.default",
            response = Web.Contents(tokenUrl, [
                Headers = [#"Content-Type" = "application/x-www-form-urlencoded"],
                Content = Text.ToBinary(body)
            ]),
            jsonResponse = Json.Document(response),
            accessToken = jsonResponse[access_token]
        in
            accessToken
in
    GetAzureADToken

关键说明:

  • 替换参数tenantId、clientId、clientSecret为你的Azure服务主体信息
  • 确保该服务主体拥有Microsoft.Authorization/recommendations/read(或对应资源的读取权限)

2. 调用Recommendations - List API获取数据

创建新查询,先调用令牌函数获取有效令牌,再发起GET请求到目标API端点:

let
    // 配置核心参数
    TenantID = "你的租户ID",
    ClientID = "你的客户端ID",
    ClientSecret = "你的客户端密钥",
    RecommendationsAPIUrl = "你的Recommendations API GET地址",
    APIVersion = "2023-01-01",
    
    // 获取Bearer令牌
    AccessToken = GetAzureADToken(TenantID, ClientID, ClientSecret),
    
    // 构造完整API请求
    FullAPIUrl = RecommendationsAPIUrl & "?api-version=" & APIVersion,
    APIResponse = Web.Contents(FullAPIUrl, [
        Headers = [
            #"Authorization" = "Bearer " & AccessToken,
            #"Content-Type" = "application/json"
        ]
    ]),
    
    // 解析并整理返回数据(根据实际JSON结构调整)
    ParsedResponse = Json.Document(APIResponse),
    RecommendationsData = Table.FromRecords(ParsedResponse[value])
in
    RecommendationsData

关键说明:

  • 若API返回嵌套结构,需用Table.ExpandRecordColumn等函数调整数据展开逻辑
  • 在Power BI Desktop中预览数据,确认返回结果符合预期

3. 配置每日自动刷新

3.1 Power BI Desktop端准备

  • 确认服务主体凭据有效,API请求无需人工交互
  • 调整隐私设置:进入文件 > 选项和设置 > 隐私,选择忽略隐私级别检查,避免刷新时权限冲突

3.2 Power BI服务端配置

  1. 将Power BI Desktop文件发布到Power BI服务
  2. 进入数据集设置界面:
    • 在数据源凭据中找到对应Web数据源,点击编辑凭据,选择匿名(令牌已在请求头中携带)并保存
    • 开启计划刷新,设置每日刷新的时间与频率
    • 确认工作区权限足够,服务主体权限未过期

注意事项

  • 定期轮换服务主体的客户端密钥,避免凭据泄露
  • 刷新失败时,优先检查令牌有效性、服务主体权限、API端点是否变更

内容的提问来源于stack exchange,提问作者Francesco Mantovani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 17:47:52