rebuild schema dynamically

This commit is contained in:
Oliver Walters committed 2026-11-12 02:44:35 +00:00
1 parent e479fbf95e
commit 03e3872d80
26 files changed
+701 -1672

No files matched your search

+1
View File
@@ -12,6 +12,7 @@ site/
# Generated API schema files
docs/api/schema/*.yml
docs/api/schema/*.md
# Temporary cache files
url_cache.txt
-7
View File
@@ -1,7 +0,0 @@
---
title: Authorization and Authentication
---
The *Authorization and Authentication* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/auth.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: Background Task Management
---
The *Background Task Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/background-task.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: Barcode Scanning
---
The *Barcode Scanning* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/barcode.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: Bill of Materials
---
The *Bill of Materials* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/bom.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: Build Order Management
---
The *Build Order Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/build.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: Company Management
---
The *Company Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/company.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: General API Endpoints
---
The *General API Endpoints* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/general.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: Label Printing
---
The *Label Printing* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/label.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: External Machine Management
---
The *External Machine Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/machine.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: External Order Management
---
The *External Order Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/order.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: Parts and Part Categories
---
The *Parts and Part Categories* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/part.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: Plugin Functionality
---
The *Plugin Functionality* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/plugins.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: Part Pricing
---
The *Part Pricing* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/pricing.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: Report Generation
---
The *Report Generation* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/report.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: Settings Management
---
The *Settings Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/settings.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: Stock and Stock Locations
---
The *Stock and Stock Locations* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/stock.yml)]
-7
View File
@@ -1,7 +0,0 @@
---
title: User Management
---
The *User Management* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/user.yml)]
+21
View File
@@ -155,3 +155,24 @@ div:nth-of-type(1) p {
background-color: #5bc0de;
color: #555;
}
/* HTTP method badges for the generated API schema documentation */
.api-method {
display: inline-block;
min-width: 4.2em;
padding: 0.1em 0.5em;
border-radius: 0.2rem;
color: #fff;
font-family: var(--md-code-font-family);
font-size: 0.75em;
font-weight: 700;
text-align: center;
vertical-align: middle;
}
.api-method-get { background-color: #2b8a3e; }
.api-method-post { background-color: #1971c2; }
.api-method-put { background-color: #e67700; }
.api-method-patch { background-color: #9c36b5; }
.api-method-delete { background-color: #c92a2a; }
.api-method-head, .api-method-options { background-color: #495057; }
File diff suppressed because it is too large. Load diff
+10 -93
View File
@@ -2,10 +2,10 @@
import argparse
import os
import re
import textwrap
import yaml
from render_schema import SchemaRenderer
OUTPUT_DIR = './docs/api/schema/'
@@ -54,21 +54,11 @@ def top_level_path(path: str) -> str:
return GENERAL_PATH
def generate_schema_file(key: str) -> None:
"""Generate a schema file for the provided key."""
def generate_schema_file(key: str, renderer: SchemaRenderer, paths: dict) -> None:
"""Render the API documentation page for the provided key."""
description = SPECIAL_PATHS.get(key, 'General API Endpoints')
output = f"""
---
title: {description}
---
The *{description}* section of the InvenTree API schema is documented below.
[OAD(./docs/docs/api/schema/{key}.yml)]
"""
output = textwrap.dedent(output).strip() + '\n'
output = renderer.render_page(description, paths)
output_file = os.path.join(os.path.dirname(__file__), OUTPUT_DIR, f'{key}.md')
output_file = os.path.abspath(output_file)
@@ -125,99 +115,26 @@ def generate_index_file(version: str):
f.write(output)
def extract_refs(data: dict, components: dict) -> dict:
"""Extract a dict of refs from the provided paths dict.
The refs are located like so:
<path>:<method>:responses:<status>:content:application/json:schema:$ref
Also, the referenced components might reference *sub* components,
so we need to do this step recursively.
"""
pattern = r"'?\$ref'?: '#\/components\/schemas\/(\S+)'"
# First, extract the results from the paths data dict
matches = re.findall(pattern, str(data))
refs = list(matches)
# Next, extract additional refs from the components dict
# Note that the components dict may reference other components
idx = 0
while idx < len(refs):
ref = refs[idx]
schema = components.get('schemas', {}).get(ref, None)
if schema:
# Search for additional refs
matches = re.findall(pattern, str(schema))
for match in matches:
if match not in refs:
refs.append(match)
idx += 1
# Return a dict only of the extracted refs
schemas = {ref: components['schemas'][ref] for ref in refs}
return schemas
def parse_api_file(filename: str):
"""Parse the input API file, and split into smaller sections.
"""Parse the input API file, and render it as a set of smaller documentation pages.
The intent is to make the API schema easier to peruse on the documentation.
"""
with open(filename, encoding='utf-8') as f:
data = yaml.safe_load(f)
paths = data['paths']
top_level_paths = {}
for path, methods in paths.items():
for path, methods in data['paths'].items():
tlp = top_level_path(path)
top_level_paths.setdefault(tlp, {})[path] = methods
if tlp not in top_level_paths:
top_level_paths[tlp] = {}
top_level_paths[tlp][path] = methods
# The renderer uses the complete schema, so all references can be resolved
renderer = SchemaRenderer(data)
# Generate output files
for key, value in top_level_paths.items():
output_file = os.path.join(os.path.dirname(__file__), OUTPUT_DIR, f'{key}.yml')
output = {}
output['paths'] = value
components = data.get('components', {})
# Extract only the schemas relating to the provided paths
path_schemas = extract_refs(value, components)
for k, v in data.items():
if k == 'components':
v = v.copy()
v['schemas'] = path_schemas
if k != 'paths':
output[k] = v
print(f'Writing schema file to {output_file}...')
output_file = os.path.abspath(output_file)
with open(output_file, 'w', encoding='utf-8') as f:
yaml.dump(output, f)
# Generate a markdown file for the schema
generate_schema_file(key)
generate_schema_file(key, renderer, value)
# Finally, generate an index file for the API schema
generate_index_file(data['info']['version'])
-3
View File
@@ -57,7 +57,6 @@ extra_css:
- stylesheets/bootstrap.css
- stylesheets/splide.min.css
- stylesheets/extra.css
- stylesheets/neoteroi-mkdocs.css
- https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@3.31.0/dist/tabler-icons.min.css
extra_javascript:
- javascripts/extra.js
@@ -303,8 +302,6 @@ nav:
# Plugins
plugins:
- neoteroi.mkdocsoad:
use_pymdownx: true
- include-markdown:
opening_tag: "{!"
closing_tag: "!}"
+1 -4
View File
@@ -2,7 +2,7 @@
# zensical build -f docs/mkdocs.zensical.yml
# Differences: theme.variant classic, include_dir relative to this file, native mermaid,
# macros on_error_fail, separate site_dir. mermaid2 / simple-hooks / git-revision-date /
# neoteroi plugins are not supported by Zensical (silently ignored).
# plugins are not supported by Zensical (silently ignored).
# Project
site_url: https://inventree.readthedocs.io
@@ -64,7 +64,6 @@ extra_css:
- stylesheets/bootstrap.css
- stylesheets/splide.min.css
- stylesheets/extra.css
- stylesheets/neoteroi-mkdocs.css
- https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@3.31.0/dist/tabler-icons.min.css
extra_javascript:
- javascripts/extra.js
@@ -310,8 +309,6 @@ nav:
# Plugins
plugins:
- neoteroi.mkdocsoad:
use_pymdownx: true
- include-markdown:
opening_tag: "{!"
closing_tag: "!}"
+667
View File
@@ -0,0 +1,667 @@
"""Render sections of the InvenTree OpenAPI schema as static Markdown pages.
This replaces the 'neoteroi.mkdocsoad' plugin, so that the API documentation
is plain Markdown which can be rendered by any static site generator
(mkdocs, zensical, etc), without requiring a build-time plugin.
The rendered pages are generated as a pre-build step (see 'extract_schema.py').
"""
import json
import re
from typing import Any, Optional
HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options']
# Placeholder values for generated examples, keyed by OpenAPI 'format'
FORMAT_EXAMPLES = {
'date': '2024-01-01',
'date-time': '2024-01-01T12:00:00Z',
'time': '12:00:00',
'email': 'user@example.com',
'uri': 'https://example.com',
'uuid': '3fa85f64-5717-4562-b3fc-2c963f66afa6',
'decimal': '0.00',
'binary': '<binary>',
'ipv4': '127.0.0.1',
}
# Maximum depth when generating JSON examples (guards against deep nesting)
EXAMPLE_MAX_DEPTH = 5
def schema_anchor(name: str) -> str:
"""Return the HTML anchor for a named component schema."""
return 'schema-' + re.sub(r'[^a-z0-9]+', '-', name.lower()).strip('-')
def operation_anchor(method: str, path: str) -> str:
"""Return the HTML anchor for a single API operation."""
return method.lower() + '-' + re.sub(r'[^a-z0-9]+', '-', path.lower()).strip('-')
def escape_text(text: Any) -> str:
"""Escape free text so it cannot inject HTML into the rendered page.
Markdown formatting (e.g. `code` or *emphasis*) is preserved.
"""
text = '' if text is None else str(text)
return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
def escape_cell(text: Any) -> str:
"""Escape text for use within a single Markdown table cell."""
text = escape_text(text).strip()
text = text.replace('|', '\\|')
lines = []
for line in text.splitlines():
line = line.strip()
# Bulleted lists cannot be rendered within a table cell
if line.startswith(('* ', '- ')):
line = '• ' + line[2:]
lines.append(line)
return '<br>'.join(line for line in lines if line)
def inline_code(text: Any) -> str:
"""Wrap a value as inline code, coping with embedded backticks."""
text = str(text)
fence = '``' if '`' in text else '`'
pad = ' ' if '`' in text else ''
return f'{fence}{pad}{text}{pad}{fence}'
class SchemaRenderer:
"""Render API operations and their component schemas to Markdown."""
def __init__(self, spec: dict):
"""Initialize the renderer with the *complete* OpenAPI spec.
The full spec is required so that '$ref' entries can always be resolved,
regardless of which subset of paths is being rendered.
"""
self.spec = spec
self.components = spec.get('components', {})
self.schemas = self.components.get('schemas', {})
# ------------------------------------------------------------------ #
# Reference handling
# ------------------------------------------------------------------ #
@staticmethod
def ref_name(ref: str) -> str:
"""Return the final component name from a '$ref' string."""
return ref.split('/')[-1]
def resolve(self, obj: Any) -> Any:
"""Resolve a '$ref' (to any component type) into the referenced object."""
seen = set()
while isinstance(obj, dict) and '$ref' in obj:
ref = obj['$ref']
if ref in seen or not ref.startswith('#/'):
break
seen.add(ref)
node = self.spec
for part in ref[2:].split('/'):
node = node.get(part, {}) if isinstance(node, dict) else {}
obj = node
return obj
def collect_schema_refs(self, obj: Any, found: Optional[set] = None) -> set:
"""Find all component schemas referenced (transitively) by an object.
References to other component types (e.g. responses or parameters)
are followed, so that the schemas they use are also included.
"""
found = set() if found is None else found
stack = [obj]
visited = set()
while stack:
node = stack.pop()
if isinstance(node, list):
stack.extend(node)
continue
if not isinstance(node, dict):
continue
ref = node.get('$ref')
if isinstance(ref, str) and ref not in visited:
visited.add(ref)
if ref.startswith('#/components/schemas/'):
found.add(self.ref_name(ref))
stack.append(self.resolve(node))
stack.extend(v for k, v in node.items() if k != '$ref')
return found
# ------------------------------------------------------------------ #
# Type descriptions
# ------------------------------------------------------------------ #
def type_str(self, schema: Any) -> str:
"""Return a short (Markdown) description of a schema's type."""
if not isinstance(schema, dict):
return ''
if '$ref' in schema:
ref = schema['$ref']
if ref.startswith('#/components/schemas/'):
name = self.ref_name(ref)
return f'[{name}](#{schema_anchor(name)})'
return self.type_str(self.resolve(schema))
for key, joiner in (('allOf', ' & '), ('oneOf', ' or '), ('anyOf', ' or ')):
if key in schema:
options = [self.type_str(s) for s in schema[key]]
return joiner.join(o for o in options if o) or 'any'
schema_type = schema.get('type')
if schema_type == 'array':
return f'array[{self.type_str(schema.get("items", {})) or "any"}]'
if schema_type == 'object' or (not schema_type and 'properties' in schema):
extra = schema.get('additionalProperties')
if isinstance(extra, dict) and extra:
return f'object[string, {self.type_str(extra) or "any"}]'
return 'object'
if not schema_type:
return 'any'
if fmt := schema.get('format'):
return f'{schema_type}({fmt})'
return schema_type
def merged(self, schema: dict) -> dict:
"""Flatten 'allOf' wrappers so that flags such as 'readOnly' are visible."""
if not isinstance(schema, dict):
return {}
result = {k: v for k, v in schema.items() if k != 'allOf'}
for sub in schema.get('allOf', []):
sub = self.resolve(sub)
if isinstance(sub, dict):
for k, v in sub.items():
result.setdefault(k, v)
return result
def constraints(self, schema: dict, description: str = '') -> list[str]:
"""Return a list of human readable constraints for a schema.
Arguments:
schema: The schema to describe
description: Accompanying description text. Enum values are not
repeated if the description already lists them all.
"""
notes = []
enum_listed = all(
f'`{v}`' in (description or '') for v in schema.get('enum', []) if v
)
if 'enum' in schema and not enum_listed:
values = ', '.join(inline_code(json.dumps(v)) for v in schema['enum'])
notes.append(f'One of: {values}')
for key, label in (
('minLength', 'Min length'),
('maxLength', 'Max length'),
('minimum', 'Minimum'),
('maximum', 'Maximum'),
('minItems', 'Min items'),
('maxItems', 'Max items'),
):
if key in schema:
notes.append(f'{label}: {inline_code(schema[key])}')
if 'pattern' in schema:
notes.append(f'Pattern: {inline_code(schema["pattern"])}')
if 'default' in schema:
notes.append(f'Default: {inline_code(json.dumps(schema["default"]))}')
return notes
# ------------------------------------------------------------------ #
# Example generation
# ------------------------------------------------------------------ #
def example(
self, schema: Any, mode: str = 'response', depth: int = 0, stack=()
) -> Any:
"""Generate an example value for a schema.
Arguments:
schema: The schema to generate an example for
mode: 'request' (omit read-only fields) or 'response' (omit write-only fields)
depth: Current nesting depth
stack: Component names currently being expanded (cycle protection)
"""
if not isinstance(schema, dict) or depth > EXAMPLE_MAX_DEPTH:
return None
if '$ref' in schema:
name = self.ref_name(schema['$ref'])
if name in stack:
return {}
return self.example(self.resolve(schema), mode, depth, (*stack, name))
if 'example' in schema:
return schema['example']
if 'allOf' in schema:
result = {}
for sub in schema['allOf']:
value = self.example(sub, mode, depth, stack)
if isinstance(value, dict):
result.update(value)
elif value is not None:
return value
return result
for key in ('oneOf', 'anyOf'):
if key in schema:
# Prefer the first option which is not a 'null' or 'blank' variant
for sub in schema[key]:
value = self.example(sub, mode, depth, stack)
if value not in (None, ''):
return value
return None
if 'default' in schema:
return schema['default']
if 'enum' in schema:
options = [v for v in schema['enum'] if v not in (None, '')]
return options[0] if options else None
schema_type = schema.get('type')
if schema_type == 'object' or 'properties' in schema:
result = {}
for name, prop in schema.get('properties', {}).items():
flags = self.merged(prop)
if mode == 'request' and flags.get('readOnly'):
continue
if mode == 'response' and flags.get('writeOnly'):
continue
result[name] = self.example(prop, mode, depth + 1, stack)
return result
if schema_type == 'array':
item = self.example(schema.get('items', {}), mode, depth + 1, stack)
return [] if item is None else [item]
if schema_type == 'string':
return FORMAT_EXAMPLES.get(schema.get('format'), 'string')
if schema_type == 'integer':
return 0
if schema_type == 'number':
return 0.0
if schema_type == 'boolean':
return False
return None
def example_block(self, schema: dict, mode: str, title: str) -> list[str]:
"""Render a collapsible JSON example for the given schema."""
value = self.example(schema, mode)
if value is None:
return []
body = json.dumps(value, indent=2)
lines = [f'??? example "{title}"', ' ```json']
lines += [' ' + line for line in body.splitlines()]
lines += [' ```', '']
return lines
# ------------------------------------------------------------------ #
# Operations
# ------------------------------------------------------------------ #
@staticmethod
def security_names(security: Optional[list]) -> tuple:
"""Return a sorted tuple of security scheme names for an operation."""
if not security:
return ()
names = set()
for requirement in security:
names.update(requirement.keys())
return tuple(sorted(names))
def render_security(self, names: tuple) -> str:
"""Render a list of security schemes as Markdown."""
if not names:
return 'No authentication required'
return ', '.join(inline_code(n) for n in names)
def render_parameters(self, parameters: list) -> list[str]:
"""Render the parameters of an operation as a table."""
if not parameters:
return []
lines = [
'**Parameters**',
'',
'| Name | In | Type | Required | Description |',
'| --- | --- | --- | --- | --- |',
]
for param in parameters:
param = self.resolve(param)
schema = param.get('schema', {})
notes = [escape_cell(param.get('description', ''))]
notes += self.constraints(
self.merged(self.resolve(schema)), param.get('description', '')
)
description = '<br>'.join(n for n in notes if n)
lines.append(
f'| {inline_code(param.get("name", ""))} '
f'| {param.get("in", "")} '
f'| {self.type_str(schema)} '
f'| {"Yes" if param.get("required") else "No"} '
f'| {description} |'
)
return [*lines, '']
def render_request_body(self, body: dict) -> list[str]:
"""Render the request body of an operation."""
body = self.resolve(body)
content = body.get('content', {})
if not content:
return []
content_types = ', '.join(inline_code(c) for c in content)
required = ' (required)' if body.get('required') else ''
# Prefer the JSON representation for documentation purposes
media = content.get('application/json') or next(iter(content.values()))
schema = media.get('schema', {})
lines = [
f'**Request body**{required}: {self.type_str(schema)}',
'',
f'Content types: {content_types}',
'',
]
lines += self.example_block(schema, 'request', 'Example request body')
return lines
def render_responses(self, responses: dict) -> list[str]:
"""Render the responses of an operation."""
if not responses:
return []
lines = [
'**Responses**',
'',
'| Status | Description | Schema |',
'| --- | --- | --- |',
]
examples = []
for status, response in responses.items():
response = self.resolve(response)
content = response.get('content', {})
media = content.get('application/json') or (
next(iter(content.values())) if content else {}
)
schema = media.get('schema', {}) if media else {}
lines.append(
f'| {inline_code(status)} '
f'| {escape_cell(response.get("description", ""))} '
f'| {self.type_str(schema) if schema else ""} |'
)
# Provide an example for successful JSON responses only
if schema and str(status).startswith('2') and not examples:
examples = self.example_block(
schema, 'response', f'Example response ({status})'
)
return [*lines, '', *examples]
def render_operation(
self, path: str, method: str, operation: dict, default_security: tuple
) -> list[str]:
"""Render a single API operation (path + method)."""
anchor = operation_anchor(method, path)
label = method.upper()
lines = [
f'### <span class="api-method api-method-{method}">{label}</span> '
f'{inline_code(path)} {{#{anchor}}}',
'',
]
if operation.get('deprecated'):
lines += [
'!!! warning "Deprecated"',
' This endpoint is deprecated.',
'',
]
if summary := operation.get('summary'):
lines += [f'**{escape_text(summary).strip()}**', '']
if description := operation.get('description'):
lines += [escape_text(description).strip(), '']
security = self.security_names(operation.get('security'))
if security != default_security:
lines += [f'**Authentication**: {self.render_security(security)}', '']
lines += self.render_parameters(operation.get('parameters', []))
lines += self.render_request_body(operation.get('requestBody', {}))
lines += self.render_responses(operation.get('responses', {}))
return lines
# ------------------------------------------------------------------ #
# Component schemas
# ------------------------------------------------------------------ #
def render_schema(self, name: str) -> list[str]:
"""Render a single named component schema."""
schema = self.schemas.get(name, {})
lines = [f'### {name} {{#{schema_anchor(name)}}}', '']
if description := schema.get('description'):
lines += [escape_text(description).strip(), '']
properties = schema.get('properties', {})
if properties:
required = set(schema.get('required', []))
lines += [
'| Field | Type | Required | Description |',
'| --- | --- | --- | --- |',
]
for field, prop in properties.items():
flags = self.merged(prop)
resolved = self.merged(self.resolve(prop))
notes = []
badges = []
if flags.get('readOnly'):
badges.append('read-only')
if flags.get('writeOnly'):
badges.append('write-only')
if flags.get('nullable'):
badges.append('nullable')
if badges:
notes.append(' '.join(f'*{b}*' for b in badges))
if title := flags.get('title'):
if title.lower() != field.replace('_', ' ').lower():
notes.append(f'**{escape_cell(title)}**')
field_description = flags.get('description') or resolved.get(
'description'
)
notes.append(escape_cell(field_description))
# Constraints of referenced schemas are documented on that schema
notes += self.constraints(flags, field_description)
lines.append(
f'| {inline_code(field)} '
f'| {self.type_str(prop)} '
f'| {"Yes" if field in required else "No"} '
f'| {"<br>".join(n for n in notes if n)} |'
)
lines.append('')
elif 'enum' in schema:
base_type = self.type_str({k: v for k, v in schema.items() if k != 'enum'})
lines += [f'Type: {base_type}', '']
# Only list the values if the description does not already do so
if self.constraints({'enum': schema['enum']}, description or ''):
lines += ['| Value |', '| --- |']
lines += [f'| {inline_code(json.dumps(v))} |' for v in schema['enum']]
lines.append('')
else:
lines += [f'Type: {self.type_str(schema)}', '']
if notes := self.constraints(schema):
lines += ['<br>'.join(notes), '']
return lines
# ------------------------------------------------------------------ #
# Page rendering
# ------------------------------------------------------------------ #
def default_security(self, paths: dict) -> tuple:
"""Return the most common set of security schemes across the given paths."""
counts = {}
for methods in paths.values():
for method, operation in methods.items():
if method in HTTP_METHODS:
key = self.security_names(operation.get('security'))
counts[key] = counts.get(key, 0) + 1
if not counts:
return ()
return max(counts, key=counts.get)
def render_page(self, title: str, paths: dict) -> str:
"""Render a full documentation page for a subset of API paths.
Arguments:
title: The title of this section of the API
paths: Dict of {path: {method: operation}} items to render
"""
info = self.spec.get('info', {})
default_security = self.default_security(paths)
lines = [
'---',
f'title: {json.dumps(title)}',
# Schema text must never be interpreted as Jinja2 template code
'render_macros: false',
'---',
'',
f'The *{escape_text(title)}* section of the InvenTree API schema is documented below.',
'',
f'!!! info "API Version {escape_text(info.get("version", ""))}"',
' This page was generated automatically from the InvenTree API schema.',
'',
]
if default_security:
lines += [
'## Authentication',
'',
'Unless otherwise noted, endpoints on this page accept the following authentication methods: '
+ self.render_security(default_security)
+ '. Refer to the [API documentation](../index.md#authentication) for more information.',
'',
]
lines += ['## Endpoints', '']
referenced = set()
for path in sorted(paths):
methods = paths[path]
# Parameters may also be declared at the path level (shared by all methods)
path_params = methods.get('parameters', [])
for method in HTTP_METHODS:
if operation := methods.get(method):
if path_params:
operation = {
**operation,
'parameters': path_params + operation.get('parameters', []),
}
lines += self.render_operation(
path, method, operation, default_security
)
self.collect_schema_refs(operation, referenced)
if referenced:
lines += ['## Schemas', '']
for name in sorted(referenced, key=str.lower):
lines += self.render_schema(name)
return '\n'.join(lines).rstrip() + '\n'
-1
View File
@@ -6,6 +6,5 @@ mkdocs-git-revision-date-localized-plugin>=1.6.0,<2.0
mkdocs-redirects
mkdocs-simple-hooks
mkdocs-include-markdown-plugin
neoteroi-mkdocs
mkdocstrings[python]
mkdocs-mermaid2-plugin
+1 -53
View File
@@ -1,9 +1,5 @@
# This file was autogenerated by uv via the following command:
# uv pip compile docs/requirements.in -o docs/requirements.txt -c src/backend/requirements.txt
anyio==4.15.1 \
--hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101 \
--hash=sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94
# via httpx
babel==2.18.0 \
--hash=sha256:b80b99a14bd085fcacfa15c9165f651fbb3406e66cc603abf11c5750937c992d \
--hash=sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35
@@ -33,8 +29,6 @@ certifi==2026.10.23 \
--hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1
# via
# -c src/backend/requirements.txt
# httpcore
# httpx
# requests
charset-normalizer==3.5.2 \
--hash=sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e \
@@ -217,7 +211,6 @@ click==8.5.0 \
--hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34
# via
# mkdocs
# neoteroi-mkdocs
# properdocs
colorama==0.4.6 \
--hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \
@@ -227,14 +220,6 @@ editorconfig==0.17.1 \
--hash=sha256:1eda9c2c0db8c16dbd50111b710572a5e6de934e39772de1959d41f64fc17c82 \
--hash=sha256:23c08b00e8e08cc3adcddb825251c497478df1dada6aefeb01e626ad37303745
# via jsbeautifier
essentials==1.1.9 \
--hash=sha256:71ef161e0e27ef77cd6f5fc05e0b8688a575fcab870c01c95940f832e321dfbb \
--hash=sha256:7fbea3a518cbeafe5374fb7e2ea2c15a109e8a7fd1eaab62ae87cbd1b3b1e8d0
# via essentials-openapi
essentials-openapi==1.4.0 \
--hash=sha256:578c81501ccf6d18c0839d60636214fbd051f0ef37f1d207d4e3c92de2aac008 \
--hash=sha256:86d879c32734248ad52482a90ee89a32883bce348b4edd323c01556b505b45b9
# via neoteroi-mkdocs
ghp-import==2.1.0 \
--hash=sha256:8337dd7b50877f163d4c0289bc1f1c7f127550241988d568c1db512c4324a619 \
--hash=sha256:9c535c4c61193c2df8871222567d7fd7e5014d835f97dc7b7439069e2413d343
@@ -253,31 +238,17 @@ griffelib==2.4.1 \
--hash=sha256:40c028dd2e623f464423f0e11e3c553158f1cf4f1368239a370534d73e1407ff \
--hash=sha256:76bc562f936ad1ce198d2cf6d0731bd5c92a7d934b69ef828ef22ee0ffdb62ce
# via mkdocstrings-python
h11==0.16.0 \
--hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \
--hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86
# via httpcore
hjson==3.1.0 \
--hash=sha256:55af475a27cf83a7969c808399d7bccdec8fb836a07ddbd574587593b9cdcf75 \
--hash=sha256:65713cdcf13214fb554eb8b4ef803419733f4f5e551047c9b711098ab7186b89
# via
# mkdocs-macros-plugin
# super-collections
httpcore==1.0.9 \
--hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55 \
--hash=sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8
# via httpx
httpx==0.28.1 \
--hash=sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc \
--hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad
# via neoteroi-mkdocs
idna==3.20 \
--hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \
--hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
# via
# -c src/backend/requirements.txt
# anyio
# httpx
# requests
jinja2==3.1.6 \
--hash=sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d \
@@ -288,7 +259,6 @@ jinja2==3.1.6 \
# mkdocs-macros-plugin
# mkdocs-material
# mkdocstrings
# neoteroi-mkdocs
# properdocs
jsbeautifier==2.0.3 \
--hash=sha256:9579d4e9dbaa00383f3efdff4c98c8140bb85ba319398e8b97cdaba27abd6ba3 \
@@ -305,10 +275,6 @@ markdown==3.11.2 \
# mkdocstrings
# properdocs
# pymdown-extensions
markdown-it-py==4.2.0 \
--hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \
--hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a
# via rich
markupsafe==3.0.4 \
--hash=sha256:007e1ffd9bf65bb6ee96df7b258fc632a4868dd5566037986c64781f35a36e98 \
--hash=sha256:02fa4acbc6a3fc5c693c34d4dd8c1130b7fe99cc915181b0ddd6f72aeb296002 \
@@ -463,16 +429,11 @@ markupsafe==3.0.4 \
--hash=sha256:fdb4ca07ab75ffadab4a8b135ad59cdbb3156b99310f3d565370da74a15d6bd3
# via
# -c src/backend/requirements.txt
# essentials-openapi
# jinja2
# mkdocs
# mkdocs-autorefs
# mkdocstrings
# properdocs
mdurl==0.1.2 \
--hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \
--hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba
# via markdown-it-py
mergedeep==1.3.4 \
--hash=sha256:0096d52e9dad9939c3d975a774666af186eda617e6ca84df4c94dec30004f2a8 \
--hash=sha256:70775750742b25c0d8f36c55aed03d24c3384d17c951b3175d898bd778ef0307
@@ -493,7 +454,6 @@ mkdocs==1.6.1 \
# mkdocs-redirects
# mkdocs-simple-hooks
# mkdocstrings
# neoteroi-mkdocs
mkdocs-autorefs==1.4.5 \
--hash=sha256:68ee484e0800f3ba50cda1bc4a94293adbdfcc010243c322b3f5d66e15d06770 \
--hash=sha256:856f75b327b7717923ce06267094650689a510a748c48657f5333965950c2788
@@ -546,10 +506,6 @@ mkdocstrings-python==2.0.10 \
--hash=sha256:4a3aaeebb25ba5ae57a8f9e75432fe4571984889602f2b2f7d672faa760e9062 \
--hash=sha256:5e34ae56b2f20a57807ee479d603ddc5ec7cc6d2252c4c177754627ef2d3b833
# via mkdocstrings
neoteroi-mkdocs==1.2.0 \
--hash=sha256:58e25cb1b9db093ffa8d12bdb33264bf567cac30fb964b56e0a493efa749ad6e \
--hash=sha256:91b6aa95a4e46c9bb93e00e021d2044cb0c7d80c0b4600434ff8f440d613a0a8
# via -r docs/requirements.in
packaging==26.3 \
--hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \
--hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c
@@ -586,9 +542,7 @@ properdocs==1.6.7 \
pygments==2.21.0 \
--hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \
--hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c
# via
# mkdocs-material
# rich
# via mkdocs-material
pymdown-extensions==12.3 \
--hash=sha256:345493a8e3497e24382902903a1c43a28e34a52f2b7571a1c9641429b820ca74 \
--hash=sha256:a7f2a4e0bc60c6e6babfa7922cfb3b01cd640eb00fb208f3c582e12bae00ea67
@@ -679,7 +633,6 @@ pyyaml==6.0.3 \
--hash=sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0
# via
# -c src/backend/requirements.txt
# essentials-openapi
# mkdocs
# mkdocs-get-deps
# mkdocs-macros-plugin
@@ -700,10 +653,6 @@ requests==2.34.2 \
# mkdocs-macros-plugin
# mkdocs-material
# mkdocs-mermaid2-plugin
rich==15.0.0 \
--hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \
--hash=sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36
# via neoteroi-mkdocs
setuptools==84.2.1 \
--hash=sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc \
--hash=sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2
@@ -737,7 +686,6 @@ typing-extensions==4.16.0 \
--hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5
# via
# -c src/backend/requirements.txt
# anyio
# beautifulsoup4
urllib3==2.8.0 \
--hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \