Skip to content

Commit 73a8c5b

Browse files
author
Michael "M3" Lasevich
committed
Add cli command to generate openapi schema from app without running it
1 parent 1844ba1 commit 73a8c5b

File tree

6 files changed

+164
-3
lines changed

6 files changed

+164
-3
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,12 @@ It will listen on the IP address `0.0.0.0`, which means all the available IP add
8989

9090
In most cases you would (and should) have a "termination proxy" handling HTTPS for you on top, this will depend on how you deploy your application, your provider might do this for you, or you might need to set it up yourself. You can learn more about it in the <a href="https://fastapi.tiangolo.com/deployment/" class="external-link" target="_blank">FastAPI Deployment documentation</a>.
9191

92+
## `fastapi schema`
93+
94+
When you run `fastapi schema`, it will generate a swagger/openapi document.
95+
96+
This document will be output to stderr by default, however `--output <filename>` option can be used to write output into file. You can control the format of the JSON file by specifying indent level with `--indent #`. If set to 0, JSON will be in the minimal/compress form. Default is 2 spaces.
97+
9298
## License
9399

94100
This project is licensed under the terms of the MIT license.

src/fastapi_cli/cli.py

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import json
12
import logging
3+
import sys
24
from pathlib import Path
35
from typing import Any, List, Union
46

@@ -7,7 +9,7 @@
79
from rich.tree import Tree
810
from typing_extensions import Annotated
911

10-
from fastapi_cli.discover import get_import_data
12+
from fastapi_cli.discover import get_app, get_import_data
1113
from fastapi_cli.exceptions import FastAPICLIException
1214

1315
from . import __version__
@@ -370,5 +372,42 @@ def run(
370372
)
371373

372374

375+
@app.command()
376+
def schema(
377+
path: Annotated[
378+
Union[Path, None],
379+
typer.Argument(
380+
help="A path to a Python file or package directory (with [blue]__init__.py[/blue] files) containing a [bold]FastAPI[/bold] app. If not provided, a default set of paths will be tried."
381+
),
382+
] = None,
383+
*,
384+
app: Annotated[
385+
Union[str, None],
386+
typer.Option(
387+
help="The name of the variable that contains the [bold]FastAPI[/bold] app in the imported module or package. If not provided, it is detected automatically."
388+
),
389+
] = None,
390+
output: Annotated[
391+
Union[str, None],
392+
typer.Option(
393+
help="The filename to write schema to. If not provided, write to stderr."
394+
),
395+
] = None,
396+
indent: Annotated[
397+
int,
398+
typer.Option(help="JSON format indent. If 0, disable pretty printing"),
399+
] = 2,
400+
) -> Any:
401+
"""Generate schema"""
402+
fastapi_app = get_app(path=path, app_name=app)
403+
schema = fastapi_app.openapi()
404+
405+
stream = open(output, "w") if output else sys.stderr
406+
json.dump(schema, stream, indent=indent if indent > 0 else None)
407+
if output:
408+
stream.close()
409+
return 0
410+
411+
373412
def main() -> None:
374413
app()

src/fastapi_cli/discover.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import importlib
22
import sys
3+
from contextlib import contextmanager
34
from dataclasses import dataclass
45
from logging import getLogger
56
from pathlib import Path
6-
from typing import List, Union
7+
from typing import Iterator, List, Union
78

89
from fastapi_cli.exceptions import FastAPICLIException
910

@@ -41,6 +42,18 @@ class ModuleData:
4142
extra_sys_path: Path
4243
module_paths: List[Path]
4344

45+
@contextmanager
46+
def sys_path(self) -> Iterator[str]:
47+
"""Context manager to temporarily alter sys.path"""
48+
extra_sys_path = str(self.extra_sys_path) if self.extra_sys_path else ""
49+
if extra_sys_path:
50+
logger.debug("Adding %s to sys.path...", extra_sys_path)
51+
sys.path.insert(0, extra_sys_path)
52+
yield extra_sys_path
53+
if extra_sys_path and sys.path and sys.path[0] == extra_sys_path:
54+
logger.debug("Removing %s from sys.path...", extra_sys_path)
55+
sys.path.pop(0)
56+
4457

4558
def get_module_data_from_path(path: Path) -> ModuleData:
4659
use_path = path.resolve()
@@ -130,3 +143,16 @@ def get_import_data(
130143
return ImportData(
131144
app_name=use_app_name, module_data=mod_data, import_string=import_string
132145
)
146+
147+
148+
def get_app(
149+
*, path: Union[Path, None] = None, app_name: Union[str, None] = None
150+
) -> FastAPI:
151+
"""Get the FastAPI app instance from the given path and app name."""
152+
import_data: ImportData = get_import_data(path=path, app_name=app_name)
153+
mod_data, use_app_name = import_data.module_data, import_data.app_name
154+
with mod_data.sys_path():
155+
mod = importlib.import_module(mod_data.module_import_str)
156+
app = getattr(mod, use_app_name)
157+
## get_import_string_parts guarantees app is FastAPI object
158+
return app # type: ignore[no-any-return]

tests/assets/openapi.json

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"openapi": "3.1.0",
3+
"info": {
4+
"title": "FastAPI",
5+
"version": "0.1.0"
6+
},
7+
"paths": {
8+
"/": {
9+
"get": {
10+
"summary": "App Root",
11+
"operationId": "app_root__get",
12+
"responses": {
13+
"200": {
14+
"description": "Successful Response",
15+
"content": {
16+
"application/json": {
17+
"schema": {}
18+
}
19+
}
20+
}
21+
}
22+
}
23+
}
24+
}
25+
}

tests/test_cli.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import os
12
import subprocess
23
import sys
34
from pathlib import Path
@@ -7,6 +8,7 @@
78
from typer.testing import CliRunner
89

910
from fastapi_cli.cli import app
11+
from fastapi_cli.exceptions import FastAPICLIException
1012
from fastapi_cli.utils.cli import get_uvicorn_log_config
1113
from tests.utils import changing_dir
1214

@@ -15,6 +17,13 @@
1517
assets_path = Path(__file__).parent / "assets"
1618

1719

20+
def read_file(filename: str, strip: bool = True) -> str:
21+
"""Read file and return content as string"""
22+
with open("openapi.json") as stream:
23+
data = stream.read()
24+
return data.strip() if data and strip else data
25+
26+
1827
def test_dev() -> None:
1928
with changing_dir(assets_path):
2029
with patch.object(uvicorn, "run") as mock_run:
@@ -251,6 +260,51 @@ def test_dev_help() -> None:
251260
assert "Use multiple worker processes." not in result.output
252261

253262

263+
def test_schema() -> None:
264+
with changing_dir(assets_path):
265+
with open("openapi.json") as stream:
266+
expected = stream.read().strip()
267+
assert expected != "", "Failed to read expected result"
268+
result = runner.invoke(app, ["schema", "single_file_app.py"])
269+
assert result.exit_code == 0, result.output
270+
assert expected in result.output, result.output
271+
272+
273+
def test_schema_file() -> None:
274+
with changing_dir(assets_path):
275+
filename = "unit-test.json"
276+
expected = read_file("openapi.json", strip=True)
277+
assert expected != "", "Failed to read expected result"
278+
result = runner.invoke(
279+
app, ["schema", "single_file_app.py", "--output", filename]
280+
)
281+
assert os.path.isfile(filename)
282+
actual = read_file(filename, strip=True)
283+
os.remove(filename)
284+
assert result.exit_code == 0, result.output
285+
assert expected == actual
286+
287+
288+
def test_schema_invalid_path() -> None:
289+
with changing_dir(assets_path):
290+
result = runner.invoke(app, ["schema", "invalid/single_file_app.py"])
291+
assert result.exit_code == 1, result.output
292+
assert isinstance(result.exception, FastAPICLIException)
293+
assert "Path does not exist invalid/single_file_app.py" in str(result.exception)
294+
295+
296+
#
297+
#
298+
# def test_schema_invalid_package() -> None:
299+
# with changing_dir(assets_path):
300+
# result = runner.invoke(
301+
# app, ["schema", "broken_package/mod/app.py"]
302+
# )
303+
# assert result.exit_code == 1, result.output
304+
# assert isinstance(result.exception, ImportError)
305+
# assert "attempted relative import beyond top-level package" in str(result.exception)
306+
307+
254308
def test_run_help() -> None:
255309
result = runner.invoke(app, ["run", "--help"])
256310
assert result.exit_code == 0, result.output

tests/test_utils_package.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import pytest
44
from pytest import CaptureFixture
55

6-
from fastapi_cli.discover import get_import_data
6+
from fastapi_cli.discover import get_app, get_import_data
77
from fastapi_cli.exceptions import FastAPICLIException
88
from tests.utils import changing_dir
99

@@ -169,6 +169,17 @@ def test_broken_package_dir(capsys: CaptureFixture[str]) -> None:
169169
assert "Ensure all the package directories have an __init__.py file" in captured.out
170170

171171

172+
def test_get_app_broken_package_dir(capsys: CaptureFixture[str]) -> None:
173+
with changing_dir(assets_path):
174+
# TODO (when deprecating Python 3.8): remove ValueError
175+
with pytest.raises((ImportError, ValueError)):
176+
get_app(path=Path("broken_package/mod/app.py"))
177+
178+
captured = capsys.readouterr()
179+
assert "Import error:" in captured.out
180+
assert "Ensure all the package directories have an __init__.py file" in captured.out
181+
182+
172183
def test_package_dir_no_app() -> None:
173184
with changing_dir(assets_path):
174185
with pytest.raises(FastAPICLIException) as e:

0 commit comments

Comments
 (0)