Bird
Raised Fist0
Flaskframework~10 mins

Health check endpoints in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Health check endpoints
Start Flask App
↓
Receive HTTP GET /health
↓
Run health check function
↓
Check system status
↓
If OK
↓
If NOT OK
↓
Send HTTP response
↓
End request
The app listens for a GET request on /health, runs checks, then returns a status response.
Execution Sample
Flask
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/health')
def health_check():
    return jsonify({'status': 'ok'}), 200
Defines a simple health check endpoint that returns status 'ok' with HTTP 200.
Execution Table
StepActionInputCheck ResultResponse Sent
1App starts and listensN/AN/AN/A
2GET request received/healthN/AN/A
3Run health_check functionN/ASystem OKN/A
4Return JSON response{"status": "ok"}N/AHTTP 200 with JSON
5Request endsN/AN/AResponse delivered
💡 Request ends after sending HTTP 200 response with status 'ok'.
Variable Tracker
VariableStartAfter Request
appFlask instance createdListening for requests
health_check responseNone{"status": "ok"}, 200
Key Moments - 2 Insights
Why does the health check return a JSON response instead of plain text?
The execution_table row 4 shows the function returns jsonify({'status': 'ok'}), which formats the response as JSON for easy machine reading.
What happens if the system is not OK in the health check?
Though not shown in this simple example, row 3 explains the check result. If not OK, the function would return a 500 error instead of 200.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what response is sent at step 4?
AHTTP 500 Internal Server Error
BHTTP 200 with JSON {'status': 'ok'}
CHTTP 404 Not Found
DNo response sent
💡 Hint
Check the 'Response Sent' column in row 4 of the execution_table.
At which step does the app receive the GET request for /health?
AStep 2
BStep 1
CStep 3
DStep 5
💡 Hint
Look at the 'Action' and 'Input' columns in the execution_table.
If the health check function returned a 500 error, which step would change?
AStep 2 - GET request received
BStep 3 - Run health_check function
CStep 4 - Return JSON response
DStep 5 - Request ends
💡 Hint
Step 4 shows the response sent; changing status code affects this step.
Concept Snapshot
Health check endpoints in Flask:
- Use @app.route('/health') with GET method
- Define a function returning JSON status and HTTP code
- Return 200 OK if system is healthy
- Return 500 or error code if unhealthy
- Helps monitoring tools check app status easily
Full Transcript
This example shows how a Flask app creates a health check endpoint at /health. When a GET request arrives, the app runs a function that returns a JSON response with status 'ok' and HTTP 200. This lets monitoring systems know the app is running fine. The execution table traces each step from app start, request received, function run, response sent, to request end. Variables like the Flask app instance and response data change accordingly. Key moments clarify why JSON is used and what happens if the system is not OK. The quiz tests understanding of the response sent, request step, and how errors affect the flow.

Practice

(1/5)
1. What is the main purpose of a health check endpoint in a Flask application?
easy
A. To connect to the database and run queries
B. To handle user login and authentication
C. To confirm the app is running and responsive
D. To serve static files like images and CSS

Solution

  1. Step 1: Understand the role of health check endpoints

    Health check endpoints are simple URLs that return a status message indicating the app is running properly.
  2. Step 2: Compare options with this role

    Only To confirm the app is running and responsive matches this purpose. Other options describe unrelated app functions.
  3. Final Answer:

    To confirm the app is running and responsive -> Option C
  4. Quick Check:

    Health check = Confirm app running [OK]
Hint: Health check endpoints confirm app health quickly [OK]
Common Mistakes:
  • Confusing health check with user authentication
  • Thinking health check serves static files
  • Assuming health check runs database queries
2. Which of the following is the correct way to define a simple health check endpoint in Flask?
easy
A. app.route('/health') def health(): return {'status': 'ok'}
B. @app.route('/health') health = {'status': 'ok'}
C. app.route('/health') health = lambda: {'status': 'ok'}
D. @app.route('/health') def health(): return {'status': 'ok'}

Solution

  1. Step 1: Recall Flask route decorator syntax

    Flask uses @app.route('/path') decorator above a function to define routes.
  2. Step 2: Check each option for correct syntax

    @app.route('/health') def health(): return {'status': 'ok'} correctly uses @app.route decorator and defines a function returning a dictionary. Others miss the decorator or define incorrectly.
  3. Final Answer:

    @app.route('/health')\ndef health():\n return {'status': 'ok'} -> Option D
  4. Quick Check:

    Use @app.route decorator for routes [OK]
Hint: Use @ before app.route to define Flask routes [OK]
Common Mistakes:
  • Forgetting the @ symbol before app.route
  • Returning a dictionary without a function
  • Assigning route to a variable instead of a function
3. Given this Flask code, what will be the JSON response when accessing /health?
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/health')
def health():
    return jsonify(status='ok', uptime=12345)
medium
A. {"status": "ok", "uptime": 12345}
B. status=ok, uptime=12345
C. {"status": ok, "uptime": "12345"}
D. A runtime error occurs

Solution

  1. Step 1: Understand jsonify output

    The jsonify function converts keyword arguments into a JSON response with keys as strings and values as their types.
  2. Step 2: Check the returned JSON format

    It returns a JSON string with keys "status" and "uptime". The uptime is an integer, so no quotes around 12345.
  3. Final Answer:

    {"status": "ok", "uptime": 12345} -> Option A
  4. Quick Check:

    jsonify returns JSON string with keys and values [OK]
Hint: jsonify returns proper JSON with quotes on keys and string values [OK]
Common Mistakes:
  • Missing quotes around string values
  • Confusing Python dict print with JSON string
  • Expecting runtime error when code is correct
4. What is wrong with this Flask health check endpoint code?
from flask import Flask
app = Flask(__name__)

app.route('/health')
def health():
    return {'status': 'ok'}
medium
A. The route decorator is missing the @ symbol
B. It will cause a syntax error because return type is wrong
C. It returns a Python dict but Flask needs a Response or JSON
D. The function name 'health' is reserved and cannot be used

Solution

  1. Step 1: Recall Flask route decorator syntax

    Flask uses the @app.route('/path') decorator above the function definition. The @ symbol is required to apply the decorator.
  2. Step 2: Analyze the provided code

    The code has app.route('/health') without the @, so it calls the route method but does not decorate the health function. Thus, the /health endpoint will not be registered and accessing it returns 404.
  3. Final Answer:

    The route decorator is missing the @ symbol -> Option A
  4. Quick Check:

    Missing @ means no route registration [OK]
Hint: Use @ before app.route to define Flask routes [OK]
Common Mistakes:
  • Returning plain dict without jsonify
  • Forgetting @ before route decorator
  • Thinking function names are reserved keywords
5. You want to create a health check endpoint in Flask that returns status 'ok' only if the database connection is alive, otherwise 'error'. Which approach is best?
hard
A. Return {'status': 'ok'} always, ignoring database state
B. Check database connection inside the route, return JSON accordingly
C. Use a separate thread to update status and return cached result
D. Raise an exception if database is down and let Flask handle it

Solution

  1. Step 1: Understand health check purpose with dependencies

    A health check should verify critical dependencies like database connectivity to report accurate status.
  2. Step 2: Evaluate options for checking database state

    Check database connection inside the route, return JSON accordingly directly checks the database connection inside the route and returns JSON status accordingly, which is clear and reliable.
  3. Step 3: Consider other options

    Return {'status': 'ok'} always, ignoring database state ignores database state, C adds unnecessary complexity, D relies on exceptions which is less clear for health checks.
  4. Final Answer:

    Check database connection inside the route, return JSON accordingly -> Option B
  5. Quick Check:

    Health check should verify dependencies live [OK]
Hint: Check dependencies live inside health endpoint for accuracy [OK]
Common Mistakes:
  • Ignoring database state in health check
  • Overcomplicating with threads or caching
  • Relying on exceptions instead of status checks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard