blog

Creating a Simple Python Health Check Endpoint: A Step-by-Step Guide

In the realm of modern application development, ensuring reliability and availability is of paramount importance. One effective way to achieve this is by implementing a health check endpoint in your application. This article will guide you through the process of creating a simple Python health check endpoint, covering essential concepts along the way, including enterprise secure AI usage, IBM API Connect, and different authentication methods like Basic Auth, AKSK, and JWT.

What is a Health Check Endpoint?

A health check endpoint is a specific URL route in your web application that can be called to determine the operational status of your application. It provides a way for monitoring systems to check the health of your application by returning a simple response indicating if the application is up and running.

Why Are Health Check Endpoints Important?

Health check endpoints are crucial for several reasons:

  1. Reliability: They allow for automated monitoring of application status, ensuring that any downtime is detected and reported immediately.

  2. Scalability: When applications scale, having dedicated health checks ensures that load balancers and orchestrators can route traffic to healthy instances only.

  3. Integration: These endpoints can be integrated with various monitoring tools, allowing teams to visualize the health status of applications easily.

Overview of the Technologies We Will Use

Before diving into implementation, let’s overview the technologies and concepts we’ll use throughout this guide:

  • Python: The programming language used to create our health check endpoint.
  • Flask: A lightweight WSGI web application framework in Python.
  • IBM API Connect: A platform for creating, managing, and securing APIs.
  • Authentication Methods:
  • Basic Auth: Simple authentication method built into HTTP.
  • AKSK: Access Key and Secret Key mechanism for securing API calls.
  • JWT: JSON Web Tokens used for stateless authentication.

Setting Up Your Python Environment

To create our health check endpoint, we will use Flask. First, ensure you have Python installed on your machine. You can download it from the official Python website.

Once installed, you can set up a virtual environment and install Flask using the following commands:

# Create a virtual environment
python -m venv myenv
# Activate the virtual environment
# On Windows
myenv\Scripts\activate
# On Unix or MacOS
source myenv/bin/activate

# Install Flask
pip install Flask

Creating the Health Check Endpoint

Now, let’s write a simple Flask application. Create a file named app.py and add the following code:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/health', methods=['GET'])
def health_check():
    """Health Check Endpoint"""
    return jsonify({'status': 'healthy'}), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

In this script, we define a single route /health, which returns a JSON response indicating that the application is healthy. The jsonify function converts the dictionary into a JSON response.

Running the Application

You can run the application using the command:

python app.py

Open your web browser or a tool like Postman to test the endpoint at http://localhost:5000/health. You should receive a response like:

{
    "status": "healthy"
}

Introducing Authentication Mechanisms

For applications in production, it is vital to secure your health check endpoint. Here, we will discuss the methods of authentication: Basic Auth, AKSK, and JWT.

1. Basic Authentication

To secure the health check endpoint with Basic Auth, we can use Flask’s built-in capabilities. This method sends the username and password as part of the HTTP headers.

Here’s how to implement Basic Auth:

from flask import Flask, jsonify, request, Response

app = Flask(__name__)

# User credentials
USERNAME = 'admin'
PASSWORD = 'secret'

def check_auth(username, password):
    """Check if a username/password combination is valid."""
    return username == USERNAME and password == PASSWORD

def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})

@app.route('/health', methods=['GET'])
def health_check():
    """Health Check Endpoint with Basic Auth"""
    auth = request.authorization
    if not auth or not check_auth(auth.username, auth.password):
        return authenticate()

    return jsonify({'status': 'healthy'}), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Now the endpoint will require Basic Auth credentials. When trying to access the /health endpoint without proper authentication, you will receive a 401 Unauthorized response.

APIPark is a high-performance AI gateway that allows you to securely access the most comprehensive LLM APIs globally on the APIPark platform, including OpenAI, Anthropic, Mistral, Llama2, Google Gemini, and more.Try APIPark now! 👇👇👇

2. AKSK Authentication

AKSK (Access Key & Secret Key) authentication is ideal for enterprises as it provides a straightforward way to authenticate API requests. This requires generating an access key and a secret key and verifying them within the application.

Here is a simple implementation:

from flask import Flask, jsonify, request

app = Flask(__name__)

# Predefined access and secret keys for demonstration
ACCESS_KEY = 'my_access_key'
SECRET_KEY = 'my_secret_key'

@app.route('/health', methods=['GET'])
def health_check():
    """Health Check Endpoint with AKSK"""
    access_key = request.headers.get('X-Access-Key')
    secret_key = request.headers.get('X-Secret-Key')

    if access_key != ACCESS_KEY or secret_key != SECRET_KEY:
        return jsonify({'message': 'Unauthorized'}), 401

    return jsonify({'status': 'healthy'}), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

With this implementation, you’ll need to include the X-Access-Key and X-Secret-Key in your HTTP headers when you send a request to the /health endpoint.

3. JWT Authentication

JWT (JSON Web Token) is a popular method for securing API endpoints. It involves issuing a token which then gets validated on each request. Below is how to implement JWT authentication:

First, you need to install the pyjwt library:

pip install PyJWT

Then modify your app.py:

import jwt
import datetime
from flask import Flask, jsonify, request

app = Flask(__name__)

# Secret key for encoding and decoding JWTs
SECRET_KEY = 'your_secret_key_here'

def token_required(f):
    def decorated(*args, **kwargs):
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({'message': 'Token is missing!'}), 403

        try:
            data = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
        except:
            return jsonify({'message': 'Token is invalid!'}), 403

        return f(*args, **kwargs)
    return decorated

@app.route('/health', methods=['GET'])
@token_required
def health_check():
    """Health Check Endpoint with JWT Authentication"""
    return jsonify({'status': 'healthy'}), 200

@app.route('/token', methods=['POST'])
def create_token():
    """Endpoint to create a new JWT token"""
    token = jwt.encode({'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, SECRET_KEY, algorithm="HS256")
    return jsonify({'token': token})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

In this implementation, you can generate a token by making a POST request to the /token endpoint. The health check endpoint now uses a decorator called token_required that ensures only requests with a valid token can access it.

Comparison of Authentication Methods

Here’s a quick comparison in a table format to better illustrate the differences between Basic Auth, AKSK, and JWT:

Authentication Method Pros Cons
Basic Auth Simple to implement, widely supported Less secure, credentials sent with each request in plain text.
AKSK Easy to use, no need for sessions Can be exposed without HTTPS, limited by key rotation policies.
JWT Stateless, secure, can carry user info Slightly complex to implement, token management needed.

Deploying Your Application

Once your application is complete, the next step is deployment. You can host your application on various platforms, such as Heroku, AWS, or even using a simple VPS. If you’re using IBM API Connect, you can integrate this endpoint seamlessly into your API management practices.

Securing Your Application

When deploying, ensure that you run your application over HTTPS to secure data transmission. Also, consider using a proper WAF (Web Application Firewall) for enhanced security, especially when dealing with sensitive data.

Conclusion

In this tutorial, we have crafted a simple health check endpoint in Python using Flask, defined various authentication mechanisms (Basic Auth, AKSK, JWT), and discussed best practices around deployment and security. Implementing a health check endpoint is a straightforward yet effective way to enhance the reliability of your applications.

By ensuring proper usage of enterprise secure AI solutions, and effectively managing APIs through IBM API Connect, organizations can maintain robust applications ready to meet growing demands.

Make sure to test your endpoint thoroughly in a simulated production environment before deploying it live, and continue to monitor its performance.

Additional Resources

For further reading, consider checking out:

With the knowledge gained from this guide, you’re now equipped to implement health check endpoints in your applications securely. Happy coding!

🚀You can securely and efficiently call the Claude(anthropic) API on APIPark in just two steps:

Step 1: Deploy the APIPark AI gateway in 5 minutes.

APIPark is developed based on Golang, offering strong product performance and low development and maintenance costs. You can deploy APIPark with a single command line.

curl -sSO https://download.apipark.com/install/quick-start.sh; bash quick-start.sh

APIPark Command Installation Process

In my experience, you can see the successful deployment interface within 5 to 10 minutes. Then, you can log in to APIPark using your account.

APIPark System Interface 01

Step 2: Call the Claude(anthropic) API.

APIPark System Interface 02