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

如何通过Azure SDK获取Azure API Management的分析页面数据?

获取Azure API Management分析页面内容的解决方案

azure.resourcemanager.apimanagement包聚焦于APIM资源的生命周期管理(创建、更新、删除等操作),分析页面的运营类数据并不在这个包的覆盖范围内,你可以通过以下两种方式获取目标数据:

1. 使用Azure Monitor SDK(azure-mgmt-monitor)获取核心指标

APIM门户分析页面的基础指标(请求数、响应延迟、错误率等)都存储在Azure Monitor中,通过azure-mgmt-monitor包可直接拉取这些数据:

from azure.identity import DefaultAzureCredential
from azure.mgmt.monitor import MonitorManagementClient

# 初始化Monitor客户端
credential = DefaultAzureCredential()
monitor_client = MonitorManagementClient(credential, "<你的订阅ID>")

# 填写你的APIM资源ID,格式:/subscriptions/{订阅ID}/resourceGroups/{资源组名}/providers/Microsoft.ApiManagement/service/{APIM实例名}
resource_id = "<你的APIM资源ID>"

# 获取过去24小时的请求总数指标
metrics_result = monitor_client.metrics.list(
    resource_id,
    metricnames="Count",
    aggregation="Sum",
    timespan="PT24H"
)

# 遍历并输出结果
for metric in metrics_result.value:
    print(f"指标名称: {metric.name.value}")
    for time_series in metric.timeseries:
        for data_point in time_series.data:
            print(f"时间点: {data_point.time_stamp}, 请求数: {data_point.total}")

2. 使用APIM Analytics REST API获取精细化分析数据

如果需要和门户分析页面高度匹配的精细化数据(比如按API、操作拆分的请求详情、错误分布、用户访问趋势),可以直接调用APIM官方提供的Analytics REST API:

认证方式

使用APIM的管理密钥进行认证,请求头添加:Authorization: SharedAccessSignature integration&<你的APIM管理密钥>

示例请求(获取7天内的API请求统计)

GET https://{APIM实例名}.management.azure-api.net/subscriptions/{订阅ID}/resourceGroups/{资源组名}/providers/Microsoft.ApiManagement/service/{APIM实例名}/analytics/requests?api-version=2022-08-01&$filter=timestamp ge datetime'2024-01-01T00:00:00' and timestamp le datetime'2024-01-07T23:59:59'

Python请求示例

import requests

apim_name = "<你的APIM实例名>"
subscription_id = "<你的订阅ID>"
resource_group = "<你的资源组名>"
management_key = "<你的APIM管理密钥>"

url = f"https://{apim_name}.management.azure-api.net/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.ApiManagement/service/{apim_name}/analytics/requests?api-version=2022-08-01&$filter=timestamp ge datetime'2024-01-01T00:00:00' and timestamp le datetime'2024-01-07T23:59:59'"

headers = {
    "Authorization": f"SharedAccessSignature integration&{management_key}"
}

response = requests.get(url, headers=headers)
response.raise_for_status()
analytics_data = response.json()
print(analytics_data)

权限要求

确保你的账号拥有以下权限之一:

  • Microsoft.ApiManagement/service/analytics/read(APIM Analytics读取权限)
  • Monitor Reader(Azure Monitor指标读取权限)
  • APIM Contributor(APIM全权限)

内容的提问来源于stack exchange,提问作者ElNeoX-dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:42:44