5 min read

Prometheus in Practice - Scraping, the /metrics Endpoint and a Mini Python App Exposing Metrics

1. Recap: From an Empty Stack to the First Data Source

In the first article of this series, we brought up Prometheus, Loki and Grafana with Docker Compose, but with no real application sending data — Prometheus only monitored itself. This article fixes that: we’ll understand how Prometheus actually collects metrics from an application (scraping) and build a mini application in plain Python, with no framework at all, that exposes metrics in that format.

2. Pull vs Push: Prometheus’ Scraping Model

There are two ways for a metrics tool to get data from an application:

  • Push — the application actively sends values to a central server whenever it wants (or at intervals it defines itself). StatsD works this way.
  • Pull (scraping) — the application just exposes its current values on an HTTP endpoint, and it’s the metrics server that periodically visits that endpoint and reads the current state. This is Prometheus’ model.

Prometheus chose pull deliberately, for a few practical reasons:

  • Centralized failure detection — if Prometheus can’t scrape a target, it already knows and records it (metric up == 0), without depending on the application noticing it stopped sending data.
  • Easy to test manually — since the endpoint is just HTTP, you can open /metrics in a browser or with curl and see exactly what will be collected, without simulating the Prometheus side.
  • Central control of the collection interval — whoever consumes the data (Prometheus) decides the frequency, not each application individually.

The exception is short-lived jobs (a batch script that runs and finishes in seconds, without staying up to be scraped) — for those cases there’s the Pushgateway, an auxiliary component that accepts pushes and is exposed for Prometheus to pull from. For long-lived applications like the ones in this series (HTTP servers), the default pull model is enough.

3. The Exposition Format: What Lives at /metrics

A Prometheus /metrics endpoint is simply plain text, in a specific format called the exposition format. Each metric follows this structure:

# HELP app_requests_total Total requests received
# TYPE app_requests_total counter
app_requests_total 42
  • The # HELP line is a human-readable description (optional, but good practice).
  • The # TYPE line declares the metric type — counter, gauge, histogram or summary (article 3 of this series details each type).
  • The data line is metric_name{optional_labels="value"} value.

No library is strictly needed to generate this text — it’s just string formatting. This makes the format easy to implement in any language, even without an official client, which is exactly what this mini application will do.

4. A Mini App in Plain Python with http.server

Using only Python’s standard library (the http.server module, no Flask, Django or any other framework), a minimal application that counts requests and exposes that count at /metrics:

# app.py
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

start_time = time.time()
request_count = 0


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        global request_count

        if self.path == "/metrics":
            uptime = time.time() - start_time
            body = (
                "# HELP app_requests_total Total requests received\n"
                "# TYPE app_requests_total counter\n"
                f"app_requests_total {request_count}\n"
                "# HELP app_uptime_seconds Time since the process started\n"
                "# TYPE app_uptime_seconds gauge\n"
                f"app_uptime_seconds {uptime:.2f}\n"
            )
            self.send_response(200)
            self.send_header("Content-Type", "text/plain; version=0.0.4")
            self.end_headers()
            self.wfile.write(body.encode("utf-8"))
            return

        request_count += 1
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()
        self.wfile.write(b"hello from the python app\n")

    def log_message(self, format, *args):
        pass  # silence http.server's default log on stdout


if __name__ == "__main__":
    server = ThreadingHTTPServer(("0.0.0.0", 8000), Handler)
    print("app running at http://0.0.0.0:8000")
    server.serve_forever()

Running it locally:

python3 app.py

Every request to any path other than /metrics increments the app_requests_total counter — note that the request to /metrics itself does not count as a business request, on purpose, so it doesn’t skew the metric. Testing:

curl http://localhost:8000/
curl http://localhost:8000/
curl http://localhost:8000/metrics

The last call should show app_requests_total 2.

5. Configuring prometheus.yml to Collect the New App

With the endpoint working, the next step is to add a job to the previous article’s prometheus.yml, pointing at this application:

# prometheus.yml
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: "prometheus"
    static_configs:
      - targets: ["localhost:9090"]

  - job_name: "python-app"
    static_configs:
      - targets: ["python-app:8000"]

And add the application to docker-compose.yml, on the same network as the other services (that’s why the python-app hostname works in the target above — it’s the service name in Compose):

# docker-compose.yml (excerpt added to the previous article's file)
services:
  python-app:
    image: python:3.12-slim
    working_dir: /app
    volumes:
      - ./app.py:/app/app.py:ro
    command: ["python3", "app.py"]
    ports:
      - "8000:8000"

After docker compose up -d, Prometheus starts scraping the application every 15 seconds (the global scrape_interval). To confirm the target is healthy, the python-app job should show up with state UP at http://localhost:9090/targets.

6. Querying the Data in Prometheus

After a few minutes of collection (generating traffic manually with curl in a loop, if needed), you can already query in Prometheus’ expression field (http://localhost:9090/graph):

# raw counter value, accumulated since the process started
app_requests_total

# requests per second, calculated over a 1-minute window
rate(app_requests_total[1m])

rate() is the most used function on counters in PromQL: since a counter only goes up (and resets if the process restarts), the raw value doesn’t say much on its own — what matters is the speed at which it grows, which is exactly what rate() calculates, correctly handling counter resets along the way.

7. Conclusion and Next Steps

We saw why Prometheus chooses pull over push, how the exposition format at /metrics is just plain text — implementable without any library —, built a mini Python application that exposes a real metric, and configured Prometheus to collect it periodically. In the next article, the mini application is written in plain PHP, and the focus moves to the three metric types — counters, gauges and histograms — applied to business metrics, not just request counts.


References:

  1. Prometheus — Exposition Formats
  2. Prometheus — Configuration
  3. Prometheus — Querying Basics
  4. Python Docs — http.server