Prometheus API Client for Python
prometheus-api-client is a Python wrapper for the Prometheus HTTP API, providing tools for collecting and processing metrics. The library is currently at version 0.7.0 and maintains an active development cadence with regular updates and feature additions.
Warnings
- breaking Breaking change in v0.2.0: Date and time range inputs for `Metric` objects and querying methods (`get_metric_range_data`, etc.) changed from accepting strings to requiring `datetime.datetime` or `datetime.timedelta` objects.
- breaking Starting from v0.7.0, `pandas`, `numpy`, and `matplotlib` are no longer default dependencies. If your application relies on DataFrame or plotting functionalities, you must install the library with the corresponding extras (e.g., `pip install prometheus-api-client[dataframe]`).
- deprecated Internal use of `DataFrame.append` (a `pandas` method) may trigger `FutureWarning` in versions where it's still present. The `pandas.DataFrame.append` method is deprecated and will be removed in future `pandas` versions, recommending `pandas.concat` instead.
- gotcha Prometheus queries, especially complex ones or those over large time ranges, can lead to request timeouts. The library added timeout functionality in v0.5.7.
- gotcha Ensure the Prometheus host URL is correct and accessible. Common issues include incorrect protocol (http/https), port (default 9090), or SSL certificate verification failures.
Install
-
pip install prometheus-api-client -
pip install prometheus-api-client[dataframe] -
pip install prometheus-api-client[analytics] -
pip install prometheus-api-client[plot]
Imports
- PrometheusConnect
from prometheus_api_client import PrometheusConnect
- Metric
from prometheus_api_client import Metric
- MetricRangeDataFrame
from prometheus_api_client import MetricRangeDataFrame
- MetricSnapshotDataFrame
from prometheus_api_client import MetricSnapshotDataFrame
Quickstart
import os
from prometheus_api_client import PrometheusConnect
from datetime import datetime, timedelta
# Configure your Prometheus URL. Use environment variable for production.
prom_url = os.environ.get('PROMETHEUS_URL', 'http://localhost:9090')
# Establish connection to Prometheus
prom = PrometheusConnect(url=prom_url, disable_ssl=True)
# Get a list of all available metric names
all_metrics = prom.all_metrics()
print(f"Found {len(all_metrics)} metrics. Example: {all_metrics[:5]}")
# Query a specific metric for a range of data
end_time = datetime.now()
start_time = end_time - timedelta(hours=1)
metric_data = prom.get_metric_range_data(
query='up',
start_time=start_time,
end_time=end_time,
step='5m'
)
print(f"'up' metric data points fetched: {len(metric_data)}")
# Example of getting current value
current_up = prom.get_current_metric_value(query='up')
print(f"Current 'up' metric values: {current_up[:2]}")