Skip to content

Commands

spec_command(format, output, indent, quiet)

Output the OpenAPI spec to stdout or a file.

Check out the docs for the detailed usage:

https://apiflask.com/openapi/#the-flask-spec-command

Source code in apiflask/commands.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@click.command('spec', short_help='Show the OpenAPI spec.')
@click.option(
    '--format',
    '-f',
    type=click.Choice(['json', 'yaml', 'yml']),
    help='The format of the spec, defaults to SPEC_FORMAT config.',
)
@click.option(
    '--output',
    '-o',
    type=click.Path(),
    help='The file path to the spec file, defaults to LOCAL_SPEC_PATH config.',
)
@click.option(
    '--indent',
    '-i',
    type=int,
    help='The indentation for JSON spec, defaults to LOCAL_SPEC_JSON_INDENT config.',
)
@click.option(
    '--quiet', '-q', type=bool, is_flag=True, help='A flag to suppress printing output to stdout.'
)
@with_appcontext
def spec_command(format, output, indent, quiet):
    """Output the OpenAPI spec to stdout or a file.

    Check out the docs for the detailed usage:

    https://apiflask.com/openapi/#the-flask-spec-command
    """
    spec_format = format or current_app.config['SPEC_FORMAT']
    spec = current_app._get_spec(spec_format)
    output_path = output or current_app.config['LOCAL_SPEC_PATH']
    if indent is None:
        indent = current_app.config['LOCAL_SPEC_JSON_INDENT']
    json_indent = None if indent == 0 else indent

    if spec_format == 'json':
        spec = json.dumps(spec, indent=json_indent)

    # output to stdout
    if not quiet:
        click.echo(spec)

    # output to local file
    if output_path:
        with open(output_path, 'w') as f:
            click.echo(spec, file=f)