0
0
Flaskframework~5 mins

Health check endpoints in Flask

Choose your learning style9 modes available
Introduction

Health check endpoints help you quickly see if your web app is running well. They tell you if the app is alive and ready to serve users.

You want to monitor if your Flask app is up and running.
You need to let a load balancer know if your app can handle traffic.
You want to check if your app's dependencies like databases are working.
You want a simple URL to test your app's status during deployment.
Syntax
Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/health')
def health_check():
    return jsonify({'status': 'ok'})

The @app.route decorator creates the health check URL.

The function returns a JSON response with a simple status message.

Examples
Basic health check returning a simple 'ok' status.
Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/health')
def health_check():
    return jsonify({'status': 'ok'})
Health check that also verifies database connection and returns 500 error if down.
Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/health')
def health_check():
    # Check database connection here
    db_ok = True
    if db_ok:
        return jsonify({'status': 'ok', 'db': 'connected'})
    else:
        return jsonify({'status': 'error', 'db': 'disconnected'}), 500
Sample Program

This Flask app has a health check endpoint at '/health'. When you visit this URL, it returns JSON showing the app is 'ok'.

Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/health')
def health_check():
    # Simulate checking app status
    app_status = 'ok'
    return jsonify({'status': app_status})

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Keep health check endpoints simple and fast to respond.

Use HTTP status codes: 200 for healthy, 500 for problems.

Do not expose sensitive info in health check responses.

Summary

Health check endpoints show if your app is running well.

They are simple URLs returning JSON status messages.

Use them to help monitor and manage your Flask app.