prometheus-api-client-python
A Python client for the Prometheus HTTP API with tools for fetching, converting, and analyzing time series metrics data.
Repository Health
Technical Analysis
prometheus-api-client is a Python wrapper around the Prometheus HTTP API, built around a single PrometheusConnect class that handles authentication, retries, and both GET and POST query modes. Beyond raw HTTP calls, it ships companion classes — Metric, MetricsList, MetricSnapshotDataFrame, and MetricRangeDataFrame — that turn Prometheus’s raw JSON responses into objects you can add, compare, and load straight into pandas for analysis or plotting.
Originally built by Red Hat’s AIOps team, the library has stayed narrowly focused on one job: making it easy to pull and reshape time series data out of a Prometheus host, whether you’re building a custom alerting layer, feeding a machine learning pipeline, or exploring metrics ad hoc in a notebook. Heavier dependencies like pandas, numpy, and matplotlib are optional extras, so a minimal install can use PrometheusConnect alone.
What You Get
- PrometheusConnect client with GET/POST query modes, a configurable retry policy, proxy and custom-session support, and SSL toggling
- Metric and MetricsList classes that merge and arithmetic-combine data from the same time series, with automatic pruning of old data via oldest_data_datetime
- MetricSnapshotDataFrame and MetricRangeDataFrame converters that turn raw Prometheus JSON straight into pandas DataFrames
- Optional extras (dataframe, analytics, plot, all) so pandas/numpy/matplotlib are only installed when needed, keeping the base install lightweight
Common Use Cases
- Building a lightweight alerting or dashboard backend that queries Prometheus directly instead of going through Grafana’s API
- Feeding historical metrics into a Jupyter notebook or ML pipeline for anomaly detection and forecasting
- Writing ChatOps or CLI tools that need ad hoc PromQL queries without hand-rolling HTTP calls
- Backfilling or exporting metrics from one Prometheus host for archival or migration to another monitoring stack
Under The Hood
Architecture
The library is organized as a flat, single-package module (prometheus_api_client/) with lazy imports in init.py — a getattr hook that defers importing PrometheusConnect, Metric, MetricsList, and the DataFrame converters until they’re actually referenced, so a bare import prometheus_api_client doesn’t pull in pandas or numpy. PrometheusConnect (prometheus_connect.py) is the single entry point for HTTP access, wrapping a requests.Session with a configurable HTTPAdapter/Retry policy and exposing one method per Prometheus HTTP API endpoint (custom_query, get_metric_range_data, get_targets, and similar). Above that sits a small data-modeling layer — Metric wraps a single time series with arithmetic (add, eq) and pruning logic, MetricsList batches and merges same-series Metric objects, and MetricSnapshotDataFrame/MetricRangeDataFrame convert either shape of Prometheus’s JSON directly into pandas. There’s no dependency injection or plugin system; the design trades architectural depth for a narrow, predictable API surface.
Tech Stack The core runtime dependency is just requests (via requests.Session, HTTPAdapter, and urllib3’s Retry) plus dateparser for flexible time-string parsing in parse_datetime/parse_timedelta. pandas, numpy, and matplotlib are all optional extras declared in setup.py (dataframe, analytics, plot, all) rather than hard requirements, keeping a minimal PrometheusConnect-only install lightweight — useful in constrained environments like Alpine-based Docker images, per the README. Packaging is plain setuptools with a version pulled from init.py at build time; releases publish to PyPI via a dedicated python-publish.yml workflow, and docs are built with Sphinx and hosted on Read the Docs.
Code Quality Tests live under tests/ and use pytest together with httmock to mock Prometheus HTTP responses, with dedicated test modules for the connect client, the Metric/MetricsList classes, both DataFrame converters, and the lazy-import behavior of init.py — a good sign the maintainers treat the lazy-loading refactor as a real API contract, not an implementation detail. Code style is enforced via a pre-commit config running black, flake8 (with pep8-naming), mypy (ignoring missing imports), and pydocstyle, backed by a python-package.yml GitHub Actions workflow plus a CodeQL security-scanning workflow. Error handling is explicit rather than swallowed — PrometheusConnect methods raise PrometheusApiClientException or requests exceptions on failure, and Metric raises a dedicated MetricValueConversionError when a string metric value can’t be converted to float.
API Design The public API is deliberately small and consistent: one PrometheusConnect object exposes the query surface, and simple, composable value objects (Metric, MetricsList) let you treat time series like Python collections you can add and compare rather than raw dicts. The one genuinely distinctive touch is the DataFrame layer — MetricSnapshotDataFrame and MetricRangeDataFrame are purpose-built converters for Prometheus’s two JSON response shapes, sparing users from writing that reshaping logic themselves, which is the kind of ergonomic shortcut that matters most for a client library used mainly in analysis notebooks. Boilerplate to get started is minimal: PrometheusConnect() with no arguments works against a local host, and get_current_metric_value/get_metric_range_data cover the common query shapes directly.