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

调用Intune API获取数据时出现Key Error问题求助

Intune API调用报错:KeyError与401未授权问题

问题详情

调用Intune API获取数据时触发KeyError(错误截图:Key Error),使用的代码如下:

#pip install requests pandas plotly
import requests
import pandas as pd
import plotly.graph_objects as go

# Replace with your actual Intune OData API endpoint
intune_api_url = "API_Link"

# Fetch data from the Intune API
def fetch_data():
    response = requests.get(intune_api_url)
    data = response.json()
    return data['d']['results']

def create_dashboard():
    # Fetch data from Intune OData API
    intune_data = fetch_data()

    # Convert data to pandas DataFrame
    df = pd.DataFrame(intune_data)

    # Filter compliant device
    compliant_devices = df[df['ComplianceState'] == 'Compliant']

    # Get the number of compliant devices
    num_compliant_devices = len(compliant_devices)

    # Create a simple dashboard with plotly
    fig = go.Figure(data=[go.Indicator(
        mode="number+delta",
        value=num_compliant_devices,
        title="Compliant Devices",
        delta={'reference': 0}
    )])

    fig.show()

if __name__ == "__main__":
    create_dashboard()

为排查问题,使用以下代码检查API响应状态:

import requests
import json
response_API = requests.get("API")
print(response_API.status_code)

输出状态码为401(截图:状态码401)

问题根源

401状态码表示未授权访问,这是触发KeyError的核心原因:因为请求没有通过Intune API的身份验证,API返回的不是预期的包含d和results键的有效数据JSON,而是错误信息JSON,直接按原逻辑解析就会找不到对应键,抛出KeyError。

解决方法

Intune API需要通过Azure AD的OAuth 2.0授权才能访问,必须添加身份验证流程:

  1. 在Azure AD注册应用:

    • 登录Azure门户,在Azure AD中注册一个应用程序
    • 记录应用的客户端ID、租户ID、客户端密钥(或证书)
    • 为应用分配Intune相关的API权限(比如DeviceManagementManagedDevices.Read.All)
  2. 获取访问令牌:
    通过Azure AD的令牌端点获取访问令牌,示例代码:

    def get_access_token(tenant_id, client_id, client_secret):
        token_url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
        payload = {
            "grant_type": "client_credentials",
            "client_id": client_id,
            "client_secret": client_secret,
            "scope": "https://graph.microsoft.com/.default"
        }
        response = requests.post(token_url, data=payload)
        response.raise_for_status()  # 处理令牌请求失败的情况
        return response.json()["access_token"]
    
  3. 修改原代码,添加授权头:
    更新fetch_data函数,在请求中携带Authorization头(注意:新版Intune Graph API返回数据的键为value,而非旧OData的d.results):

    def fetch_data(intune_api_url, access_token):
        headers = {
            "Authorization": f"Bearer {access_token}"
        }
        response = requests.get(intune_api_url, headers=headers)
        response.raise_for_status()  # 先检查响应状态,非200直接抛出错误
        data = response.json()
        return data['value']
    
  4. 完善错误处理:
    在代码中添加响应状态检查,避免因非预期响应导致KeyError,比如在解析JSON前先判断响应状态码是否为200,以及返回的JSON是否包含预期的键。

内容的提问来源于stack exchange,提问作者Jalapu Mahipal Reddy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 05:53:13