Operations 7 min read

How to Retrieve and Analyze Prometheus Monitoring Data via API

This guide explains how to use Prometheus' stable V1 API to perform instant and range queries, handle common error codes, parse JSON responses, and fetch metrics programmatically with curl or Python, enabling deeper data analysis and cost management.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
How to Retrieve and Analyze Prometheus Monitoring Data via API

01. API Format

Prometheus provides a stable V1 API whose base path is /api/v1. Both GET and POST methods are supported, and a successful request returns a 2xx status code.

If the request fails, typical error codes include:

400 Bad Request – missing or incorrect parameters.
422 Unprocessable Entity – expression cannot be executed.
503 Service Unavailable – query timed out or was aborted.

The API offers many endpoint types such as expression queries, metadata queries, configuration queries, rule queries, and even data cleanup.

When a request succeeds, the response follows this JSON structure:

{
  "status": "success" | "error",
  "data": <data>,
  // present only when status is "error"
  "errorType": "<string>",
  "error": "<string>",
  // optional warnings array
  "warnings": ["<string>"]
}

02. API Calls

1. Instant Query

This endpoint evaluates an expression at a single point in time.

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

Supported query parameters:

query – Prometheus expression string.

time – optional evaluation timestamp (RFC3339 or Unix).

timeout – optional query timeout (defaults to the global -query.timeout).

Example curl to fetch node_load5 for instance 192.168.214.108:9100:

curl http://localhost:9090/api/v1/query?query=node_load5{instance="192.168.214.108:9100"}

Sample response (status = success, value contains timestamp and metric value):

{
  "status": "success",
  "data": {
    "resultType": "vector",
    "result": [
      {
        "metric": {
          "__name__": "node_load5",
          "instance": "192.168.214.108:9100",
          "job": "node"
        },
        "value": [1666865246.993, "0.04"]
      }
    ]
  }
}

2. Range Query

This endpoint returns a series of data points over a time range.

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

Supported parameters:

query – Prometheus expression string.

start – start timestamp (RFC3339 or Unix).

end – end timestamp (RFC3339 or Unix).

step – resolution step (duration or float).

timeout – optional query timeout.

Example curl to retrieve node_load5 values for the same instance over a three‑minute window with a 60‑second step:

curl http://localhost:9090/api/v1/query_range?query=node_load5{instance="192.168.214.108:9100"}&start=2022-10-28T02:10:10.000Z&end=2022-10-28T02:13:00.000Z&step=60s

Sample response (status = success, result type = matrix, three data points):

{
  "status": "success",
  "data": {
    "resultType": "matrix",
    "result": [
      {
        "metric": {
          "__name__": "node_load5",
          "instance": "192.168.214.108:9100",
          "job": "node"
        },
        "values": [
          [1666923010, "0.04"],
          [1666923070, "0.04"],
          [1666923130, "0.03"]
        ]
      }
    ]
  }
}

03. Getting Data Programmatically

For production use, retrieve metrics with code instead of manual curl commands. Below is a Python example that uses the requests library.

$ pip install requests
# -*- coding: utf-8 -*-
import requests

# Define parameters
url = 'http://192.168.214.108:9090'
query_api = '/api/v1/query'
params = 'query=node_load5{instance="192.168.214.108:9100"}'

# Call Prometheus API
res = requests.get(url + query_api, params)
metrics = res.json().get("data").get("result")

if metrics:
    value = metrics[0].get('value')[1]
    print('Server 192.168.214.108 node_load5 value is %s' % value)
else:
    print('Unable to fetch valid data')

Running the script produces output such as:

$ python test_api.py
服务器 192.168.214.108的node_load5值为 0.01

Conclusion: This article demonstrates basic usage of the Prometheus API for instant and range queries and shows how to fetch metrics with Python; for more advanced endpoints, refer to the official documentation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

APIData RetrievalRange QueryInstant Query
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.