docs(openapi): add AI index and annotate setting endpoints
- add openapi-index.py to generate a compact Markdown index from OpenAPI JSON/YAML - generate docs/openapi.index.md from the export scripts by default - annotate SettingController with tags, operations, parameters and public security - document the AI index workflow in api-integration.md
This commit is contained in:
@@ -1,10 +1,11 @@
|
||||
<#
|
||||
<#
|
||||
.SYNOPSIS
|
||||
导出本地 OpenAPI 文档。
|
||||
|
||||
.DESCRIPTION
|
||||
从本地已启动的服务获取 /v3/api-docs.yaml(或 JSON),写入 docs 目录。
|
||||
生成的文件已被 .gitignore 忽略,不会提交。
|
||||
默认同时生成面向 AI Agent 的接口索引 docs/openapi.index.md。
|
||||
生成的 OpenAPI 快照已被 .gitignore 忽略;索引文件可按需提交或单独发送。
|
||||
|
||||
.PARAMETER BaseUrl
|
||||
服务地址,默认 http://localhost:18092。
|
||||
@@ -13,25 +14,41 @@
|
||||
输出文件路径,默认 docs/openapi.local.yaml。
|
||||
扩展名为 .json 时导出 JSON,否则导出 YAML。
|
||||
|
||||
.PARAMETER IndexFile
|
||||
接口索引输出路径,默认 docs/openapi.index.md。
|
||||
|
||||
.PARAMETER NoIndex
|
||||
跳过接口索引生成。
|
||||
|
||||
.EXAMPLE
|
||||
.\scripts\export-openapi.ps1
|
||||
|
||||
.EXAMPLE
|
||||
.\scripts\export-openapi.ps1 -BaseUrl http://192.168.1.10:18092 -OutFile docs/openapi.local.json
|
||||
|
||||
.EXAMPLE
|
||||
.\scripts\export-openapi.ps1 -NoIndex
|
||||
#>
|
||||
param(
|
||||
[string]$BaseUrl = "http://localhost:18092",
|
||||
[string]$OutFile
|
||||
[string]$OutFile,
|
||||
[string]$IndexFile,
|
||||
[switch]$NoIndex
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$RootDir = Split-Path -Parent $PSScriptRoot
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($OutFile)) {
|
||||
$OutFile = Join-Path (Split-Path -Parent $PSScriptRoot) "docs\openapi.local.yaml"
|
||||
$OutFile = Join-Path $RootDir "docs\openapi.local.yaml"
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($IndexFile)) {
|
||||
$IndexFile = Join-Path $RootDir "docs\openapi.index.md"
|
||||
}
|
||||
|
||||
$BaseUrl = $BaseUrl.TrimEnd("/")
|
||||
$OutFile = [System.IO.Path]::GetFullPath($OutFile)
|
||||
$IndexFile = [System.IO.Path]::GetFullPath($IndexFile)
|
||||
$OutDir = Split-Path -Parent $OutFile
|
||||
|
||||
if (-not (Test-Path -LiteralPath $OutDir)) {
|
||||
@@ -48,3 +65,60 @@ $Url = "$BaseUrl$ApiPath"
|
||||
Write-Host "Fetching $Url"
|
||||
Invoke-WebRequest -Uri $Url -OutFile $OutFile -UseBasicParsing
|
||||
Write-Host "OpenAPI exported to $OutFile"
|
||||
|
||||
if ($NoIndex) {
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($IndexFile -eq $OutFile) {
|
||||
Write-Warning "接口索引不能与 OpenAPI 输出文件相同,跳过接口索引生成。"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$IndexScript = Join-Path $PSScriptRoot "openapi-index.py"
|
||||
if (-not (Test-Path -LiteralPath $IndexScript)) {
|
||||
Write-Warning "未找到 $IndexScript,跳过接口索引生成。"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$Python = $null
|
||||
foreach ($Candidate in @("python", "python3")) {
|
||||
$Command = Get-Command $Candidate -ErrorAction SilentlyContinue
|
||||
if ($Command) {
|
||||
$Python = $Command.Source
|
||||
break
|
||||
}
|
||||
}
|
||||
if (-not $Python) {
|
||||
Write-Warning "未找到 Python,跳过接口索引生成。安装 Python 或使用 -NoIndex 关闭该提示。"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$IndexDir = Split-Path -Parent $IndexFile
|
||||
if (-not (Test-Path -LiteralPath $IndexDir)) {
|
||||
New-Item -ItemType Directory -Path $IndexDir -Force | Out-Null
|
||||
}
|
||||
|
||||
$IndexInput = $OutFile
|
||||
$TempIndexInput = $null
|
||||
if ([System.IO.Path]::GetExtension($OutFile) -ine ".json") {
|
||||
$TempIndexInput = [System.IO.Path]::GetTempFileName()
|
||||
try {
|
||||
Invoke-WebRequest -Uri "$BaseUrl/v3/api-docs" -OutFile $TempIndexInput -UseBasicParsing
|
||||
$IndexInput = $TempIndexInput
|
||||
} catch {
|
||||
Write-Warning "获取 OpenAPI JSON 失败,跳过接口索引生成:$($_.Exception.Message)"
|
||||
$IndexInput = $null
|
||||
}
|
||||
}
|
||||
|
||||
if ($IndexInput) {
|
||||
& $Python $IndexScript $IndexInput $IndexFile
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Warning "接口索引生成失败(退出码 $LASTEXITCODE)。"
|
||||
}
|
||||
}
|
||||
|
||||
if ($TempIndexInput -and (Test-Path -LiteralPath $TempIndexInput)) {
|
||||
Remove-Item -LiteralPath $TempIndexInput -Force
|
||||
}
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
# 导出本地 OpenAPI 文档。
|
||||
# 导出本地 OpenAPI 文档,并默认生成面向 AI Agent 的接口索引。
|
||||
#
|
||||
# 用法:
|
||||
# scripts/export-openapi.sh [baseUrl] [outFile]
|
||||
# scripts/export-openapi.sh [baseUrl] [outFile] [indexFile]
|
||||
#
|
||||
# 输出文件扩展名为 .json 时导出 JSON,否则导出 YAML。
|
||||
# 生成的文件已被 .gitignore 忽略,不会提交。
|
||||
# 索引默认输出到 docs/openapi.index.md;设置 SKIP_INDEX=1 可跳过。
|
||||
# 生成的 OpenAPI 快照已被 .gitignore 忽略;索引文件可按需提交或单独发送。
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
BASE_URL="${1:-http://localhost:18092}"
|
||||
OUT_FILE="${2:-$ROOT_DIR/docs/openapi.local.yaml}"
|
||||
INDEX_FILE="${3:-$ROOT_DIR/docs/openapi.index.md}"
|
||||
|
||||
BASE_URL="${BASE_URL%/}"
|
||||
mkdir -p "$(dirname "$OUT_FILE")"
|
||||
@@ -28,3 +30,50 @@ esac
|
||||
echo "Fetching ${BASE_URL}${API_PATH}"
|
||||
curl -fsS "${BASE_URL}${API_PATH}" -o "$OUT_FILE"
|
||||
echo "OpenAPI exported to $OUT_FILE"
|
||||
|
||||
if [[ "${SKIP_INDEX:-0}" == "1" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [[ "$INDEX_FILE" == "$OUT_FILE" ]]; then
|
||||
echo "warning: 接口索引不能与 OpenAPI 输出文件相同,跳过接口索引生成。" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
INDEX_SCRIPT="$ROOT_DIR/scripts/openapi-index.py"
|
||||
if [[ ! -f "$INDEX_SCRIPT" ]]; then
|
||||
echo "warning: 未找到 $INDEX_SCRIPT,跳过接口索引生成。" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
PYTHON="$(command -v python3 2>/dev/null || command -v python 2>/dev/null || true)"
|
||||
if [[ -z "$PYTHON" ]]; then
|
||||
echo "warning: 未找到 Python,跳过接口索引生成。安装 Python 或设置 SKIP_INDEX=1 关闭该提示。" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
INDEX_INPUT="$OUT_FILE"
|
||||
TEMP_JSON=""
|
||||
cleanup() {
|
||||
if [[ -n "$TEMP_JSON" ]]; then
|
||||
rm -f "$TEMP_JSON"
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
if [[ "$OUT_FILE" != *.json ]]; then
|
||||
TEMP_JSON="$(mktemp)"
|
||||
if curl -fsS "${BASE_URL}/v3/api-docs" -o "$TEMP_JSON"; then
|
||||
INDEX_INPUT="$TEMP_JSON"
|
||||
else
|
||||
echo "warning: 获取 OpenAPI JSON 失败,跳过接口索引生成。" >&2
|
||||
INDEX_INPUT=""
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -n "$INDEX_INPUT" ]]; then
|
||||
mkdir -p "$(dirname "$INDEX_FILE")"
|
||||
if ! "$PYTHON" "$INDEX_SCRIPT" "$INDEX_INPUT" "$INDEX_FILE"; then
|
||||
echo "warning: 接口索引生成失败。" >&2
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
#!/usr/bin/env python3
|
||||
"""从 OpenAPI 文档生成供 AI Agent 使用的接口索引。
|
||||
|
||||
默认优先读取 JSON(标准库即可解析);读取 YAML 时需要安装 PyYAML。
|
||||
导出脚本会优先传入 /v3/api-docs 的 JSON,避免额外依赖。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
HTTP_METHODS = ("get", "head", "post", "put", "patch", "delete", "options", "trace")
|
||||
REQUEST_MEDIA = ("application/json", "multipart/form-data", "application/x-www-form-urlencoded", "*/*")
|
||||
RESPONSE_MEDIA = ("application/json", "*/*", "text/event-stream", "application/octet-stream")
|
||||
|
||||
|
||||
def load_spec(path: Path) -> dict[str, Any]:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
try:
|
||||
import yaml
|
||||
except ImportError as exc:
|
||||
raise SystemExit(
|
||||
"无法解析 YAML:请安装 PyYAML(pip install pyyaml),"
|
||||
"或改用 /v3/api-docs 的 JSON 输出。"
|
||||
) from exc
|
||||
data = yaml.safe_load(text)
|
||||
if not isinstance(data, dict):
|
||||
raise SystemExit("OpenAPI 文档格式不正确:根节点必须是对象")
|
||||
return data
|
||||
|
||||
|
||||
def resolve(spec: dict[str, Any], value: Any) -> Any:
|
||||
"""解析本地 $ref,最多跟随 32 层,避免循环引用。"""
|
||||
for _ in range(32):
|
||||
if not isinstance(value, dict) or "$ref" not in value:
|
||||
return value
|
||||
ref = value["$ref"]
|
||||
if not isinstance(ref, str) or not ref.startswith("#/"):
|
||||
return value
|
||||
current: Any = spec
|
||||
for part in ref[2:].split("/"):
|
||||
part = part.replace("~1", "/").replace("~0", "~")
|
||||
if not isinstance(current, dict) or part not in current:
|
||||
return value
|
||||
current = current[part]
|
||||
value = current
|
||||
return value
|
||||
|
||||
|
||||
def ref_name(ref: str) -> str:
|
||||
return ref.rsplit("/", 1)[-1].replace("~1", "/").replace("~0", "~")
|
||||
|
||||
|
||||
def schema_label(spec: dict[str, Any], schema: Any, depth: int = 0) -> str:
|
||||
if not isinstance(schema, dict) or depth > 4:
|
||||
return "-"
|
||||
if "$ref" in schema:
|
||||
return ref_name(str(schema["$ref"]))
|
||||
schema_type = schema.get("type")
|
||||
if isinstance(schema_type, list):
|
||||
schema_type = "/".join(str(item) for item in schema_type)
|
||||
if schema_type == "array":
|
||||
return f"Array<{schema_label(spec, schema.get('items'), depth + 1)}>"
|
||||
if schema_type == "object" or "properties" in schema:
|
||||
additional = schema.get("additionalProperties")
|
||||
if isinstance(additional, dict):
|
||||
return f"Map<String, {schema_label(spec, additional, depth + 1)}>"
|
||||
if additional is True:
|
||||
return "Map<String, any>"
|
||||
properties = schema.get("properties")
|
||||
if isinstance(properties, dict) and properties:
|
||||
names = list(properties)
|
||||
if len(names) > 8:
|
||||
names = names[:8] + ["..."]
|
||||
return "object{" + ", ".join(names) + "}"
|
||||
return "object"
|
||||
for keyword in ("oneOf", "anyOf", "allOf"):
|
||||
items = schema.get(keyword)
|
||||
if isinstance(items, list) and items:
|
||||
joiner = " | " if keyword == "oneOf" else " & "
|
||||
return "(" + joiner.join(schema_label(spec, item, depth + 1) for item in items) + ")"
|
||||
if schema_type == "string" and schema.get("format") in ("binary", "byte"):
|
||||
return "binary"
|
||||
if schema_type:
|
||||
return str(schema_type)
|
||||
return "-"
|
||||
|
||||
|
||||
def pick_media(content: Any, preferred: tuple[str, ...]) -> tuple[str | None, Any]:
|
||||
if not isinstance(content, dict) or not content:
|
||||
return None, None
|
||||
for media in preferred:
|
||||
if media in content:
|
||||
return media, content[media]
|
||||
media = next(iter(content))
|
||||
return media, content[media]
|
||||
|
||||
|
||||
def request_label(spec: dict[str, Any], operation: dict[str, Any]) -> str:
|
||||
body = resolve(spec, operation.get("requestBody"))
|
||||
if not isinstance(body, dict):
|
||||
return "-"
|
||||
media, entry = pick_media(body.get("content"), REQUEST_MEDIA)
|
||||
if media is None:
|
||||
return "-"
|
||||
schema = entry.get("schema") if isinstance(entry, dict) else None
|
||||
label = schema_label(spec, schema)
|
||||
if label == "-":
|
||||
return media
|
||||
if media in ("application/json", "*/*"):
|
||||
return label
|
||||
return f"{label} ({media})"
|
||||
|
||||
|
||||
def response_label(spec: dict[str, Any], operation: dict[str, Any]) -> str:
|
||||
responses = operation.get("responses")
|
||||
if not isinstance(responses, dict) or not responses:
|
||||
return "-"
|
||||
response = None
|
||||
for code in ("200", "201", "202", "204"):
|
||||
if code in responses:
|
||||
response = responses[code]
|
||||
break
|
||||
if response is None:
|
||||
for code, candidate in responses.items():
|
||||
if str(code).startswith("2"):
|
||||
response = candidate
|
||||
break
|
||||
if response is None and "default" in responses:
|
||||
response = responses["default"]
|
||||
response = resolve(spec, response)
|
||||
if not isinstance(response, dict):
|
||||
return "-"
|
||||
media, entry = pick_media(response.get("content"), RESPONSE_MEDIA)
|
||||
if media is None:
|
||||
return "-"
|
||||
if media == "text/event-stream":
|
||||
return "SSE"
|
||||
schema = entry.get("schema") if isinstance(entry, dict) else None
|
||||
label = schema_label(spec, schema)
|
||||
if label == "-":
|
||||
return media
|
||||
if media in ("application/json", "*/*"):
|
||||
return label
|
||||
return f"{label} ({media})"
|
||||
|
||||
|
||||
def parameter_label(spec: dict[str, Any], path_item: dict[str, Any], operation: dict[str, Any]) -> str:
|
||||
merged: dict[tuple[str, str], dict[str, Any]] = {}
|
||||
for source in (path_item.get("parameters"), operation.get("parameters")):
|
||||
if not isinstance(source, list):
|
||||
continue
|
||||
for raw in source:
|
||||
parameter = resolve(spec, raw)
|
||||
if not isinstance(parameter, dict):
|
||||
continue
|
||||
name = parameter.get("name")
|
||||
location = parameter.get("in")
|
||||
if name and location:
|
||||
merged[(str(name), str(location))] = parameter
|
||||
if not merged:
|
||||
return "-"
|
||||
parts = []
|
||||
for (name, location), parameter in merged.items():
|
||||
prefix = ""
|
||||
if location in ("header", "cookie"):
|
||||
prefix = f"{location}:"
|
||||
suffix = "*" if parameter.get("required") else ""
|
||||
parts.append(f"{prefix}{name}{suffix}")
|
||||
return ", ".join(parts)
|
||||
|
||||
|
||||
def cell(value: Any) -> str:
|
||||
text = "" if value is None else str(value)
|
||||
text = re.sub(r"\s+", " ", text).strip()
|
||||
text = text.replace("|", "\\|")
|
||||
return text or "-"
|
||||
|
||||
|
||||
def module_key(path: str) -> str:
|
||||
segments = [segment for segment in path.split("/") if segment]
|
||||
if not segments:
|
||||
return "root"
|
||||
if segments[0] == "gao" and len(segments) > 1:
|
||||
return f"gao-{segments[1]}"
|
||||
return segments[0]
|
||||
|
||||
|
||||
def module_prefix(key: str) -> str:
|
||||
if key == "root":
|
||||
return "/"
|
||||
if key.startswith("gao-"):
|
||||
return f"/gao/{key[4:]}/"
|
||||
return f"/{key}/"
|
||||
|
||||
|
||||
def module_sort(key: str) -> tuple[int, str]:
|
||||
if key.startswith("gao-"):
|
||||
return 0, key
|
||||
order = {"system": 1, "user": 2, "app": 3}
|
||||
return order.get(key, 4), key
|
||||
|
||||
|
||||
def collect_operations(spec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
paths = spec.get("paths")
|
||||
if not isinstance(paths, dict):
|
||||
return []
|
||||
operations = []
|
||||
for path, path_item in paths.items():
|
||||
if not isinstance(path_item, dict):
|
||||
continue
|
||||
path_item = resolve(spec, path_item)
|
||||
if not isinstance(path_item, dict):
|
||||
continue
|
||||
for method in HTTP_METHODS:
|
||||
operation = path_item.get(method)
|
||||
if not isinstance(operation, dict):
|
||||
continue
|
||||
operation = resolve(spec, operation)
|
||||
if not isinstance(operation, dict):
|
||||
continue
|
||||
summary = operation.get("summary") or operation.get("operationId") or ""
|
||||
if operation.get("summary") is None and isinstance(summary, str):
|
||||
summary = re.sub(r"_\d+$", "", summary)
|
||||
if operation.get("deprecated"):
|
||||
summary = f"[已废弃] {summary}"
|
||||
public = operation["security"] == [] if "security" in operation else not spec.get("security")
|
||||
if public:
|
||||
summary = f"[公开] {summary}"
|
||||
operations.append({
|
||||
"methods": [method.upper()],
|
||||
"path": path,
|
||||
"summary": summary,
|
||||
"parameters": parameter_label(spec, path_item, operation),
|
||||
"request": request_label(spec, operation),
|
||||
"response": response_label(spec, operation),
|
||||
"tag": ", ".join(operation.get("tags") or []),
|
||||
"module": module_key(path),
|
||||
"order": (path, HTTP_METHODS.index(method)),
|
||||
})
|
||||
# 同一个处理器的多个 HTTP 方法(如 @RequestMapping 未限定 method)合并为一行。
|
||||
merged: dict[tuple[Any, ...], dict[str, Any]] = {}
|
||||
for operation in operations:
|
||||
key = (
|
||||
operation["path"],
|
||||
operation["summary"],
|
||||
operation["parameters"],
|
||||
operation["request"],
|
||||
operation["response"],
|
||||
operation["tag"],
|
||||
operation["module"],
|
||||
)
|
||||
if key in merged:
|
||||
merged[key]["methods"].append(operation["methods"][0])
|
||||
else:
|
||||
merged[key] = operation
|
||||
return list(merged.values())
|
||||
|
||||
|
||||
def render(spec: dict[str, Any], source: str) -> str:
|
||||
info = spec.get("info") if isinstance(spec.get("info"), dict) else {}
|
||||
title = info.get("title") or "OpenAPI"
|
||||
version = info.get("version") or "-"
|
||||
openapi_version = spec.get("openapi") or "-"
|
||||
paths = spec.get("paths") if isinstance(spec.get("paths"), dict) else {}
|
||||
operations = collect_operations(spec)
|
||||
groups: dict[str, list[dict[str, Any]]] = {}
|
||||
for operation in operations:
|
||||
groups.setdefault(operation["module"], []).append(operation)
|
||||
for items in groups.values():
|
||||
items.sort(key=lambda item: item["order"])
|
||||
|
||||
lines = [
|
||||
f"# {title} 接口索引",
|
||||
"",
|
||||
"> 本文件由 `scripts/openapi-index.py` 从 OpenAPI 快照生成,请勿手工编辑。",
|
||||
f"> 数据来源:`{source}`。完整字段定义以 OpenAPI 原文为准。",
|
||||
"",
|
||||
f"- 服务版本:`{version}`",
|
||||
f"- OpenAPI 版本:`{openapi_version}`",
|
||||
f"- 路径数:{len(paths)}",
|
||||
f"- 接口数:{len(operations)}(同一路径的同一处理器会合并多个 HTTP 方法)",
|
||||
f"- 模块数:{len(groups)}",
|
||||
"",
|
||||
"## 使用说明",
|
||||
"",
|
||||
"- 先按模块定位接口,再读取 `docs/openapi.local.yaml` 中对应的 `path` 或 `components/schemas`,不要整文件加载。",
|
||||
"- 参数列中 `*` 表示必填;`header:`、`cookie:` 为参数位置前缀,其余为 path/query 参数。",
|
||||
"- 摘要前的 `[公开]` 表示 OpenAPI 中显式标记为无需登录;未标记的接口默认使用 `Token` 鉴权。",
|
||||
"- 方法列出现多个 HTTP 方法,表示 Controller 使用了未限定 method 的 `@RequestMapping`。",
|
||||
"- 请求体和响应列展示顶层 schema 名称;`binary` 表示二进制响应,`SSE` 表示 `text/event-stream`。",
|
||||
"- 普通 JSON 接口的响应仍由 `TimiResponse` 包装,鉴权、错误码、分页等约定见 `docs/api-integration.md`。",
|
||||
"",
|
||||
"## 模块导航",
|
||||
"",
|
||||
"| 模块 | 接口数 | 路径前缀 |",
|
||||
"| --- | ---: | --- |",
|
||||
]
|
||||
for key in sorted(groups, key=module_sort):
|
||||
lines.append(f"| [`{cell(key)}`](#module-{key}) | {len(groups[key])} | `{module_prefix(key)}` |")
|
||||
|
||||
for key in sorted(groups, key=module_sort):
|
||||
lines.extend([
|
||||
"",
|
||||
f'<a id="module-{key}"></a>',
|
||||
f"## {key}",
|
||||
"",
|
||||
f"共 {len(groups[key])} 个接口,路径前缀 `{module_prefix(key)}`。",
|
||||
"",
|
||||
"| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |",
|
||||
"| --- | --- | --- | --- | --- | --- | --- |",
|
||||
])
|
||||
for operation in groups[key]:
|
||||
lines.append(
|
||||
"| {method} | `{path}` | {summary} | {parameters} | {request} | {response} | {tag} |".format(
|
||||
method="/".join(operation["methods"]),
|
||||
path=cell(operation["path"]),
|
||||
summary=cell(operation["summary"]),
|
||||
parameters=cell(operation["parameters"]),
|
||||
request=cell(operation["request"]),
|
||||
response=cell(operation["response"]),
|
||||
tag=cell(operation["tag"]),
|
||||
)
|
||||
)
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="从 OpenAPI 文档生成 AI Agent 接口索引")
|
||||
parser.add_argument("input", type=Path, help="OpenAPI JSON/YAML 文件")
|
||||
parser.add_argument("output", type=Path, help="输出的 Markdown 文件")
|
||||
parser.add_argument(
|
||||
"--source-label",
|
||||
default="docs/openapi.local.yaml",
|
||||
help="索引中显示的数据来源(默认 docs/openapi.local.yaml)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
spec = load_spec(args.input)
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(render(spec, args.source_label), encoding="utf-8", newline="\n")
|
||||
print(f"OpenAPI index written to {args.output}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user