Health Endpoint
A health endpoint refers to a specific endpoint or route provided by the server that is used to determine the health or status of the server or application. This endpoint is typically used for monitoring and management purposes, allowing external systems or monitoring tools to check whether the API server is functioning properly.
Modify main.py:
from flask import Flask, jsonify
app = Flask(__name__)
# Define a health endpoint handler, use `/health` or `/`
@app.route('/')
def health():
# Return a simple response indicating the server is healthy
return jsonify({"status": "ok"})
Start the server:
flask --app main run --debug
The response of endpoint /
:
{
"status": "ok"
}
Optional:
If you want to include CPU or memory data in the health endpoint response, you would need to gather this information from the system where your Python application is running.
Modify main.py [optional]:
@@ -1,10 +1,27 @@
from flask import Flask, jsonify
+import psutil
app = Flask(__name__)
# Define a health endpoint handler, use `/health` or `/`
@app.route('/')
def health():
- # Return a simple response indicating the server is healthy
- return jsonify({"status": "ok"})
+ # Get CPU usage
+ cpu_percent = psutil.cpu_percent()
+ # Get memory usage
+ mem = psutil.virtual_memory()
+ mem_total = mem.total
+ mem_used = mem.used
+ mem_percent = mem.percent
+
+ # Return a simple response indicating the server is healthy
+ return jsonify({
+ "status": "ok",
+ "cpu_usage_percent": cpu_percent,
+ "memory_usage": {
+ "total": mem_total,
+ "used": mem_used,
+ "percent": mem_percent
+ }
+ })
Install psutil
, [optional]:
pip3 install psutil
The response is something like this:
{
"cpu_usage_percent": 4.3,
"memory_usage": {
"percent": 58.8,
"total": 17179869184,
"used": 9561190400
},
"status": "ok"
}