{"id":13605055,"url":"https://github.com/4n4nd/prometheus-api-client-python","last_synced_at":"2026-03-17T23:36:56.402Z","repository":{"id":37641389,"uuid":"174265685","full_name":"4n4nd/prometheus-api-client-python","owner":"4n4nd","description":"A python wrapper for the prometheus http api","archived":false,"fork":false,"pushed_at":"2024-07-09T18:59:13.000Z","size":1706,"stargazers_count":233,"open_issues_count":23,"forks_count":77,"subscribers_count":11,"default_branch":"master","last_synced_at":"2024-10-06T21:35:07.178Z","etag":null,"topics":["artificial-intelligence","collects-metrics","hacktoberfest","metrics-data","metrics-fetched","metrics-processing","prometheus","prometheus-api","prometheus-metrics","series-data"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/4n4nd.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"4n4nd","patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"lfx_crowdfunding":null,"custom":null}},"created_at":"2019-03-07T03:35:47.000Z","updated_at":"2024-09-30T19:05:30.000Z","dependencies_parsed_at":"2023-10-05T02:12:43.618Z","dependency_job_id":"895ea389-4345-4459-914a-8daffe8e2c1c","html_url":"https://github.com/4n4nd/prometheus-api-client-python","commit_stats":{"total_commits":187,"total_committers":43,"mean_commits":4.348837209302325,"dds":0.7754010695187166,"last_synced_commit":"49362b07cb3bec835a8211d81becd5ed205ace18"},"previous_names":["4n4nd/prometheus-connect"],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/4n4nd%2Fprometheus-api-client-python","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/4n4nd%2Fprometheus-api-client-python/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/4n4nd%2Fprometheus-api-client-python/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/4n4nd%2Fprometheus-api-client-python/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/4n4nd","download_url":"https://codeload.github.com/4n4nd/prometheus-api-client-python/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223489720,"owners_count":17153812,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["artificial-intelligence","collects-metrics","hacktoberfest","metrics-data","metrics-fetched","metrics-processing","prometheus","prometheus-api","prometheus-metrics","series-data"],"created_at":"2024-08-01T19:00:54.148Z","updated_at":"2025-12-13T17:05:29.836Z","avatar_url":"https://github.com/4n4nd.png","language":"Python","funding_links":["https://github.com/sponsors/4n4nd"],"categories":["Python"],"sub_categories":[],"readme":"# prometheus-api-client\n\n[![PyPI version](https://badge.fury.io/py/prometheus-api-client.svg)](https://badge.fury.io/py/prometheus-api-client) [![PyPI download month](https://img.shields.io/pypi/dm/prometheus-api-client.svg)](https://pypi.python.org/pypi/prometheus-api-client/) ![Pepy Total Downloads](https://img.shields.io/pepy/dt/prometheus-api-client?label=total%20downloads)\n\n\nA Python wrapper for the Prometheus http api and some tools for metrics processing.\n\n## Installation\n\nTo install the latest release:\n\n`pip install prometheus-api-client`\n\nTo install with all optional dependencies (pandas, numpy, matplotlib):\n\n`pip install prometheus-api-client[all]`\n\n**Note:** Starting from version 0.7.0, pandas, numpy, and matplotlib are optional dependencies. \nIf you only need `PrometheusConnect` without DataFrame support or plotting capabilities, you can install the minimal version which significantly reduces memory footprint and installation time, especially on Alpine-based Docker images.\n\nTo install only specific extras:\n- For DataFrame support: `pip install prometheus-api-client[dataframe]`\n- For analytics/aggregation operations: `pip install prometheus-api-client[analytics]`\n- For plotting support: `pip install prometheus-api-client[plot]`\n\nTo install directly from this branch:\n\n`pip install https://github.com/4n4nd/prometheus-api-client-python/zipball/master`\n\n## Links\n\n- [Slack](https://join.slack.com/share/zt-kw3v8t1e-hbcVH7X7bXORiQuQtsNZ4A)\n- [Google Chat](https://chat.google.com/room/AAAAzFPwq5s)\n- [Documentation](https://prometheus-api-client-python.readthedocs.io/en/master/source/prometheus_api_client.html)\n\n## Getting Started\n\n### Usage\n[Prometheus](https://prometheus.io/), a Cloud Native Computing Foundation project, is a systems and service monitoring system. It collects metrics (time series data) from configured targets at given intervals, evaluates rule expressions, displays the results, and can trigger alerts if some condition is observed to be true. The raw time series data obtained from a Prometheus host can sometimes be hard to interpret. To help better understand these metrics we have created a Python wrapper for the Prometheus http api for easier metrics processing and analysis.\n\nThe `prometheus-api-client` library consists of multiple modules which assist in connecting to a Prometheus host, fetching the required metrics and performing various aggregation operations on the time series data.\n\n#### Connecting and Collecting Metrics from a Prometheus host\nThe `PrometheusConnect` module of the library can be used to connect to a Prometheus host. This module is essentially a class created for the collection of metrics from a Prometheus host. It stores the following connection parameters:\n\n-   **url** - (str) url for the prometheus host\n-   **headers** – (dict) A dictionary of http headers to be used to communicate with the host. Example: {“Authorization”: “bearer my_oauth_token_to_the_host”}\n-   **disable_ssl** – (bool) If set to True, will disable ssl certificate verification for the http requests made to the prometheus host\n\n```python\nfrom prometheus_api_client import PrometheusConnect\nprom = PrometheusConnect(url =\"\u003cprometheus-host\u003e\", disable_ssl=True)\n\n# Get the list of all the metrics that the Prometheus host scrapes\nprom.all_metrics()\n```\n\nYou can also fetch the time series data for a specific metric using custom queries as follows:\n\n```python\nprom = PrometheusConnect()\nmy_label_config = {'cluster': 'my_cluster_id', 'label_2': 'label_2_value'}\nprom.get_current_metric_value(metric_name='up', label_config=my_label_config)\n\n# Here, we are fetching the values of a particular metric name\nprom.custom_query(query=\"prometheus_http_requests_total\")\n\n# Now, lets try to fetch the `sum` of the metrics\nprom.custom_query(query=\"sum(prometheus_http_requests_total)\")\n```\n\nWe can also use custom queries for fetching the metric data in a specific time interval. For example, let's try to fetch the past 2 days of data for a particular metric in chunks of 1 day:\n\n```python\n# Import the required datetime functions\nfrom prometheus_api_client.utils import parse_datetime\nfrom datetime import timedelta\n\nstart_time = parse_datetime(\"2d\")\nend_time = parse_datetime(\"now\")\nchunk_size = timedelta(days=1)\n\nmetric_data = prom.get_metric_range_data(\n    \"up{cluster='my_cluster_id'}\",  # this is the metric name and label config\n    start_time=start_time,\n    end_time=end_time,\n    chunk_size=chunk_size,\n)\n```\n\nFor more functions included in the `PrometheusConnect` module, refer to this [documentation.](https://prometheus-api-client-python.readthedocs.io/en/master/source/prometheus_api_client.html#module-prometheus_api_client.prometheus_connect)\n\n#### Understanding the Metrics Data Fetched\nThe `MetricsList` module initializes a list of Metric objects for the metrics fetched from a Prometheus host as a result of a promql query.\n\n```python\n# Import the MetricsList and Metric modules\nfrom prometheus_api_client import PrometheusConnect, MetricsList, Metric\n\nprom = PrometheusConnect()\nmy_label_config = {'cluster': 'my_cluster_id', 'label_2': 'label_2_value'}\nmetric_data = prom.get_metric_range_data(metric_name='up', label_config=my_label_config)\n\nmetric_object_list = MetricsList(metric_data) # metric_object_list will be initialized as\n                                              # a list of Metric objects for all the\n                                              # metrics downloaded using get_metric query\n\n# We can see what each of the metric objects look like\nfor item in metric_object_list:\n    print(item.metric_name, item.label_config, \"\\n\")\n```\n\nEach of the items in the `metric_object_list` are initialized as a `Metric` class object. Let's look at one of the metrics from the `metric_object_list` to learn more about the `Metric` class:\n\n```python\nmy_metric_object = metric_object_list[1] # one of the metrics from the list\nprint(my_metric_object)\n```\n\nFor more functions included in the `MetricsList` and `Metrics` module, refer to this [documentation.](https://prometheus-api-client-python.readthedocs.io/en/master/source/prometheus_api_client.html#module-prometheus_api_client.metric)\n\n#### Additional Metric Functions\nThe `Metric` class also supports multiple functions such as adding, equating and plotting various metric objects.\n\n##### Adding Metrics\nYou can add add two metric objects for the same time-series as follows:\n\n```python\nmetric_1 = Metric(metric_data_1)\nmetric_2 = Metric(metric_data_2)\nmetric_12 = metric_1 + metric_2 # will add the data in ``metric_2`` to ``metric_1``\n                                # so if any other parameters are set in ``metric_1``\n                                # will also be set in ``metric_12``\n                                # (like ``oldest_data_datetime``)\n```\n\n##### Equating Metrics\nOverloading operator =, to check whether two metrics are the same (are the same time-series regardless of their data)\n```python\nmetric_1 = Metric(metric_data_1)\nmetric_2 = Metric(metric_data_2)\nprint(metric_1 == metric_2) # will print True if they belong to the same time-series\n```\n\n##### Plotting Metric Objects\nPlot a very simple line graph for the metric time series:\n\n```python\nfrom prometheus_api_client import PrometheusConnect, MetricsList, Metric\n\nprom = PrometheusConnect()\nmy_label_config = {'cluster': 'my_cluster_id', 'label_2': 'label_2_value'}\nmetric_data = prom.get_metric_range_data(metric_name='up', label_config=my_label_config)\n\nmetric_object_list = MetricsList(metric_data)\nmy_metric_object = metric_object_list[1] # one of the metrics from the list\nmy_metric_object.plot()\n```\n\n#### Getting Metrics Data as pandas DataFrames\nTo perform data analysis and manipulation, it is often helpful to have the data represented using a [pandas DataFrame](https://pandas.pydata.org/docs/user_guide/dsintro.html#dataframe). There are two modules in this library that can be used to process the raw metrics fetched into a DataFrame.\n\nThe `MetricSnapshotDataFrame` module converts \"current metric value\" data to a DataFrame representation, and the `MetricRangeDataFrame` converts \"metric range values\" data to a DataFrame representation. Example usage of these classes can be seen below:\n\n```python\nimport datetime as dt\nfrom prometheus_api_client import PrometheusConnect,  MetricSnapshotDataFrame, MetricRangeDataFrame\n\nprom = PrometheusConnect()\nmy_label_config = {'cluster': 'my_cluster_id', 'label_2': 'label_2_value'}\n\n# metric current values\nmetric_data = prom.get_current_metric_value(\n    metric_name='up',\n    label_config=my_label_config,\n)\nmetric_df = MetricSnapshotDataFrame(metric_data)\nmetric_df.head()\n\"\"\" Output:\n+-------------------------+-----------------+------------+-------+\n| __name__ | cluster      | label_2         | timestamp  | value |\n+==========+==============+=================+============+=======+\n| up       | cluster_id_0 | label_2_value_2 | 1577836800 | 0     |\n+-------------------------+-----------------+------------+-------+\n| up       | cluster_id_1 | label_2_value_3 | 1577836800 | 1     |\n+-------------------------+-----------------+------------+-------+\n\"\"\"\n\n# metric values for a range of timestamps\nmetric_data = prom.get_metric_range_data(\n    metric_name='up',\n    label_config=my_label_config,\n    start_time=(dt.datetime.now() - dt.timedelta(minutes=30)),\n    end_time=dt.datetime.now(),\n)\nmetric_df = MetricRangeDataFrame(metric_data)\nmetric_df.head()\n\"\"\" Output:\n+------------+------------+-----------------+--------------------+-------+\n|            |  __name__  | cluster         | label_2            | value |\n+-------------------------+-----------------+--------------------+-------+\n| timestamp  |            |                 |                    |       |\n+============+============+=================+====================+=======+\n| 1577836800 | up         | cluster_id_0    | label_2_value_2    | 0     |\n+-------------------------+-----------------+--------------------+-------+\n| 1577836801 | up         | cluster_id_1    | label_2_value_3    | 1     |\n+-------------------------+-----------------+------------=-------+-------+\n\"\"\"\n```\n\n\nFor more functions included in the `prometheus-api-client` library, please refer to this [documentation.](https://prometheus-api-client-python.readthedocs.io/en/master/source/prometheus_api_client.html)\n\n## Running tests\n\n`PROM_URL=\"https://demo.promlabs.com/\" pytest`\n\n## Code Styling and Linting\n\nPrometheus Api client uses [pre-commit](https://pre-commit.com) framework to maintain the code linting and python code styling.\u003cbr\u003e\nThe AICoE-CI would run the pre-commit check on each pull request.\u003cbr\u003e\nWe encourage our contributors to follow the same pattern, while contributing to the code.\u003cbr\u003e\nwe would like to keep the same standard and maintain the code for better quality and readability.\n\nThe pre-commit configuration file is present in the repository `.pre-commit-config.yaml`\u003cbr\u003e\nIt contains the different code styling and linting guide which we use for the application.\n\nwe just need to run [pre-commit](https://pre-commit.com/#install) before raising a Pull Request.\u003cbr\u003e\nFollowing command can be used to run the pre-commit:\u003cbr\u003e\n`pre-commit run --all-files`\n\nIf pre-commit is not installed in your system, it can be install with : `pip install pre-commit`\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F4n4nd%2Fprometheus-api-client-python","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F4n4nd%2Fprometheus-api-client-python","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F4n4nd%2Fprometheus-api-client-python/lists"}