请参与 Prometheus 用户调研(2026 年 3 月版) ,帮助社区确定未来开发工作的优先级!

HTTP API

当前稳定的 HTTP API 可通过 Prometheus 服务器上的 /api/v1 访问。任何非破坏性的添加都将在此端点下进行。

OpenAPI 规范

HTTP API 的 OpenAPI 规范可在 /api/v1/openapi.yaml 获取。默认情况下,它返回 OpenAPI 3.1 以实现更广泛的兼容性。使用 ?openapi_version=3.2 可获取 OpenAPI 3.2,其中包含高级功能和诸如 /api/v1/notifications/live 等端点。

此机器可读的规范描述了所有可用的端点、请求参数、响应格式和架构。

OpenAPI 规范可用于:

  • 生成各种编程语言的客户端库。
  • 验证 API 请求和响应。
  • 生成交互式 API 文档。
  • 测试 API 端点。

格式概述

API 响应格式为 JSON。每个成功的 API 请求都会返回 2xx 状态码。

到达 API 处理程序的无效请求将返回 JSON 错误对象和以下 HTTP 响应码之一:

  • 400 Bad Request:当参数缺失或不正确时。
  • 422 Unprocessable Entity:当表达式无法执行时(RFC4918 )。
  • 503 Service Unavailable:当查询超时或中止时。

其他非 2xx 的代码可能会在到达 API 端点之前发生的错误中返回。

如果存在不会阻止请求执行的错误,则可能会返回一系列警告。对于可能存在也可能不存在假阳性的潜在查询问题,可能会返回额外的 info 级别注解数组。所有成功收集的数据都将返回在 data 字段中。

JSON 响应封装格式如下:

{
  "status": "success" | "error",
  "data": <data>,

  // Only set if status is "error". The data field may still hold
  // additional data.
  "errorType": "<string>",
  "error": "<string>",

  // Only set if there were warnings while executing the request.
  // There will still be data in the data field.
  "warnings": ["<string>"],
  // Only set if there were info-level annotations while executing the request.
  "infos": ["<string>"]
}

通用占位符定义如下

  • <rfc3339 | unix_timestamp>:输入时间戳可以 RFC3339  格式提供,也可以作为 Unix 时间戳(秒)提供,并可选小数部分以获得亚秒级精度。输出时间戳始终以 Unix 时间戳(秒)形式表示。
  • <series_selector>:Prometheus 时间序列选择器(例如 http_requests_totalhttp_requests_total{method=~"(GET|POST)"}),需要进行 URL 编码。
  • <duration>使用时间单位的 Prometheus 浮点字面量子集。例如,5m 指 5 分钟的持续时间。
  • <bool>:布尔值(字符串 truefalse)。

注意:可能重复的查询参数名称以 [] 结尾。

表达式查询

查询语言表达式可以在单个瞬间或一段时间内进行评估。以下各节描述了每种类型表达式查询的 API 端点。

瞬时查询

以下端点可在单个时间点评估瞬时查询:

GET /api/v1/query
POST /api/v1/query

URL 查询参数

  • query=<string>:Prometheus 表达式查询字符串。
  • time=<rfc3339 | unix_timestamp>:评估时间戳。可选。
  • timeout=<duration>:评估超时时间。可选。默认值为 -query.timeout 标志的值,并受其上限限制。
  • limit=<number>:返回序列的最大数量。不影响标量或字符串,但会截断矩阵和向量的序列数量。可选。0 表示禁用。
  • lookback_delta=<duration | float>:仅针对此查询覆盖 回溯周期,格式为 duration 或浮点秒数。可选。
  • stats=<string>:在响应中包含查询统计信息。如果设置为 all,则包含详细统计信息。可选。

如果省略 time 参数,则使用当前服务器时间。

可以使用 POST 方法和 Content-Type: application/x-www-form-urlencoded 头直接在请求体中对这些参数进行 URL 编码。这在指定可能超过服务器端 URL 字符限制的大型查询时非常有用。

查询结果的 data 部分格式如下:

{
  "resultType": "matrix" | "vector" | "scalar" | "string",
  "result": <value>
}

<value> 指查询结果数据,其格式根据 resultType 不同而有所不同。参见 表达式查询结果格式

以下示例在 2015-07-01T20:10:51.781Z 时间评估表达式 up

curl 'https://:9090/api/v1/query?query=up&time=2015-07-01T20:10:51.781Z'
{
   "status" : "success",
   "data" : {
      "resultType" : "vector",
      "result" : [
         {
            "metric" : {
               "__name__" : "up",
               "job" : "prometheus",
               "instance" : "localhost:9090"
            },
            "value": [ 1435781451.781, "1" ]
         },
         {
            "metric" : {
               "__name__" : "up",
               "job" : "node",
               "instance" : "localhost:9100"
            },
            "value" : [ 1435781451.781, "0" ]
         }
      ]
   }
}

范围查询

以下端点可在一个时间范围内评估表达式查询:

GET /api/v1/query_range
POST /api/v1/query_range

URL 查询参数

  • query=<string>:Prometheus 表达式查询字符串。
  • start=<rfc3339 | unix_timestamp>:开始时间戳,包含在内。
  • end=<rfc3339 | unix_timestamp>:结束时间戳,包含在内。
  • step=<duration | float>:查询分辨率步长,格式为 duration 或浮点秒数。
  • timeout=<duration>:评估超时时间。可选。默认值为 -query.timeout 标志的值,并受其上限限制。
  • limit=<number>:返回序列的最大数量。可选。0 表示禁用。
  • lookback_delta=<duration | float>:仅针对此查询覆盖 回溯周期,格式为 duration 或浮点秒数。可选。
  • stats=<string>:在响应中包含查询统计信息。如果设置为 all,则包含详细统计信息。可选。

可以使用 POST 方法和 Content-Type: application/x-www-form-urlencoded 头直接在请求体中对这些参数进行 URL 编码。这在指定可能超过服务器端 URL 字符限制的大型查询时非常有用。

查询结果的 data 部分格式如下:

{
  "resultType": "matrix",
  "result": <value>
}

有关 <value> 占位符的格式,请参见 范围向量结果格式

以下示例在 30 秒范围内以 15 秒的查询分辨率评估表达式 up

curl 'https://:9090/api/v1/query_range?query=up&start=2015-07-01T20:10:30.781Z&end=2015-07-01T20:11:00.781Z&step=15s'
{
   "status" : "success",
   "data" : {
      "resultType" : "matrix",
      "result" : [
         {
            "metric" : {
               "__name__" : "up",
               "job" : "prometheus",
               "instance" : "localhost:9090"
            },
            "values" : [
               [ 1435781430.781, "1" ],
               [ 1435781445.781, "1" ],
               [ 1435781460.781, "1" ]
            ]
         },
         {
            "metric" : {
               "__name__" : "up",
               "job" : "node",
               "instance" : "localhost:9091"
            },
            "values" : [
               [ 1435781430.781, "0" ],
               [ 1435781445.781, "0" ],
               [ 1435781460.781, "1" ]
            ]
         }
      ]
   }
}

格式化查询表达式

以下端点以漂亮的方式格式化 PromQL 表达式:

GET /api/v1/format_query
POST /api/v1/format_query

URL 查询参数

  • query=<string>:Prometheus 表达式查询字符串。

可以使用 POST 方法和 Content-Type: application/x-www-form-urlencoded 头直接在请求体中对这些参数进行 URL 编码。这在指定可能超过服务器端 URL 字符限制的大型查询时非常有用。

查询结果的 data 部分是一个包含格式化后查询表达式的字符串。注意,格式化字符串中会删除所有注释。

以下示例格式化表达式 foo/bar

curl 'https://:9090/api/v1/format_query?query=foo/bar'
{
   "status" : "success",
   "data" : "foo / bar"
}

将 PromQL 表达式解析为抽象语法树 (AST)

此端点是实验性的,将来可能会发生变化。目前它仅供 Prometheus 自身的 Web UI 使用,端点名称和返回的确切格式可能会在不同的 Prometheus 版本之间发生变化。如果 UI 不再需要它,它也可能被移除。

以下端点解析 PromQL 表达式并将其作为 JSON 格式的 AST(抽象语法树)表示返回:

GET /api/v1/parse_query
POST /api/v1/parse_query

URL 查询参数

  • query=<string>:Prometheus 表达式查询字符串。

可以使用 POST 方法和 Content-Type: application/x-www-form-urlencoded 头直接在请求体中对这些参数进行 URL 编码。这在指定可能超过服务器端 URL 字符限制的大型查询时非常有用。

查询结果的 data 部分是一个包含已解析查询表达式的 AST 的字符串。

以下示例解析表达式 foo/bar

curl 'https://:9090/api/v1/parse_query?query=foo/bar'
{
   "data" : {
      "bool" : false,
      "lhs" : {
         "matchers" : [
            {
               "name" : "__name__",
               "type" : "=",
               "value" : "foo"
            }
         ],
         "name" : "foo",
         "offset" : 0,
         "startOrEnd" : null,
         "timestamp" : null,
         "type" : "vectorSelector"
      },
      "matching" : {
         "card" : "one-to-one",
         "include" : [],
         "labels" : [],
         "on" : false
      },
      "op" : "/",
      "rhs" : {
         "matchers" : [
            {
               "name" : "__name__",
               "type" : "=",
               "value" : "bar"
            }
         ],
         "name" : "bar",
         "offset" : 0,
         "startOrEnd" : null,
         "timestamp" : null,
         "type" : "vectorSelector"
      },
      "type" : "binaryExpr"
   },
   "status" : "success"
}

查询元数据

Prometheus 提供了一组 API 端点来查询有关序列及其标签的元数据。

注意这些 API 端点可能会返回在所选时间范围内没有样本的序列的元数据,和/或返回已通过删除 API 端点标记为删除的样本的序列的元数据。额外返回的序列元数据的具体程度是一个实现细节,将来可能会发生变化。

按标签匹配器查找序列

以下端点返回匹配特定标签集的序列列表:

GET /api/v1/series
POST /api/v1/series

URL 查询参数

  • match[]=<series_selector>:重复的序列选择器参数,用于选择要返回的序列。必须至少提供一个 match[] 参数。
  • start=<rfc3339 | unix_timestamp>:开始时间戳。
  • end=<rfc3339 | unix_timestamp>:结束时间戳。
  • limit=<number>:返回序列的最大数量。可选。0 表示禁用。

可以使用 POST 方法和 Content-Type: application/x-www-form-urlencoded 头直接在请求体中对这些参数进行 URL 编码。这在指定大量或动态数量的序列选择器时非常有用,因为它们可能会超过服务器端 URL 字符限制。

查询结果的 data 部分包含一个对象列表,这些对象包含标识每个序列的标签名/值对。请注意,startend 时间是近似值,结果可能包含在给定时间间隔内没有样本的序列的标签值。

以下示例返回匹配选择器 upprocess_start_time_seconds{job="prometheus"} 的所有序列:

curl -g 'https://:9090/api/v1/series?' --data-urlencode 'match[]=up' --data-urlencode 'match[]=process_start_time_seconds{job="prometheus"}'
{
   "status" : "success",
   "data" : [
      {
         "__name__" : "up",
         "job" : "prometheus",
         "instance" : "localhost:9090"
      },
      {
         "__name__" : "up",
         "job" : "node",
         "instance" : "localhost:9091"
      },
      {
         "__name__" : "process_start_time_seconds",
         "job" : "prometheus",
         "instance" : "localhost:9090"
      }
   ]
}

获取标签名

以下端点返回标签名列表:

GET /api/v1/labels
POST /api/v1/labels

URL 查询参数

  • start=<rfc3339 | unix_timestamp>:开始时间戳。可选。
  • end=<rfc3339 | unix_timestamp>:结束时间戳。可选。
  • match[]=<series_selector>:重复的序列选择器参数,用于选择从中读取标签名的序列。可选。
  • limit=<number>:返回序列的最大数量。可选。0 表示禁用。

JSON 响应的 data 部分是一个字符串标签名列表。请注意,startend 时间是近似值,结果可能包含在给定时间间隔内没有样本的序列的标签名。

这是一个示例:

curl 'localhost:9090/api/v1/labels'
{
    "status": "success",
    "data": [
        "__name__",
        "call",
        "code",
        "config",
        "dialer_name",
        "endpoint",
        "event",
        "goversion",
        "handler",
        "instance",
        "interval",
        "job",
        "le",
        "listener_name",
        "name",
        "quantile",
        "reason",
        "role",
        "scrape_job",
        "slice",
        "version"
    ]
}

查询标签值

以下端点返回给定标签名的标签值列表:

GET /api/v1/label/<label_name>/values

URL 查询参数

  • start=<rfc3339 | unix_timestamp>:开始时间戳。可选。
  • end=<rfc3339 | unix_timestamp>:结束时间戳。可选。
  • match[]=<series_selector>:重复的序列选择器参数,用于选择从中读取标签值的序列。可选。
  • limit=<number>:返回序列的最大数量。可选。0 表示禁用。

JSON 响应的 data 部分是一个字符串标签值列表。请注意,startend 时间是近似值,结果可能包含在给定时间间隔内没有样本的序列的标签值。

此示例查询标签 http_status_code 的所有标签值:

curl https://:9090/api/v1/label/http_status_code/values
{
   "status" : "success",
   "data" : [
      "200",
      "504"
   ]
}

标签名可以根据需要使用值转义方法进行编码,如果名称包含 / 字符,则必须这样做。要以这种方式对名称进行编码:

  • 在标签前加上 U__
  • 字母、数字和冒号按原样显示。
  • 将单个下划线转换为双下划线。
  • 对于所有其他字符,使用十六进制整数形式的 UTF-8 码点,并用下划线括起来。因此 变为 _20_,而 . 变为 _2e_

有关文本转义的更多信息,请参阅原始 UTF-8 提案文档 

此示例查询标签 http.status_code 的所有标签值:

curl https://:9090/api/v1/label/U__http_2e_status_code/values
{
   "status" : "success",
   "data" : [
      "200",
      "404"
   ]
}

查询 Exemplars

这是实验性功能,将来可能会发生变化。以下端点返回特定时间范围内有效的 PromQL 查询的 Exemplars 列表:

GET /api/v1/query_exemplars
POST /api/v1/query_exemplars

URL 查询参数

  • query=<string>:Prometheus 表达式查询字符串。
  • start=<rfc3339 | unix_timestamp>:开始时间戳。
  • end=<rfc3339 | unix_timestamp>:结束时间戳。
curl -g 'https://:9090/api/v1/query_exemplars?query=test_exemplar_metric_total&start=2020-09-14T15:22:25.479Z&end=2020-09-14T15:23:25.479Z'
{
    "status": "success",
    "data": [
        {
            "seriesLabels": {
                "__name__": "test_exemplar_metric_total",
                "instance": "localhost:8090",
                "job": "prometheus",
                "service": "bar"
            },
            "exemplars": [
                {
                    "labels": {
                        "trace_id": "EpTxMJ40fUus7aGY"
                    },
                    "value": "6",
                    "timestamp": 1600096945.479
                }
            ]
        },
        {
            "seriesLabels": {
                "__name__": "test_exemplar_metric_total",
                "instance": "localhost:8090",
                "job": "prometheus",
                "service": "foo"
            },
            "exemplars": [
                {
                    "labels": {
                        "trace_id": "Olp9XHlq763ccsfa"
                    },
                    "value": "19",
                    "timestamp": 1600096955.479
                },
                {
                    "labels": {
                        "trace_id": "hCtjygkIHwAN9vs4"
                    },
                    "value": "20",
                    "timestamp": 1600096965.489
                }
            ]
        }
    ]
}

表达式查询结果格式

表达式查询可以在 data 部分的 result 属性中返回以下响应值。<sample_value> 占位符是数值样本值。JSON 不支持诸如 NaNInf-Inf 等特殊浮点值,因此样本值作为带引号的 JSON 字符串传输,而不是原始数字。

仅当响应中存在原生直方图时,才会显示键 "histogram""histograms"。其占位符 <histogram> 在下文中详细解释。

范围向量

范围向量作为结果类型 matrix 返回。相应的 result 属性具有以下格式:

[
  {
    "metric": { "<label_name>": "<label_value>", ... },
    "values": [ [ <unix_time>, "<sample_value>" ], ... ],
    "histograms": [ [ <unix_time>, <histogram> ], ... ]
  },
  ...
]

每个序列可以具有 "values" 键、"histograms" 键,或两者兼有。对于给定的时间戳,只会存在一种浮点类型或直方图类型的样本。

序列按 metric 排序返回。诸如 sortsort_by_label 等函数对范围向量无效。

瞬时向量

瞬时向量作为结果类型 vector 返回。相应的 result 属性具有以下格式:

[
  {
    "metric": { "<label_name>": "<label_value>", ... },
    "value": [ <unix_time>, "<sample_value>" ],
    "histogram": [ <unix_time>, <histogram> ]
  },
  ...
]

每个序列可以具有 "value" 键或 "histogram" 键,但不能同时拥有两者。

除非使用了诸如 sortsort_by_label 等函数,否则不保证序列以任何特定顺序返回。

标量

标量结果作为结果类型 scalar 返回。相应的 result 属性具有以下格式:

[ <unix_time>, "<scalar_value>" ]

字符串

字符串结果作为结果类型 string 返回。相应的 result 属性具有以下格式:

[ <unix_time>, "<string_value>" ]

原生直方图

上面使用的 <histogram> 占位符格式如下:

{
  "count": "<count_of_observations>",
  "sum": "<sum_of_observations>",
  "buckets": [ [ <boundary_rule>, "<left_boundary>", "<right_boundary>", "<count_in_bucket>" ], ... ]
}

<boundary_rule> 占位符是一个 0 到 3 之间的整数,含义如下:

  • 0:“左开”(左边界为排除,右边界为包含)
  • 1:“右开”(左边界为包含,右边界为排除)
  • 2:“双开”(两个边界均为排除)
  • 3:“双闭”(两个边界均为包含)

注意,在当前实现的桶方案中,正桶为“左开”,负桶为“右开”,而零桶(具有负左边界和正右边界)为“双闭”。

抓取池

以下端点返回所有已配置抓取池的列表:

GET /api/v1/scrape_pools

JSON 响应的 data 部分是一个字符串抓取池名称列表。

curl https://:9090/api/v1/scrape_pools
{
  "status": "success",
  "data": {
    "scrapePools": [
      "prometheus",
      "node_exporter",
      "blackbox"
    ]
  }
}

v2.42 新增

目标

以下端点返回 Prometheus 目标发现当前状态的概览:

GET /api/v1/targets

默认情况下,活跃目标和被丢弃的目标都包含在响应中。被丢弃的目标受 keep_dropped_targets 限制(如果已设置)。labels 表示重标记后生成的标签集。discoveredLabels 表示在服务发现期间、重标记发生前检索到的未修改标签。

curl https://:9090/api/v1/targets
{
  "status": "success",
  "data": {
    "activeTargets": [
      {
        "discoveredLabels": {
          "__address__": "127.0.0.1:9090",
          "__metrics_path__": "/metrics",
          "__scheme__": "http",
          "job": "prometheus"
        },
        "labels": {
          "instance": "127.0.0.1:9090",
          "job": "prometheus"
        },
        "scrapePool": "prometheus",
        "scrapeUrl": "http://127.0.0.1:9090/metrics",
        "globalUrl": "http://example-prometheus:9090/metrics",
        "lastError": "",
        "lastScrape": "2017-01-17T15:07:44.723715405+01:00",
        "lastScrapeDuration": 0.050688943,
        "health": "up",
        "scrapeInterval": "1m",
        "scrapeTimeout": "10s"
      }
    ],
    "droppedTargets": [
      {
        "discoveredLabels": {
          "__address__": "127.0.0.1:9100",
          "__metrics_path__": "/metrics",
          "__scheme__": "http",
          "__scrape_interval__": "1m",
          "__scrape_timeout__": "10s",
          "job": "node"
        },
        "scrapePool": "node"
      }
    ]
  }
}

state 查询参数允许调用者按活跃或被丢弃的目标进行过滤(例如 state=active, state=dropped, state=any)。注意,对于被过滤掉的目标,仍会返回一个空数组。其他值将被忽略。

curl 'https://:9090/api/v1/targets?state=active'
{
  "status": "success",
  "data": {
    "activeTargets": [
      {
        "discoveredLabels": {
          "__address__": "127.0.0.1:9090",
          "__metrics_path__": "/metrics",
          "__scheme__": "http",
          "job": "prometheus"
        },
        "labels": {
          "instance": "127.0.0.1:9090",
          "job": "prometheus"
        },
        "scrapePool": "prometheus",
        "scrapeUrl": "http://127.0.0.1:9090/metrics",
        "globalUrl": "http://example-prometheus:9090/metrics",
        "lastError": "",
        "lastScrape": "2017-01-17T15:07:44.723715405+01:00",
        "lastScrapeDuration": 50688943,
        "health": "up"
      }
    ],
    "droppedTargets": []
  }
}

scrapePool 查询参数允许调用者按抓取池名称进行过滤。

curl 'https://:9090/api/v1/targets?scrapePool=node_exporter'
{
  "status": "success",
  "data": {
    "activeTargets": [
      {
        "discoveredLabels": {
          "__address__": "127.0.0.1:9091",
          "__metrics_path__": "/metrics",
          "__scheme__": "http",
          "job": "node_exporter"
        },
        "labels": {
          "instance": "127.0.0.1:9091",
          "job": "node_exporter"
        },
        "scrapePool": "node_exporter",
        "scrapeUrl": "http://127.0.0.1:9091/metrics",
        "globalUrl": "http://example-prometheus:9091/metrics",
        "lastError": "",
        "lastScrape": "2017-01-17T15:07:44.723715405+01:00",
        "lastScrapeDuration": 50688943,
        "health": "up"
      }
    ],
    "droppedTargets": []
  }
}

重标记步骤

此端点是实验性的,将来可能会发生变化。目前它仅供 Prometheus 自身的 Web UI 使用,端点名称和返回的确切格式可能会在不同的 Prometheus 版本之间发生变化。如果 UI 不再需要它,它也可能被移除。

以下端点返回重标记规则及其对给定目标标签集影响的逐步列表:

GET /api/v1/targets/relabel_steps

URL 查询参数

  • scrapePool=<string>:目标的抓取池名称,用于确定要应用的重标记规则。必需。
  • labels=<string>:一个 JSON 对象,包含应用任何重标记之前目标的标签集。必需。

以下示例返回 prometheus 抓取池中发现的目标的重标记步骤,该目标标签集为 {"__address__": "localhost:9090", "job": "prometheus"}

curl -g 'https://:9090/api/v1/targets/relabel_steps?scrapePool=prometheus&labels={"__address__":"localhost:9090","job":"prometheus"}'
{
   "data" : {
      "steps" : [
         {
            "keep" : true,
            "output" : {
               "__address__" : "localhost:9090",
               "env" : "development",
               "job" : "prometheus"
            },
            "rule" : {
               "action" : "replace",
               "regex" : "(.*)",
               "replacement" : "development",
               "separator" : ";",
               "target_label" : "env"
            }
         },
         {
            "keep" : false,
            "output" : {},
            "rule" : {
               "action" : "drop",
               "regex" : "localhost:.*",
               "replacement" : "$1",
               "separator" : ";",
               "source_labels" : [
                  "__address__"
               ]
            }
         }
      ]
   },
   "status" : "success"
}

规则

/rules API 端点返回当前加载的告警和记录规则列表。此外,它还返回每个告警规则当前由 Prometheus 实例触发的活跃告警。

由于 /rules 端点相当新,它没有与总体 API v1 相同的稳定性保证。

GET /api/v1/rules

URL 查询参数

  • type=alert|record:仅返回告警规则(例如 type=alert)或记录规则(例如 type=record)。当参数缺失或为空时,不进行过滤。
  • rule_name[]=<string>:仅返回具有给定规则名称的规则。如果重复此参数,则返回具有提供的任何名称的规则。如果我们过滤掉了一个组中的所有规则,则不会返回该组。当参数缺失或为空时,不进行过滤。
  • rule_group[]=<string>:仅返回具有给定规则组名称的规则。如果重复此参数,则返回具有提供的任何规则组名称的规则。当参数缺失或为空时,不进行过滤。
  • file[]=<string>:仅返回具有给定文件路径的规则。如果重复此参数,则返回具有提供的任何文件路径的规则。当参数缺失或为空时,不进行过滤。
  • exclude_alerts=<bool>:仅返回规则,不返回活跃告警。
  • match[]=<label_selector>:仅返回具有满足标签选择器的已配置标签的规则。如果重复此参数,则返回匹配任何标签选择器集的规则。请注意,匹配是在每个规则定义中的标签上进行的,而不是在模板展开后的值上(对于告警规则)。可选。
  • group_limit=<number>group_limit 参数允许您指定单次响应中返回的规则组数量限制。如果规则组总数超过指定的 group_limit 值,响应将包含 groupNextToken 属性。您可以在后续请求的 group_next_token 参数中使用此 groupNextToken 属性的值来分页获取剩余的规则组。在最终响应中将不会包含 groupNextToken 属性,表明您已获取所有可用的规则组。请注意,如果在分页过程中修改了规则组,则不保证响应的一致性。
  • group_next_token:当设置 group_limit 属性时,在之前请求中返回的分页令牌。该分页令牌用于迭代分页获取大量规则组。要使用 group_next_token 参数,也必须提供 group_limit 参数。如果在您分页浏览规则组时移除了与下一个令牌对应的规则组,则将返回状态码为 400 的响应。
curl https://:9090/api/v1/rules
{
    "data": {
        "groups": [
            {
                "rules": [
                    {
                        "alerts": [
                            {
                                "activeAt": "2018-07-04T20:27:12.60602144+02:00",
                                "annotations": {
                                    "summary": "High request latency"
                                },
                                "labels": {
                                    "alertname": "HighRequestLatency",
                                    "severity": "page"
                                },
                                "state": "firing",
                                "value": "1e+00"
                            }
                        ],
                        "annotations": {
                            "summary": "High request latency"
                        },
                        "duration": 600,
                        "health": "ok",
                        "labels": {
                            "severity": "page"
                        },
                        "name": "HighRequestLatency",
                        "query": "job:request_latency_seconds:mean5m{job=\"myjob\"} > 0.5",
                        "type": "alerting"
                    },
                    {
                        "health": "ok",
                        "name": "job:http_inprogress_requests:sum",
                        "query": "sum by (job) (http_inprogress_requests)",
                        "type": "recording"
                    }
                ],
                "file": "/rules.yaml",
                "interval": 60,
                "limit": 0,
                "name": "example"
            }
        ]
    },
    "status": "success"
}

警报 (Alerts)

/alerts 端点返回所有活跃警报的列表。

由于 /alerts 端点相对较新,它不具备与整体 API v1 相同的稳定性保证。

GET /api/v1/alerts
curl https://:9090/api/v1/alerts
{
    "data": {
        "alerts": [
            {
                "activeAt": "2018-07-04T20:27:12.60602144+02:00",
                "annotations": {},
                "labels": {
                    "alertname": "my-alert"
                },
                "state": "firing",
                "value": "1e+00"
            }
        ]
    },
    "status": "success"
}

查询目标元数据 (Querying target metadata)

以下端点返回当前从目标抓取的指标元数据。该端点的限制是仅返回直接从目标抓取的元数据,通过 Remote-Write 或 OTLP 发送到 Prometheus 的元数据不包含在此端点中,也不会在 UI 的“探索指标 (Explore Metrics)”中显示。此功能处于实验性阶段,未来可能会有变动。

GET /api/v1/targets/metadata

URL 查询参数

  • match_target=<label_selectors>:通过标签集匹配目标的标签选择器。如果留空,则选择所有目标。
  • metric=<string>:用于检索元数据的指标名称。如果留空,则检索所有指标元数据。
  • limit=<number>:匹配目标的最大数量。

查询结果的 data 部分由一组对象组成,这些对象包含指标元数据和目标标签集。

以下示例返回标签为 job="prometheus" 的前两个目标中 go_goroutines 指标的所有元数据条目。

curl -G https://:9091/api/v1/targets/metadata \
    --data-urlencode 'metric=go_goroutines' \
    --data-urlencode 'match_target={job="prometheus"}' \
    --data-urlencode 'limit=2'
{
  "status": "success",
  "data": [
    {
      "target": {
        "instance": "127.0.0.1:9090",
        "job": "prometheus"
      },
      "type": "gauge",
      "help": "Number of goroutines that currently exist.",
      "unit": ""
    },
    {
      "target": {
        "instance": "127.0.0.1:9091",
        "job": "prometheus"
      },
      "type": "gauge",
      "help": "Number of goroutines that currently exist.",
      "unit": ""
    }
  ]
}

以下示例返回标签为 instance="127.0.0.1:9090" 的所有目标的所有指标的元数据。

curl -G https://:9091/api/v1/targets/metadata \
    --data-urlencode 'match_target={instance="127.0.0.1:9090"}'
{
  "status": "success",
  "data": [
    // ...
    {
      "target": {
        "instance": "127.0.0.1:9090",
        "job": "prometheus"
      },
      "metric": "prometheus_treecache_zookeeper_failures_total",
      "type": "counter",
      "help": "The total number of ZooKeeper failures.",
      "unit": ""
    },
    {
      "target": {
        "instance": "127.0.0.1:9090",
        "job": "prometheus"
      },
      "metric": "prometheus_tsdb_reloads_total",
      "type": "counter",
      "help": "Number of times the database reloaded block data from disk.",
      "unit": ""
    },
    // ...
  ]
}

查询指标元数据 (Querying metric metadata)

它返回当前从目标抓取的指标的元数据。但是,它不提供任何目标信息。此功能处于实验性阶段,未来可能会有变动。

GET /api/v1/metadata

URL 查询参数

  • limit=<number>:返回指标的最大数量。
  • limit_per_metric=<number>:每个指标返回元数据的最大数量。
  • metric=<string>:用于过滤元数据的指标名称。如果留空,则检索所有指标元数据。

查询结果的 data 部分由一个对象组成,其中每个键都是一个指标名称,每个值都是该指标名称在所有目标中暴露的唯一元数据对象的列表。

以下示例返回两个指标。请注意,指标 http_requests_total 在列表中有一个以上的对象。至少有一个目标的 HELP 值与其他目标不匹配。

curl -G https://:9090/api/v1/metadata?limit=2
{
  "status": "success",
  "data": {
    "cortex_ring_tokens": [
      {
        "type": "gauge",
        "help": "Number of tokens in the ring",
        "unit": ""
      }
    ],
    "http_requests_total": [
      {
        "type": "counter",
        "help": "Number of HTTP requests",
        "unit": ""
      },
      {
        "type": "counter",
        "help": "Amount of HTTP requests",
        "unit": ""
      }
    ]
  }
}

以下示例为每个指标仅返回一个元数据条目。

curl -G https://:9090/api/v1/metadata?limit_per_metric=1
{
  "status": "success",
  "data": {
    "cortex_ring_tokens": [
      {
        "type": "gauge",
        "help": "Number of tokens in the ring",
        "unit": ""
      }
    ],
    "http_requests_total": [
      {
        "type": "counter",
        "help": "Number of HTTP requests",
        "unit": ""
      }
    ]
  }
}

以下示例仅返回指标 http_requests_total 的元数据。

curl -G https://:9090/api/v1/metadata?metric=http_requests_total
{
  "status": "success",
  "data": {
    "http_requests_total": [
      {
        "type": "counter",
        "help": "Number of HTTP requests",
        "unit": ""
      },
      {
        "type": "counter",
        "help": "Amount of HTTP requests",
        "unit": ""
      }
    ]
  }
}

Alertmanagers

以下端点返回 Prometheus Alertmanager 发现的当前状态概览。

GET /api/v1/alertmanagers

活跃和已丢弃的 Alertmanager 都是响应的一部分。

curl https://:9090/api/v1/alertmanagers
{
  "status": "success",
  "data": {
    "activeAlertmanagers": [
      {
        "url": "http://127.0.0.1:9090/api/v1/alerts"
      }
    ],
    "droppedAlertmanagers": [
      {
        "url": "http://127.0.0.1:9093/api/v1/alerts"
      }
    ]
  }
}

状态 (Status)

以下状态端点公开了当前的 Prometheus 配置。

配置 (Config)

以下端点返回当前加载的配置文件。

GET /api/v1/status/config

配置以转储的 YAML 文件形式返回。由于 YAML 库的限制,不包含 YAML 注释。

curl https://:9090/api/v1/status/config
{
  "status": "success",
  "data": {
    "yaml": "<content of the loaded config file in YAML>",
  }
}

标志

以下端点返回 Prometheus 配置时所使用的标志值。

GET /api/v1/status/flags

所有值的结果类型均为 string

curl https://:9090/api/v1/status/flags
{
  "status": "success",
  "data": {
    "alertmanager.notification-queue-capacity": "10000",
    "alertmanager.timeout": "10s",
    "log.level": "info",
    "query.lookback-delta": "5m",
    "query.max-concurrency": "20",
    ...
  }
}

v2.2 新增

运行时信息 (Runtime Information)

以下端点返回关于 Prometheus 服务器的各种运行时信息属性。

GET /api/v1/status/runtimeinfo

返回的值类型各不相同,具体取决于运行时属性的性质。

curl https://:9090/api/v1/status/runtimeinfo
{
  "status": "success",
  "data": {
    "startTime": "2019-11-02T17:23:59.301361365+01:00",
    "CWD": "/",
    "hostname" : "DESKTOP-717H17Q",
    "serverTime": "2025-01-05T18:27:33Z",
    "reloadConfigSuccess": true,
    "lastConfigTime": "2019-11-02T17:23:59+01:00",
    "timeSeriesCount": 873,
    "corruptionCount": 0,
    "goroutineCount": 48,
    "GOMAXPROCS": 4,
    "GOGC": "",
    "GODEBUG": "",
    "storageRetention": "15d"
  }
}
注意返回的确切运行时属性可能会在 Prometheus 版本之间更改,恕不另行通知。

v2.14 新增

构建信息 (Build Information)

以下端点返回关于 Prometheus 服务器的各种构建信息属性。

GET /api/v1/status/buildinfo

所有值的结果类型均为 string

curl https://:9090/api/v1/status/buildinfo
{
  "status": "success",
  "data": {
    "version": "2.13.1",
    "revision": "cb7cbad5f9a2823a622aaa668833ca04f50a0ea7",
    "branch": "master",
    "buildUser": "julius@desktop",
    "buildDate": "20191102-16:19:59",
    "goVersion": "go1.13.1"
  }
}
注意返回的确切构建属性可能会在 Prometheus 版本之间更改,恕不另行通知。

v2.14 新增

TSDB 统计信息 (TSDB Stats)

以下端点返回关于 Prometheus TSDB 的各种基数统计信息。

GET /api/v1/status/tsdb

URL 查询参数

  • limit=<number>:将每组统计信息的返回项数量限制为给定数字。默认返回 10 项。允许的最大限制为 10000。

查询结果的 data 部分包含:

  • headStats:提供以下关于 TSDB 头块 (head block) 的数据:
    • numSeries:序列数量。
    • chunkCount:块数量。
    • minTime:当前最小时间戳(毫秒)。
    • maxTime:当前最大时间戳(毫秒)。
  • seriesCountByMetricName:提供指标名称列表及其序列计数。
  • labelValueCountByLabelName:提供标签名称列表及其值计数。
  • memoryInBytesByLabelName:提供标签名称列表及所使用的内存(字节)。内存使用量通过累加给定标签名称的所有值长度来计算。
  • seriesCountByLabelPair:提供标签值对列表及其序列计数。
curl https://:9090/api/v1/status/tsdb
{
  "status": "success",
  "data": {
    "headStats": {
      "numSeries": 508,
      "chunkCount": 937,
      "minTime": 1591516800000,
      "maxTime": 1598896800143,
    },
    "seriesCountByMetricName": [
      {
        "name": "net_conntrack_dialer_conn_failed_total",
        "value": 20
      },
      {
        "name": "prometheus_http_request_duration_seconds_bucket",
        "value": 20
      }
    ],
    "labelValueCountByLabelName": [
      {
        "name": "__name__",
        "value": 211
      },
      {
        "name": "event",
        "value": 3
      }
    ],
    "memoryInBytesByLabelName": [
      {
        "name": "__name__",
        "value": 8266
      },
      {
        "name": "instance",
        "value": 28
      }
    ],
    "seriesCountByLabelValuePair": [
      {
        "name": "job=prometheus",
        "value": 425
      },
      {
        "name": "instance=localhost:9090",
        "value": 425
      }
    ]
  }
}

v3.6.0 新增

TSDB 块 (TSDB Blocks)

注意:此端点处于实验性阶段,未来可能会有变动。端点名称和返回数据的确切格式可能会在 Prometheus 版本之间更改。此端点返回的确切元数据是实现细节,可能会在以后的 Prometheus 版本中更改。

以下端点返回当前加载的 TSDB 块列表及其元数据。

GET /api/v1/status/tsdb/blocks

此端点为每个块返回以下信息:

  • ulid:块的唯一 ID。
  • minTime:块的最小时间戳(毫秒)。
  • maxTime:块的最大时间戳(毫秒)。
  • stats(统计信息):
    • numSeries:块中的序列数量。
    • numSamples:块中的样本数量。
    • numChunks:块中的块数量。
  • compaction(压缩):
    • level:块的压缩级别。
    • sources:用于压缩此块的源块 ULID 列表。
  • version:块版本。
curl https://:9090/api/v1/status/tsdb/blocks
{
  "status": "success",
  "data": {
    "blocks": [
      {
        "ulid": "01JZ8JKZY6XSK3PTDP9ZKRWT60",
        "minTime": 1750860620060,
        "maxTime": 1750867200000,
        "stats": {
          "numSamples": 13701,
          "numSeries": 716,
          "numChunks": 716
        },
        "compaction": {
          "level": 1,
          "sources": [
            "01JZ8JKZY6XSK3PTDP9ZKRWT60"
          ]
        },
        "version": 1
      }
    ]
  }
}

v2.15 新增

WAL 重放统计 (WAL Replay Stats)

以下端点返回关于 WAL 重放的信息:

GET /api/v1/status/walreplay
  • read:迄今为止已重放的段数。
  • total:需要重放的段总数。
  • progress:重放进度 (0 - 100%)。
  • state:重放的状态。可能的状态包括:
    • waiting:等待重放开始。
    • in progress:重放正在进行中。
    • done:重放已完成。
curl https://:9090/api/v1/status/walreplay
{
  "status": "success",
  "data": {
    "min": 2,
    "max": 5,
    "current": 40,
    "state": "in progress"
  }
}
注意此端点在服务器被标记为就绪之前可用,并实时更新,以便监控 WAL 重放进度。

v2.28 新增

TSDB 管理 API (TSDB Admin APIs)

这些 API 为高级用户提供了数据库功能。除非设置了 --web.enable-admin-api,否则这些 API 不会启用。

快照 (Snapshot)

快照功能会在 TSDB 数据目录下创建 snapshots/<datetime>-<rand>,并将所有当前数据的快照存入其中,同时返回该目录作为响应。它可以选择跳过仅存在于头块中且尚未压缩到磁盘的数据。

POST /api/v1/admin/tsdb/snapshot
PUT /api/v1/admin/tsdb/snapshot

URL 查询参数

  • skip_head=<bool>:跳过头块中的数据。可选。
curl -XPOST https://:9090/api/v1/admin/tsdb/snapshot
{
  "status": "success",
  "data": {
    "name": "20171210T211224Z-2be650b6d019eb54"
  }
}

快照现已存在于 <data-dir>/snapshots/20171210T211224Z-2be650b6d019eb54

v2.1 新增,自 v2.9 起支持 PUT

删除序列 (Delete Series)

DeleteSeries 会在时间范围内删除选定序列的数据。实际数据仍存在于磁盘上,并在以后的压缩中清理,或者可以通过访问 清理墓碑 (Clean Tombstones) 端点显式清理。

如果成功,返回 204

POST /api/v1/admin/tsdb/delete_series
PUT /api/v1/admin/tsdb/delete_series

URL 查询参数

  • match[]=<series_selector>:用于选择要删除序列的重复标签匹配器参数。必须提供至少一个 match[] 参数。
  • start=<rfc3339 | unix_timestamp>:开始时间戳。可选,默认为可能的最小时间。
  • end=<rfc3339 | unix_timestamp>:结束时间戳。可选,默认为可能的最大时间。

如果不提及开始和结束时间,将清除数据库中匹配序列的所有数据。

示例

curl -X POST \
  -g 'https://:9090/api/v1/admin/tsdb/delete_series?match[]=up&match[]=process_start_time_seconds{job="prometheus"}'
注意此端点将序列中的样本标记为已删除,但不一定会阻止相关的序列元数据在受影响的时间范围的元数据查询中继续返回(即使在清理墓碑后)。元数据删除的确切程度是实现细节,未来可能会有变动。

v2.1 新增,自 v2.9 起支持 PUT

清理墓碑 (Clean Tombstones)

CleanTombstones 从磁盘中删除已删除的数据并清理现有的墓碑。这可以在删除序列后使用,以释放空间。

如果成功,返回 204

POST /api/v1/admin/tsdb/clean_tombstones
PUT /api/v1/admin/tsdb/clean_tombstones

此操作不接受参数或主体。

curl -XPOST https://:9090/api/v1/admin/tsdb/clean_tombstones

v2.1 新增,自 v2.9 起支持 PUT

远程写入接收器 (Remote Write Receiver)

Prometheus 可以配置为 Prometheus 远程写入协议的接收器。这不被视为摄取样本的高效方式。请谨慎用于特定的低流量场景。它不适合取代通过抓取进行的摄取,也不适合将 Prometheus 转变为基于推送的指标收集系统。

通过设置 --web.enable-remote-write-receiver 启用远程写入接收器。启用后,远程写入接收器端点为 /api/v1/write。更多详细信息请见此处

v2.33 新增

OTLP 接收器 (OTLP Receiver)

Prometheus 可以配置为 OTLP 指标协议的接收器。这不被视为摄取样本的高效方式。请谨慎用于特定的低流量场景。它不适合取代通过抓取进行的摄取。

通过设置 --web.enable-otlp-receiver 启用 OTLP 接收器。启用后,OTLP 接收器端点为 /api/v1/otlp/v1/metrics

v2.47 新增

OTLP Delta

Prometheus 可以将传入的增量时间指标转换为累积等效指标。这是通过 OpenTelemetry Collector 中的 deltatocumulative  完成的。

要启用,请传递 --enable-feature=otlp-deltatocumulative

v3.2 新增

通知 (Notifications)

以下端点提供有关 Prometheus 服务器本身的活跃状态通知信息。通知用于 Web UI。

这些端点处于实验性阶段。未来可能会有变动。

活跃通知 (Active Notifications)

/api/v1/notifications 端点返回所有当前活跃通知的列表。

GET /api/v1/notifications

示例

curl https://:9090/api/v1/notifications
{
  "status": "success",
  "data": [
    {
      "text": "Prometheus is shutting down and gracefully stopping all operations.",
      "date": "2024-10-07T12:33:08.551376578+02:00",
      "active": true
    }
  ]
}

v3.0 新增

实时通知 (Live Notifications)

/api/v1/notifications/live 端点使用 服务器发送事件 (Server-Sent Events)  实时流式传输通知。删除的通知将以 active: false 发送。连接到端点时将发送活跃通知。

GET /api/v1/notifications/live

示例

curl https://:9090/api/v1/notifications/live
data: {
  "status": "success",
  "data": [
    {
      "text": "Prometheus is shutting down and gracefully stopping all operations.",
      "date": "2024-10-07T12:33:08.551376578+02:00",
      "active": true
    }
  ]
}

注意:如果达到最大订阅者数量,/notifications/live 端点将返回 204 No Content 响应。您可以使用 --web.max-notifications-subscribers 标志设置最大监听者数量,默认值为 16。

GET /api/v1/notifications/live
204 No Content

v3.0 新增

功能 (Features)

以下端点返回 Prometheus 服务器中启用的功能列表。

GET /api/v1/features

此端点提供关于 Prometheus 实例中当前启用或禁用哪些功能的信息。功能被组织为类别,例如 apipromqlpromql_functions 等。

data 部分包含一个映射,其中每个键是一个功能类别,每个值是功能名称与其启用状态(布尔值)的映射。

curl https://:9090/api/v1/features
{
  "status": "success",
  "data": {
    "api": {
      "admin": false,
      "exclude_alerts": true
    },
    "otlp_receiver": {
      "delta_conversion": false,
      "native_delta_ingestion": false
    },
    "prometheus": {
      "agent_mode": false,
      "auto_reload_config": false
    },
    "promql": {
      "anchored": false,
      "at_modifier": true
    },
    "promql_functions": {
      "abs": true,
      "absent": true
    },
    "promql_operators": {
      "!=": true,
      "!~": true
    },
    "rules": {
      "concurrent_rule_eval": false,
      "keep_firing_for": true
    },
    "scrape": {
      "start_timestamp_zero_ingestion": false,
      "extra_metrics": false
    },
    "service_discovery": {
      "azure": true,
      "consul": true
    },
    "templating": {
      "args": true,
      "externalURL": true
    },
    "tsdb": {
      "delayed_compaction": false,
      "exemplar_storage": false
    }
  }
}

备注

  • 所有功能名称均使用 snake_case 命名约定。
  • 设置为 false 的功能可能会从响应中省略。
  • 客户端应将缺失的功能视为等同于 false
  • 为了前向兼容性,客户端必须忽略未知的特征名称和类别。

v3.8 新增

本页内容