The code looks true, However,the query in your response command is wrong . the true formate is :

response =requests.get(PROMETHEUS + '/api/v1/query', params={'query': 'container_cpu_user_seconds_total'}) 

you can change "container_cpu_user_seconds_total" to any query that you want to read. .. good luck

Answer from MOBT on Stack Overflow
๐ŸŒ
Medium
medium.com โ€บ @letathenasleep โ€บ exposing-python-metrics-with-prometheus-c5c837c21e4d
Exposing Python Metrics with Prometheus | by Adso | Medium | Medium
July 6, 2023 - Once the containers are running, you can access the API at http://localhost:5000 and the Prometheus dashboard at http://localhost:9090. The /metrics endpoint of the API will expose the metrics that Prometheus can scrape.
Discussions

python - Expose package metrics to Prometheus with prometheus_client - Stack Overflow
Expose the metrics from your client using an HTTP server|endpoint ยท Configure the Prometheus server to target this metric server|endpoint ยท If you run the Three Step Demo example on the page that you reference, and then browse http://localhost:8000, you should see something like: # HELP python_g... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python , how to import prometheus endpoint metrics for processing by another system
Hopefully someone has already done this as I can't much in the way of examples or information. I just want to validate I am on the right track andโ€ฆ More on reddit.com
๐ŸŒ r/PrometheusMonitoring
1
0
September 12, 2020
Get data from influxdb to my Prometheus
Influxdb is generally used as storage solution for Prometheus. Prometheus can save it's data in Influxdb and is probably the better option than saving it in Prometheus itself / on disk. Is there a specific reason why you'd want it in both? More on reddit.com
๐ŸŒ r/PrometheusMonitoring
5
2
May 15, 2024
Avoid reading zero values after a restart
There's no way to make Prometheus wait. Even if you could, if 0 is a valid value as you say then how would Prometheus know if a 0 reading was a "real" one or not? You should ideally handle this in your system being scraped, either by having it set the gauge on startup or by having it retrieve the current value in real-time whenever it is scraped. If for whatever reason neither of those is possible then you should avoid using 0 as the default value if it can also be a "real" value. Use NaN, -1, or something else that's more explicitly invalid, then set your rules up accordingly. More on reddit.com
๐ŸŒ r/PrometheusMonitoring
9
0
February 4, 2022
๐ŸŒ
Better Stack
betterstack.com โ€บ community โ€บ guides โ€บ monitoring โ€บ prometheus-python-metrics
Python Monitoring with Prometheus (Beginner's Guide) | Better Stack Community
February 17, 2025 - Once you've saved the file, visit http://localhost:8000/metrics in your browser or use curl to see the default Prometheus metrics: ... By default, Prometheus uses a global registry that automatically includes standard Python runtime and ...
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ prometheus-api-client
prometheus-api-client ยท PyPI
A Python wrapper for the Prometheus http api and some tools for metrics processing. ... Note: Starting from version 0.7.0, pandas, numpy, and matplotlib are optional dependencies.
      ยป pip install prometheus-api-client
    
Published: Apr 13, 2026
Version: 0.7.2
๐ŸŒ
Readthedocs
prometheus-api-client-python.readthedocs.io โ€บ en โ€บ latest โ€บ source โ€บ prometheus_api_client.html
prometheus_api_client package โ€” Prometheus Client API Python 0.0.1 documentation
(RequestException) Raises an exception in case of a connection error (PrometheusApiClientException) Raises in case of non 200 response status code ยท get_metric_aggregation(query: str, operations: list, start_time: datetime = None, end_time: datetime = None, step: str = '15', params: dict = None)[source]๏ƒ ยท Get aggregations on metric values received from PromQL query.
๐ŸŒ
Linux Hint
linuxhint.com โ€บ monitor-python-applications-prometheus
Monitoring Python Applications using Prometheus โ€“ Linux Hint
To access the Prometheus metrics, visit the URL http://192.168.20.131:8000/metrics from your favorite web browser. Now, you have to add your Python app to Prometheus.
๐ŸŒ
Sam Malekpour
s4m.ca โ€บ blog โ€บ decoding-observability-extracting-and-processing-prometheus-metrics-with-python
Decoding Observability: Extracting and Processing Prometheus Metrics with Python - Sam Malekpour
October 9, 2025 - Get metrics data from Prometheus API prometheus_data = query_prometheus_range( PROMETHEUS_QUERY, start_api, end_api, step ) # 2.
Find elsewhere
๐ŸŒ
CloudBees
cloudbees.com โ€บ blog โ€บ monitoring-your-synchronous-python-web-applications-using-prometheus
Monitoring Your Synchronous Python Web Applications Using Prometheus
June 5, 2026 - The Prometheus monitoring system differs from most other similar software in at least one way. Instead of the application pushing metrics to the monitoring system, Prometheus scrapes the application via HTTP usually on the /metrics/ endpoint.
๐ŸŒ
DBI Services
dbi-services.com โ€บ accueil โ€บ instrument your python application with prometheus (part1)
Instrument your python application with Prometheus (Part1)
July 10, 2023 - Then, in our code, we will define a variable called REQUESTS to initialize the Counter object by providing the metric name (http_request_total) and its description (Total number of requests). REQUESTS = Counter('http_request_total', 'Total number of requests') ... from flask import Flask, jsonify, request, render_template, redirect, url_for from prometheus_client import Counter REQUESTS = Counter('http_request_total', 'Total number of requests') app = Flask(__name__) (...)
๐ŸŒ
Medium
ledinhcuong99.medium.com โ€บ prometheus-api-client-in-python-ec54291aa1a
Prometheus API Client in Python - Donald Le - Medium
January 19, 2021 - def print_metrics(): from prometheus_api_client import PrometheusConnect prom = PrometheusConnect(url="http://3.19.55.237:9090", disable_ssl=True) # Get the list of all the metrics that the Prometheus host scrapes print(prom.all_metrics()) # ...
๐ŸŒ
Blog
asserts.ai โ€บ home โ€บ monitoring python using prometheus
Monitoring Python Using Prometheus - Asserts
June 20, 2023 - Prometheus is the ideal way to capture and store these metrics along with additional Python runtime metrics. To collect metrics for each endpoint and the Python runtime requires just a few simple modifications. from prometheus_flask_exporter import PrometheusMetrics def path(req): return '/' + req.path[1:].split('/')[0] app = Flask('my-app') metrics = PrometheusMetrics(app, group_by=path)
๐ŸŒ
GitHub
github.com โ€บ eminaktas โ€บ get-of-metrics
GitHub - eminaktas/get-of-metrics: Get of Metrics for Prometheus, Node Exporter and Grafana
get-of-metrics is a Python script for dealing the Broadcom switch metrics to extract from commandline, parse the metrics and expose them to be processed by Prometheus and Grafana.
Author: eminaktas
๐ŸŒ
MetricFire
metricfire.com โ€บ blog โ€บ how-to-monitor-python-applications-with-prometheus
How to monitor Python Applications with Prometheus | MetricFire
September 15, 2023 - This method rejects the concept that Prometheus must scrape our application directly. Instead, export metrics from your app to a locally running StatsD instance, and set up Prometheus to scrape the StatsD instance instead of the application.
๐ŸŒ
Pluralsight
pluralsight.com โ€บ cloud-guru โ€บ labs โ€บ aws โ€บ using-python-to-extract-prometheus-metrics
Using Python to Extract Prometheus Metrics
April 5, 2019 - The program will use PromQL examples to pull CPU and memory metrics and output them in a Comma Separated Value (CSV) file that may then be used for a Machine Learning program. This lab only covers the extract step and the Machine Learning part ...
๐ŸŒ
Medium
observabilityfeed.medium.com โ€บ sending-custom-metrics-from-python-app-to-prometheus-722211bedfe9
Sending Custom Metrics from Python to Prometheus | by K Shekar | Medium
October 31, 2023 - With the HTTP server running and metrics exposed, you can access your metrics by visiting http://localhost:8000/metrics in a web browser or using the Prometheus server to scrape and store the metrics for monitoring.
Top answer
1 of 1
7

Prometheus server scrapes HTTP endpoints that provide metrics. This differs from some other metric systems where the metrics are pushed to the metric system. Because Prometheus scrapes metric endpoints, you need to do two things:

  1. Expose the metrics from your client using an HTTP server|endpoint
  2. Configure the Prometheus server to target this metric server|endpoint

If you run the Three Step Demo example on the page that you reference, and then browse http://localhost:8000, you should see something like:

# HELP python_gc_objects_collected_total Objects collected during gc
# TYPE python_gc_objects_collected_total counter
python_gc_objects_collected_total{generation="0"} 357.0
python_gc_objects_collected_total{generation="1"} 0.0
python_gc_objects_collected_total{generation="2"} 0.0
...
...
# HELP request_processing_seconds Time spent processing request
# TYPE request_processing_seconds summary
request_processing_seconds_count 4.0
request_processing_seconds_sum 2.0374009040533565
# HELP request_processing_seconds_created Time spent processing request
# TYPE request_processing_seconds_created gauge
request_processing_seconds_created 1.6004497426536365e+09

This is the page that your Prometheus server would be configured to scrape. You can see, e.g. python_gc_objects_collected_total counter is provided. Prometheus metrics are human readable which is useful.

If you combine, your sandbox1.py into this example:

from prometheus_client import start_http_server, Counter, Summary
import random
import time

# Create a metric to track time spent and requests made.
REQUEST_TIME = Summary('request_processing_seconds',
                       'Time spent processing request')


# Decorate function with metric.
@REQUEST_TIME.time()
def process_request(t):
    """A dummy function that takes some time."""
    time.sleep(t)


if __name__ == '__main__':
    my_counter1 = Counter('my_counter1', 'My counter')
    # Start up the server to expose the metrics.
    start_http_server(8000)
    # Generate some requests.
    while True:
        my_counter1.inc()
        process_request(random.random())

And run the code again, you should now see:

# HELP python_gc_objects_collected_total Objects collected during gc
# TYPE python_gc_objects_collected_total counter
python_gc_objects_collected_total{generation="0"} 357.0
python_gc_objects_collected_total{generation="1"} 0.0
python_gc_objects_collected_total{generation="2"} 0.0
...
...
# HELP my_counter1_total My counter
# TYPE my_counter1_total counter
my_counter1_total 13.0
# HELP my_counter1_created My counter
# TYPE my_counter1_created gauge
my_counter1_created 1.6004498408280134e+09

NOTE At the bottom of the page is my_counter1_total and my_counter1_created which correspond to your my_counter1 = Counter("my_counter1","My counter")

If you point a Prometheus server at this target (localhost:8000), you should be able to e.g. graph the my_counter1_total counter and the my_counter1_created gauge.

Create a file called prometheus.yml:

global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  # Self
  - job_name: "prometheus-server"
    static_configs:
      - targets:
          - "localhost:9090"

  # Python example
  - job_name: "63957470"
    static_configs:
      - targets:
          - "localhost:8000"

And then run Prometheus:

docker run \
--interactive --tty \
--net=host \
--volume=${PWD}/prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheus@sha256:f3ada803723ccbc443ebea19f7ab24d3323def496e222134bf9ed54ae5b787bd

NOTE This assumes that prometheus.yml is in the working directory

The, you can browse Prometheus on http://localhost:9090

You can see your code configured as a target: http://localhost:9090/targets

And you can query|graph your metrics. Type e.g. my_counter1_ to see both and then my_counter1_total for the Counter:

๐ŸŒ
Robust Perception
robustperception.io โ€บ productive-prometheus-python-parsing
Productive Prometheus Python Parsing โ€“ Robust Perception | Prometheus Monitoring Experts
May 8, 2017 - First install the python client and requests, if you don't already have them: $ pip install prometheus_client requests ยท Then we can fetch the data we need, and print it: from prometheus_client.parser import text_string_to_metric_families import requests metrics = requests.get("http://dem...
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ prometheus-client โ€บ 0.14.1
prometheus-client ยท PyPI
The official Python client for Prometheus. ... from prometheus_client import start_http_server, Summary import random import time # Create a metric to track time spent and requests made.
๐ŸŒ
Prometheus
prometheus.io โ€บ docs โ€บ instrumenting โ€บ clientlibs
Client libraries | Prometheus
When Prometheus scrapes your instance's HTTP endpoint, the client library sends the current state of all tracked metrics to the server.