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

Python调用Power BI Service API获取数据集信息遇401错误求助

Power BI Service API调用401错误排查与解决

问题描述

我希望通过Python调用Power BI Service API获取所有数据集的名称、最后刷新时间及刷新状态,已完成以下步骤:

  • 创建Azure Active Directory (AAD)应用,获取tenant_id、client_secret、client_id;
  • 安装所需Python包:requests、msal;
  • 编写了对应的Python代码(代码如下)。

已确认获取到access_token,但运行代码时返回状态码401,无法获取数据集,求错误原因及解决方法。

代码

import requests
from msal import ConfidentialClientApplication
client_id = "xxxxxxxx-040d-4db7-8f43-de02b43fxxxx"
client_secret = "VQQ8Q~znvjp1ccNbyy1tVK6IBh2s2xxxxxxxxx"
tenant_id = "8cae7bf9-b754-4e93-xxxx-xxxxxxxxxxxxxx"
scope = ["https://analysis.windows.net/powerbi/api/.default"]
api_endpoint = "https://api.powerbi.com/v1.0/myorg/datasets"

def get_access_token():
    app = ConfidentialClientApplication(
        client_id=client_id,
        client_credential=client_secret,
        authority=f"https://login.microsoftonline.com/{tenant_id}"
    )
    result = app.acquire_token_silent(scope, account=None)
    if not result:
        result = app.acquire_token_for_client(scopes=scope)
    return result["access_token"]


def get_datasets():
    access_token = get_access_token()
    headers = {
        "Authorization": "Bearer " + access_token,
        "Content-Type": "application/json"
    }
    response = requests.get(api_endpoint, headers=headers)
    if response.status_code == 200:
        datasets = response.json()["value"]
        for dataset in datasets:
            print("Dataset Name:", dataset["name"])
            print("Last Refreshed Date:", dataset["lastRefreshDateTime"])
    else:
        print("Failed to retrieve datasets. Status code:", response.status_code)

if __name__ == "__main__":
    get_datasets()

运行输出

PS C:\Users\hungcht> & C:/Users/hungcht/AppData/Local/Microsoft/WindowsApps/python3.9.exe "c:/Users/hungcht/Desktop/Y4A/PYTHON 3/project/ConnectPowerBIServiceAPI/connect_power_bi_service_api.py"       
Failed to retrieve datasets. Status code: 401

错误原因分析

  • AAD应用权限不足:AAD应用未被授予读取Power BI数据集的权限,或权限未经过租户管理员同意生效。
  • 服务主体访问未开启:使用客户端凭据流(client credentials flow)时,Power BI租户未允许服务主体访问API,或目标工作区未添加该应用为成员。
  • Token权限不匹配:获取到的access_token未包含Dataset.Read.All等必要权限,导致API拒绝访问。

解决方法

1. 配置AAD应用权限

  • 登录Azure Portal,找到你的AAD应用,进入「API权限」页面。
  • 添加Power BI Service权限:选择「Power BI Service」→「应用权限」,添加Dataset.Read.All权限。
  • 点击「授予管理员同意」(需租户管理员权限),确保权限生效。

2. 启用Power BI服务主体访问

  • 登录Power BI管理员门户,进入「租户设置」→「开发人员设置」。
  • 开启「允许服务主体访问Power BI API」选项。
  • 若需访问特定工作区的数据集,在对应工作区中添加该AAD应用为成员,分配至少「成员」或「管理员」角色。

3. 验证Token权限

  • 使用JWT解析工具解析获取到的access_token,检查roles字段是否包含Dataset.Read.All权限。若缺失,重新检查AAD应用权限配置和管理员同意步骤。

4. 代码优化(辅助排查)

  • 增加Token获取错误处理,避免无效Token流入API调用:
    def get_access_token():
        app = ConfidentialClientApplication(
            client_id=client_id,
            client_credential=client_secret,
            authority=f"https://login.microsoftonline.com/{tenant_id}"
        )
        result = app.acquire_token_silent(scope, account=None)
        if not result:
            result = app.acquire_token_for_client(scopes=scope)
        if "access_token" not in result:
            raise Exception(f"获取Token失败: {result.get('error_description', '未知错误')}")
        return result["access_token"]
    
  • 打印API错误详情,便于定位问题:
    else:
        print("获取数据集失败,状态码:", response.status_code)
        print("错误详情:", response.json())
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:01:23