v0.166.0
 1import sys
 2
 3import click
 4from plain.cli import register_cli
 5from plain.runtime import settings
 6from plain.utils.module_loading import import_string
 7
 8from .openapi.generator import OpenAPISchemaGenerator
 9from .openapi.validation import OpenAPIValidationError, validate_openapi_schema
10
11
12@register_cli("api")
13@click.group()
14def cli() -> None:
15    """API commands"""
16
17
18@cli.command()
19@click.option(
20    "--validate",
21    is_flag=True,
22    help="Validate the OpenAPI schema (requires openapi-spec-validator).",
23)
24@click.option("--indent", default=2, help="Indentation level for JSON and YAML output.")
25@click.option(
26    "--format",
27    default="json",
28    help="Output format (json or yaml).",
29    type=click.Choice(["json", "yaml"]),
30)
31def generate_openapi(validate: bool, indent: int, format: str) -> None:
32    if not settings.API_OPENAPI_ROUTER:
33        click.secho("No OpenAPI URL router configured.", fg="red", err=True)
34        sys.exit(1)
35
36    url_router_class = import_string(settings.API_OPENAPI_ROUTER)
37
38    schema = OpenAPISchemaGenerator(url_router_class)
39
40    if format == "json":
41        print(schema.as_json(indent=indent))
42    elif format == "yaml":
43        print(schema.as_yaml(indent=indent))
44
45    if validate:
46        click.secho("\nOpenAPI schema validation: ", err=True, nl=False)
47        try:
48            validate_openapi_schema(schema.schema)
49        except OpenAPIValidationError as exc:
50            click.secho("Failed", fg="red", err=True)
51            click.secho(str(exc), fg="yellow", err=True)
52            sys.exit(1)
53        click.secho("Success", fg="green", err=True)