Registry / observability / prometheus-api-client

prometheus-api-client

JSON →
library0.7.2pypypi✓ verified 25d ago

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.

pip install prometheus-api-client
INSTALL
IMPORT
SIG · PROMETHEUS-API-CLI
P
prometheus-api-client
observabilitypythonv0.7.2
Install
7.0s avg
Import
354ms
Disk
50MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.7.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.363s · 31MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 7.0s · import 0.345s · 99MB
50MB installed
● package 50MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

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

This quickstart demonstrates how to connect to a Prometheus host, retrieve all available metric names, query a metric for a specific time range, and fetch its current value. It uses environment variables for the Prometheus URL for better practice.

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]}")
Debug
Known issues
breakingBreaking 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.
fix
Update date/time arguments in your code to use `datetime.datetime.now()`, `datetime.timedelta()`, or similar `datetime` objects instead of string representations.
affects: <0.2.0
breakingStarting 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]`).
fix
Install the necessary optional dependencies using `pip install prometheus-api-client[dataframe]`, `[analytics]`, or `[plot]` as required by your application's functionality.
affects: >=0.7.0
deprecatedInternal 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.
fix
While this might be an internal library issue, if you manually manipulate DataFrames returned by `prometheus-api-client` and use `.append()`, consider migrating to `pd.concat()` for better performance and to avoid future deprecation warnings.
affects: All versions (due to `pandas` dependency update)
gotchaPrometheus queries, especially complex ones or those over large time ranges, can lead to request timeouts. The library added timeout functionality in v0.5.7.
fix
For `PrometheusConnect` instances, set a `timeout` parameter in query methods or during initialization. Ensure your Prometheus server, network, and any proxies are configured for appropriate timeout values.
affects: <0.5.7 (no explicit timeout support), >=0.5.7 (timeouts can be configured)
gotchaEnsure the Prometheus host URL is correct and accessible. Common issues include incorrect protocol (http/https), port (default 9090), or SSL certificate verification failures.
fix
Verify the `url` parameter passed to `PrometheusConnect`. If connecting to an HTTPS endpoint with self-signed or untrusted certificates, set `disable_ssl=True` (for development/testing only) or configure proper certificate validation.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'prometheus-api-client'
The `prometheus-api-client` library is not installed in your Python environment or the environment where your code is running.
fix
Install the library using pip: `pip install prometheus-api-client`.
ImportError: cannot import name 'PrometheusConnect' from 'prometheus_api_client'
This error typically occurs when attempting to import `PrometheusConnect` (or other main classes like `Metric`, `MetricSnapshotDataFrame`) directly from the top-level `prometheus_api_client` package in an older version, or if there's a circular import or corrupted installation. The modern way is direct import.
fix
Ensure you are using the correct import statement: `from prometheus_api_client import PrometheusConnect`. If the error persists, update the library: `pip install --upgrade prometheus-api-client`.
PrometheusApiClientException: 400 Bad Request
This exception is raised when the Prometheus API receives a syntactically incorrect PromQL query or invalid parameters, which it cannot process.
fix
Review your PromQL query string and any parameters passed to `custom_query` or `query_range` methods for syntax errors, incorrect metric names, or improper label matchers. Test the query directly in the Prometheus UI to debug.
PrometheusApiClientException: 401 Unauthorized
The Prometheus server requires authentication, and the provided credentials (e.g., headers, username, password) are either missing or incorrect.
fix
Provide valid authentication credentials when initializing `PrometheusConnect`. For basic authentication, pass headers like `{'Authorization': 'Basic base64encoded_username:password'}` or ensure `url` includes credentials if supported by your Prometheus setup. For bearer tokens, use `headers={'Authorization': 'Bearer YOUR_TOKEN'}`.
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionRefusedError(111, 'Connection refused'))
The client application is unable to establish a network connection to the Prometheus server. This could be due to an incorrect URL, the Prometheus server not running, network firewall rules, or incorrect port.
fix
Verify that the Prometheus server URL and port are correct and accessible from where your Python script is running. Check if the Prometheus server is active and listening on the expected address/port. Ensure no firewalls are blocking the connection.
Upgrade
Version history
0.7.2latest on PyPI · released Apr 13, 2026
Audit
Dependencies
requestsrequiredHandles HTTP communication with the Prometheus server.
urllib3requiredHTTP client library, often a dependency of requests.
pandasoptionalRequired for DataFrame functionality (e.g., MetricRangeDataFrame, MetricSnapshotDataFrame). Optional since v0.7.0.
numpyoptionalOften a dependency of pandas, used for numerical operations within DataFrames. Optional since v0.7.0.
matplotliboptionalRequired for plotting capabilities. Optional since v0.7.0.
Agent activity
26 hits · last 30 days
node
18
OpenAI (training)
3
Amazon
1
Resources
prometheus-api-client — pip install prometheus-api-client · libregistry