如何通过API获取Azure Advisor推荐并解决授权错误(用于Power BI)
解决Azure Advisor API授权错误并获取推荐用于Power BI
一、先修正代码中的明显错误
你的代码存在请求方法错误:获取Azure Advisor推荐的API是GET请求,而非POST,且无需传递payload。修正后的完整代码如下:
import requests import json # 替换为你的实际租户ID、客户端ID、客户端密钥、订阅ID tenant_id = "你的租户ID" client_id = "你的客户端ID" client_secret = "你的客户端密钥" subscription_id = "你的订阅ID" # 获取访问令牌 get_token_url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/token" payload = { "client_id": client_id, "client_secret": client_secret, "grant_type": "client_credentials", "resource": "https://management.azure.com/" } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } response = requests.post(get_token_url, headers=headers, data=payload) token_data = json.loads(response.content) access_token = token_data['access_token'] # 获取Azure Advisor推荐(使用GET请求) advisor_url = f"https://management.azure.com/subscriptions/{subscription_id}/providers/Microsoft.Advisor/recommendations?api-version=2023-01-01" advisor_headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json' } # 此处用GET请求,无需传data参数 advisor_response = requests.get(advisor_url, headers=advisor_headers) recommendations = json.loads(advisor_response.content) print(recommendations)
二、解决AuthorizationFailed授权错误
该错误的核心是你的服务主体(client_id对应的Azure AD应用)没有访问Azure Advisor推荐的权限,需完成以下操作:
- 登录Azure门户,进入目标订阅页面
- 左侧导航栏选择「访问控制(IAM)」
- 点击「添加」→「添加角色分配」
- 在角色列表中搜索并选择Advisor Reader(遵循最小权限原则,也可选择Reader角色,但Advisor Reader权限更精准)
- 成员类型选择「用户、组或服务主体」,搜索你的服务主体名称(即client_id对应的应用名称)
- 完成角色分配,等待5-10分钟让权限生效
三、集成到Power BI报表
将修正后的代码导入Power BI:
- 打开Power BI Desktop,点击「获取数据」→「Python脚本」
- 粘贴修正后的代码,替换所有占位符为你的实际信息
- 点击「确定」,Power BI会执行脚本并加载推荐数据
- 对加载的数据进行清洗、建模后,即可制作报表
内容的提问来源于stack exchange,提问作者user22672915
相关产品推荐
相关产品推荐

