背景
使用Python的Flask包创建OpenAPI Schema服务,提供给Dify创建自定义工具使用。
使用Flask的原因是,国产系统,内网系统,共用系统。安装OpenSSL开发环境不方便,特别是内网和共用系统,有很大风险。
甚至弄坏其他项目。所以采用Flask。不依赖OpenSSL。
操作
dify成功配置如下:

代码如下:
python
from flask import Flask, jsonify, request
app = Flask(__name__)
# ------------------------------
# 1. OpenAPI 规范定义(给导入工具用的)
# ------------------------------
OPENAPI_SCHEMA = {
"openapi": "3.0.0",
"info": {
"title": "FLASK_TEST API",
"version": "1.0.0"
},
"servers": [
{"url": "http://192.168.240.1:9123"} # 这里改成实际IP
],
"paths": {
"/add": {
"post": {
"summary": "两数相加",
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"a": {"type": "number"},
"b": {"type": "number"}
},
"required": ["a", "b"]
}
}
}
},
"responses": {
"200": {
"description": "成功返回和",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"result": {"type": "number"}
}
}
}
}
}
}
}
},
"/echo": {
"post": {
"summary": "返回输入的消息",
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"message": {"type": "string"}
},
"required": ["message"]
}
}
}
},
"responses": {
"200": {
"description": "成功返回消息",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"result": {"type": "string"}
}
}
}
}
}
}
}
}
}
}
# ------------------------------
# 2. 提供 OpenAPI Schema 接口(关键!给导入用)
# ------------------------------
@app.route('/openapi.json', methods=['GET'])
def openapi_schema():
return jsonify(OPENAPI_SCHEMA)
# ------------------------------
# 3. 实际业务接口
# ------------------------------
@app.route('/add', methods=['POST'])
def add():
data = request.get_json()
a = data['a']
b = data['b']
return jsonify({"result": a + b})
@app.route('/echo', methods=['POST'])
def echo():
data = request.get_json()
message = data['message']
return jsonify({"result": message})
# ------------------------------
# 启动服务
# ------------------------------
if __name__ == '__main__':
app.run(host="0.0.0.0", port=9123, debug=False, use_reloader=False)
运行截图如下:
