8000 feat: Add markdown doc based on app's openapi specification by Iito · Pull Request #43 · fastapi/fastapi-cli · GitHub
[go: up one dir, main page]

Skip to content

feat: Add markdown doc based on app's openapi specification #43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
  • Loading branch information
pre-commit-ci[bot] committed Jul 10, 2024
commit c4e42b518aaebb36ce922ead4f098e66083c5283
9 changes: 6 additions & 3 deletions src/fastapi_cli/cli.py
8000
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@
from rich.panel import Panel
from typing_extensions import Annotated

from fastapi_cli.discover import get_import_string, get_api_spec
from fastapi_cli.discover import get_api_spec, get_import_string
from fastapi_cli.exceptions import FastAPICLIException

from . import __version__
from .logging import setup_logging
from .utils import generate_markdown

app = typer.Typer(rich_markup_mode="rich")

setup_logging()
Expand Down Expand Up @@ -272,6 +273,7 @@ def run(
proxy_headers=proxy_headers,
)


@app.command()
def doc(
path: Annotated[
Expand All @@ -291,9 +293,9 @@ def doc(
Union[str, None],
typer.Option(
help="The title to use for the generated markdown file. If not provided, it is detected automatically."
)
),
] = None,
) -> None:
) -> None:
"""
Generate [bold]FastAPI[/bold] API docs. 📚

Expand All @@ -320,5 +322,6 @@ def doc(
with open(f"{title.upper()}.md", "w") as f:
f.write(markdown)


def main() -> None:
app()
14 changes: 9 additions & 5 deletions src/fastapi_cli/discover.py
8000
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import importlib
import inspect
import sys
from dataclasses import dataclass
from logging import getLogger
from pathlib import Path
from typing import Union
import inspect

from rich import print
from rich.padding import Padding
Expand Down Expand Up @@ -168,13 +168,17 @@ def get_import_string(
logger.info(f"Using import string [b green]{import_string}[/b green]")
return import_string


def get_api_spec(import_string: str) -> dict:
app_module, app_name = import_string.replace("/", ".").rsplit(":", 1)
app = getattr(__import__(app_module, fromlist=[app_name]), app_name)
signature = inspect.signature(get_openapi)
props = {prop.name: getattr(app, prop.name, None) for prop in signature.parameters.values()}

props = {
prop.name: getattr(app, prop.name, None)
for prop in signature.parameters.values()
}

props["webhooks"] = None
spec = get_openapi(**props)
return spec

return spec
14 changes: 10 additions & 4 deletions src/fastapi_cli/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ def generate_markdown(api_spec, title):
schema = param.get("schema", {})
schema_str = f"`type: {schema.get('type', 'N/A')}`<br>`title: {schema.get('title', 'N/A')}`"
if "description" in schema:
schema_str += f"<br>`description: {schema.get('description', 'N/A')}`"
schema_str += (
f"<br>`description: {schema.get('description', 'N/A')}`"
)
if "enum" in schema:
schema_str += f"<br>`enum: {schema.get('enum')}`"
if "default" in schema:
Expand All @@ -50,7 +52,7 @@ def generate_markdown(api_spec, title):
if request_body:
md.append("**Request Body:**")
md.append(f"- **Required:** {request_body.get('required', False)}")
md.append(f"- **Content:**&qu 97B0 ot;)
md.append("- **Content:**")
content = request_body.get("content", {})
for content_type, content_schema in content.items():
md.append(f" - **{content_type}:**")
Expand All @@ -72,7 +74,9 @@ def generate_markdown(api_spec, title):
for content_type, content_schema in content.items():
schema_ref = content_schema.get("schema", {}).get("$ref", "N/A")
content_str += f"{content_type}: `schema: [{schema_ref.split('/')[-1]}](#{schema_ref.split('/')[-1].lower()})`<br>"
md.append(f"| {status} | {description} | {content_str.strip('<br>')} |")
md.append(
f"| {status} | {description} | {content_str.strip('<br>')} |"
)

# Components
components = api_spec.get("components", {}).get("schemas", {})
Expand All @@ -83,7 +87,9 @@ def generate_markdown(api_spec, title):
md.append(f"##### {schema_name}")
md.append(f"- **Type:** {schema_details.get('type', 'N/A')}")
if "required" in schema_details:
md.append(f"- **Required:** {', '.join(schema_details.get('required', []))}")
md.append(
f"- **Required:** {', '.join(schema_details.get('required', []))}"
)
md.append(f"- **Title:** {schema_details.get('title', 'N/A')}")
md.append("- **Properties:**")
properties = schema_details.get("properties", {})
Expand Down
Loading
0