- Add OpenAPI tags for the seven API groups and a full description (auth, error envelope, pagination, idempotency) in SPECTACULAR_SETTINGS - Annotate every endpoint with @extend_schema: summary, description, query parameters, request/response examples and error responses - Add shared schema helpers in apps/common/schema.py: ErrorEnvelope, error_responses(), pagination and catalog filter parameters - Document JWT login and token refresh that simplejwt ships without docs - Add ReDoc at /api/redoc/ next to Swagger UI at /api/docs/ - Add export_api_docs management command rendering the schema into a standalone HTML reference (no CDN) and commit docs/api-reference.html - Describe the documentation entry points in docs/architecture.md Schema validates cleanly: 41 operations, 0 warnings.
315 lines
12 KiB
Python
315 lines
12 KiB
Python
"""Exports the OpenAPI schema into a standalone HTML reference.
|
|
|
|
Swagger UI and ReDoc load their JavaScript from a CDN, which is not always
|
|
reachable (closed corporate networks, servers without internet access). This
|
|
command renders the same schema into one self-contained HTML file with inline
|
|
CSS and no external requests.
|
|
"""
|
|
|
|
import html
|
|
import json
|
|
from pathlib import Path
|
|
|
|
from django.core.management.base import BaseCommand
|
|
from drf_spectacular.generators import SchemaGenerator
|
|
|
|
METHOD_COLORS = {
|
|
"get": "#0b7a3b",
|
|
"post": "#1c4fd8",
|
|
"put": "#b26a00",
|
|
"patch": "#8a4b00",
|
|
"delete": "#b3261e",
|
|
}
|
|
|
|
CSS = """
|
|
:root { --fg:#16212b; --muted:#5b6b7a; --line:#e2e8ee; --bg:#f7f9fb; }
|
|
* { box-sizing: border-box; }
|
|
body { margin:0; font:15px/1.55 -apple-system,"Segoe UI",Roboto,Arial,sans-serif;
|
|
color:var(--fg); background:var(--bg); }
|
|
header { background:#fff; border-bottom:1px solid var(--line); padding:28px 32px 22px; }
|
|
header h1 { margin:0 0 6px; font-size:26px; letter-spacing:-.3px; }
|
|
header .version { color:var(--muted); font-size:13px; }
|
|
header p { margin:10px 0 0; color:var(--muted); max-width:900px; white-space:pre-wrap; }
|
|
main { padding:24px 32px 60px; max-width:1100px; }
|
|
nav { background:#fff; border:1px solid var(--line); border-radius:10px;
|
|
padding:12px 18px; margin-bottom:26px; }
|
|
nav a { display:inline-block; color:#1c4fd8; text-decoration:none;
|
|
margin:4px 18px 4px 0; font-size:14px; }
|
|
nav a:hover { text-decoration:underline; }
|
|
section.tag { margin-bottom:38px; }
|
|
section.tag > h2 { font-size:21px; margin:0 0 4px; }
|
|
section.tag > .tagdesc { color:var(--muted); margin:0 0 16px; max-width:850px;
|
|
white-space:pre-wrap; }
|
|
.op { background:#fff; border:1px solid var(--line); border-radius:10px;
|
|
margin-bottom:14px; overflow:hidden; }
|
|
.op > .head { display:flex; gap:12px; align-items:baseline; padding:14px 18px;
|
|
cursor:pointer; }
|
|
.op.open > .head { border-bottom:1px solid var(--line); }
|
|
.method { font:600 12px/1 ui-monospace,Menlo,Consolas,monospace; color:#fff;
|
|
padding:5px 8px; border-radius:5px; text-transform:uppercase; }
|
|
.path { font:14px/1.4 ui-monospace,Menlo,Consolas,monospace; }
|
|
.summary { color:var(--muted); font-size:14px; margin-left:auto; text-align:right; }
|
|
.body { display:none; padding:4px 18px 18px; }
|
|
.op.open .body { display:block; }
|
|
.desc { color:#31404d; white-space:pre-wrap; margin:12px 0; }
|
|
h4 { font-size:13px; text-transform:uppercase; letter-spacing:.5px;
|
|
color:var(--muted); margin:18px 0 8px; }
|
|
table { border-collapse:collapse; width:100%; font-size:14px; }
|
|
th,td { text-align:left; padding:7px 10px; border-bottom:1px solid var(--line);
|
|
vertical-align:top; }
|
|
th { color:var(--muted); font-weight:600; font-size:12px; text-transform:uppercase; }
|
|
td code, p code, li code { background:#eef2f7; padding:1px 5px; border-radius:4px;
|
|
font:13px ui-monospace,Menlo,Consolas,monospace; }
|
|
.req { color:#b3261e; font-size:12px; }
|
|
pre { background:#0f1b26; color:#dde7f0; padding:12px 14px; border-radius:8px;
|
|
overflow:auto; font:13px/1.5 ui-monospace,Menlo,Consolas,monospace; }
|
|
.badge { display:inline-block; background:#eef2f7; color:#31404d; border-radius:6px;
|
|
padding:2px 7px; font-size:12px; margin-left:8px; }
|
|
footer { color:var(--muted); font-size:13px; padding:0 32px 40px; }
|
|
"""
|
|
|
|
JS = """
|
|
document.querySelectorAll('.op > .head').forEach(function (head) {
|
|
head.addEventListener('click', function () {
|
|
head.parentElement.classList.toggle('open');
|
|
});
|
|
});
|
|
"""
|
|
|
|
|
|
def esc(value) -> str:
|
|
return html.escape(str(value), quote=False)
|
|
|
|
|
|
def render_rich(text: str) -> str:
|
|
"""Very small subset of markdown: paragraphs, **bold**, `code`, newlines."""
|
|
if not text:
|
|
return ""
|
|
out = esc(text)
|
|
parts = out.split("**")
|
|
rebuilt = []
|
|
for index, part in enumerate(parts):
|
|
rebuilt.append(f"<strong>{part}</strong>" if index % 2 else part)
|
|
out = "".join(rebuilt)
|
|
chunks = out.split("`")
|
|
rebuilt = []
|
|
for index, chunk in enumerate(chunks):
|
|
rebuilt.append(f"<code>{chunk}</code>" if index % 2 else chunk)
|
|
return "".join(rebuilt)
|
|
|
|
|
|
def resolve(node, schema, depth=0):
|
|
"""Resolves $ref against components, with a depth guard."""
|
|
if depth > 6 or not isinstance(node, dict):
|
|
return node
|
|
ref = node.get("$ref")
|
|
if not ref:
|
|
return node
|
|
name = ref.rsplit("/", 1)[-1]
|
|
target = schema.get("components", {}).get("schemas", {}).get(name, {})
|
|
return resolve(target, schema, depth + 1)
|
|
|
|
|
|
def type_label(prop: dict) -> str:
|
|
if "$ref" in prop:
|
|
return prop["$ref"].rsplit("/", 1)[-1]
|
|
if prop.get("type") == "array":
|
|
items = prop.get("items", {})
|
|
inner = type_label(items) if items else "object"
|
|
return f"array[{inner}]"
|
|
if prop.get("enum"):
|
|
return "enum (" + ", ".join(str(v) for v in prop["enum"]) + ")"
|
|
return prop.get("type", "object")
|
|
|
|
|
|
def fields_table(node, schema, required_names) -> str:
|
|
"""Renders object properties as a table. Empty string when not an object."""
|
|
node = resolve(node, schema)
|
|
props = node.get("properties") if isinstance(node, dict) else None
|
|
if not props:
|
|
return ""
|
|
rows = []
|
|
for name, prop in props.items():
|
|
prop = resolve(prop, schema) if "$ref" in prop else prop
|
|
description = prop.get("description", "")
|
|
flag = '<span class="req">*</span>' if name in required_names else ""
|
|
rows.append(
|
|
f"<tr><td><code>{esc(name)}</code>{flag}</td>"
|
|
f"<td>{esc(type_label(prop))}</td>"
|
|
f"<td>{esc(description)}</td></tr>"
|
|
)
|
|
return (
|
|
"<table><tr><th>Поле</th><th>Тип</th><th>Описание</th></tr>"
|
|
+ "".join(rows)
|
|
+ "</table>"
|
|
)
|
|
|
|
|
|
def examples_block(payload, title: str) -> str:
|
|
examples = payload.get("examples") if isinstance(payload, dict) else None
|
|
if not examples:
|
|
return ""
|
|
blocks = []
|
|
for name, example in examples.items():
|
|
value = example.get("value")
|
|
label = example.get("summary") or name
|
|
blocks.append(
|
|
f"<p><strong>{esc(label)}</strong></p>"
|
|
f"<pre>{esc(json.dumps(value, ensure_ascii=False, indent=2))}</pre>"
|
|
)
|
|
return f"<h4>{esc(title)}</h4>" + "".join(blocks)
|
|
|
|
|
|
def parameters_table(parameters, schema) -> str:
|
|
if not parameters:
|
|
return ""
|
|
rows = []
|
|
for param in parameters:
|
|
param = resolve(param, schema)
|
|
meta = param.get("schema", {})
|
|
location = param.get("in", "")
|
|
flag = '<span class="req">*</span>' if param.get("required") else ""
|
|
rows.append(
|
|
f"<tr><td><code>{esc(param.get('name', ''))}</code>{flag}</td>"
|
|
f"<td>{esc(location)}</td>"
|
|
f"<td>{esc(type_label(meta))}</td>"
|
|
f"<td>{esc(param.get('description', ''))}</td></tr>"
|
|
)
|
|
return (
|
|
"<h4>Параметры</h4><table><tr><th>Имя</th><th>Где</th><th>Тип</th>"
|
|
"<th>Описание</th></tr>" + "".join(rows) + "</table>"
|
|
)
|
|
|
|
|
|
def request_block(op, schema) -> str:
|
|
body = op.get("requestBody")
|
|
if not body:
|
|
return ""
|
|
body = resolve(body, schema)
|
|
content = body.get("content", {}).get("application/json", {})
|
|
ref = content.get("schema", {})
|
|
required = resolve(ref, schema).get("required", []) if ref else []
|
|
table = fields_table(ref, schema, required)
|
|
head = "<h4>Тело запроса</h4>" + (table or "")
|
|
return head + examples_block(content, "Примеры запроса")
|
|
|
|
|
|
def responses_block(op, schema) -> str:
|
|
chunks = ["<h4>Ответы</h4>"]
|
|
for code, response in sorted(op.get("responses", {}).items()):
|
|
response = resolve(response, schema)
|
|
description = response.get("description", "")
|
|
content = response.get("content", {}).get("application/json", {})
|
|
ref = content.get("schema", {})
|
|
required = resolve(ref, schema).get("required", []) if ref else []
|
|
table = fields_table(ref, schema, required) if ref else ""
|
|
chunks.append(
|
|
f'<p><span class="badge">{esc(code)}</span> {render_rich(description)}</p>'
|
|
)
|
|
if table:
|
|
chunks.append(table)
|
|
chunks.append(examples_block(content, "Пример ответа"))
|
|
return "".join(chunks)
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = (
|
|
"Рендерит OpenAPI-схему в один автономный HTML-файл "
|
|
"(без CDN и внешних запросов)."
|
|
)
|
|
|
|
def add_arguments(self, parser):
|
|
parser.add_argument(
|
|
"--out",
|
|
default="api-reference.html",
|
|
help="Куда сохранить HTML (по умолчанию backend/api-reference.html).",
|
|
)
|
|
|
|
def handle(self, *args, **options):
|
|
generator = SchemaGenerator()
|
|
schema = generator.get_schema(request=None, public=True)
|
|
info = schema.get("info", {})
|
|
declared_tags = schema.get("tags", [])
|
|
|
|
by_tag: dict[str, list] = {}
|
|
for path, methods in sorted(schema.get("paths", {}).items()):
|
|
for method, op in methods.items():
|
|
for tag in op.get("tags", ["Прочее"]):
|
|
by_tag.setdefault(tag, []).append((path, method, op))
|
|
|
|
ordered_tags = [tag["name"] for tag in declared_tags]
|
|
ordered_tags += [name for name in by_tag if name not in ordered_tags]
|
|
|
|
nav_links = "".join(
|
|
f'<a href="#tag-{esc(name)}">{esc(name)}</a>' for name in ordered_tags
|
|
)
|
|
|
|
sections = []
|
|
for name in ordered_tags:
|
|
operations = by_tag.get(name)
|
|
if not operations:
|
|
continue
|
|
description = next(
|
|
(tag.get("description", "") for tag in declared_tags if tag["name"] == name),
|
|
"",
|
|
)
|
|
articles = []
|
|
for path, method, op in operations:
|
|
request = request_block(op, schema)
|
|
responses = responses_block(op, schema)
|
|
params = parameters_table(op.get("parameters", []), schema)
|
|
articles.append(
|
|
'<article class="op">'
|
|
f'<div class="head"><span class="method" '
|
|
f'style="background:{METHOD_COLORS.get(method, "#475569")}">'
|
|
f"{esc(method)}</span>"
|
|
f'<span class="path">{esc(path)}</span>'
|
|
f'<span class="summary">{esc(op.get("summary", ""))}</span></div>'
|
|
f'<div class="body">'
|
|
f'<div class="desc">{render_rich(op.get("description", ""))}</div>'
|
|
f"{params}{request}{responses}</div></article>"
|
|
)
|
|
sections.append(
|
|
f'<section class="tag" id="tag-{esc(name)}">'
|
|
f"<h2>{esc(name)}</h2>"
|
|
f'<p class="tagdesc">{render_rich(description)}</p>'
|
|
+ "".join(articles)
|
|
+ "</section>"
|
|
)
|
|
|
|
document = f"""<!DOCTYPE html>
|
|
<html lang="ru">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<title>{esc(info.get("title", "API"))} — справочник</title>
|
|
<style>{CSS}</style>
|
|
</head>
|
|
<body>
|
|
<header>
|
|
<h1>{esc(info.get("title", "API"))}</h1>
|
|
<div class="version">Версия {esc(info.get("version", ""))}</div>
|
|
<p>{render_rich(info.get("description", ""))}</p>
|
|
</header>
|
|
<main>
|
|
<nav>{nav_links}</nav>
|
|
{''.join(sections)}
|
|
</main>
|
|
<footer>
|
|
Файл сгенерирован из OpenAPI-схемы командой
|
|
<code>python manage.py export_api_docs</code>. Интерактивная версия доступна
|
|
по адресу <code>/api/docs/</code> (требует доступа к CDN).
|
|
</footer>
|
|
<script>{JS}</script>
|
|
</body>
|
|
</html>
|
|
"""
|
|
out_path = Path(options["out"])
|
|
out_path.write_text(document, encoding="utf-8")
|
|
self.stdout.write(
|
|
self.style.SUCCESS(
|
|
f"Готово: {out_path} ({len(document)} байт, "
|
|
f"операций: {sum(len(v) for v in by_tag.values())})"
|
|
)
|
|
)
|