Python (Flask / WSGI) Integration Guide

The @ztlayer/python SDK provides native bindings for standard WSGI applications, with a dedicated wrapper for Flask.

If you are using Django or FastAPI, please refer to their dedicated guides:


1. Installation

Install the Python SDK via pip or your preferred package manager (Poetry, Pipenv).

pip install ztlayer-python

2. Configuration & Initialization

Ensure your API key is available in your environment variables.

# .env
ZTLAYER_API_KEY="zt_live_xxxxxxxxxxxxxxxxxxxxxxxx"

3. Flask Integration (Recommended)

To protect a Flask application, you wrap your Flask app instance with the ZTLayerFlask extension. This registers a before_request hook globally.

import os
from flask import Flask, jsonify
from ztlayer.flask import ZTLayerFlask
 
app = Flask(__name__)
 
# 1. Initialize the security layer
# By default, it automatically picks up ZTLAYER_API_KEY from os.environ
security = ZTLayerFlask(
    app, 
    fail_mode="open", 
    timeout_ms=2000
)
 
# 2. Define your routes
@app.route("/api/data", methods=["GET"])
def get_data():
    return jsonify({"message": "This route is protected by ZTLayer."})
 
if __name__ == "__main__":
    app.run(port=5000)

Route-Specific Protection in Flask

If you do not want to protect the entire application globally, initialize ZTLayerFlask without passing the app instance, and use the @security.protect decorator on specific routes.

from flask import Flask, request
from ztlayer.flask import ZTLayerFlask
 
app = Flask(__name__)
security = ZTLayerFlask() # Do not pass app
 
@app.route("/api/auth/login", methods=["POST"])
@security.protect(strict=True) # Enforce behavioral analysis
def login():
    # Only executes if the request is safe
    return handle_login(request.json)
 
@app.route("/public/health")
def health():
    # Not inspected by ZTLayer
    return "OK"

4. Pure WSGI Integration

If you are not using a framework, or you are writing a custom WSGI server, you can use the raw ZTLayerWSGIMiddleware.

from ztlayer.wsgi import ZTLayerWSGIMiddleware
 
def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return [b"Hello World"]
 
# Wrap the WSGI app
secured_app = ZTLayerWSGIMiddleware(
    application, 
    api_key=os.environ.get("ZTLAYER_API_KEY"),
    fail_mode="open"
)

Next Steps