fastapi 接口json格式转word

fastapi 接口json格式转word

fastapi api 运行之后 浏览器进入 http://127.0.0.1:8000/redoc 下载接口json

openapi_data 为json文件中的内容,需要把json中的true 修改为True,会在同级目录下生成一个word文档。代码如下:

from docx import Document
from io import BytesIO

openapi_data = {
    "openapi": "3.1.0",
    "info": {
        "title": "FastAPI",
        "version": "0.1.0"
    },
    "paths": {

        "/download-model": {
            "post": {
                "summary": "Download Model",
                "description": "下载训练好的模型文件的API端点。\n\nArgs:\n    request (DownloadRequest): 包含模型文件路径的请求体。 file_path: str  # 文件路径,必须提供\n\nReturns:\n    FileResponse: 返回模型文件流。\n\nRaises:\n    HTTPException: 如果文件不存在,返回404错误。\n    HTTPException: 如果路径无效,返回400错误。",
                "operationId": "download_model_download_model_post",
                "requestBody": {
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/DownloadRequest"
                            }
                        }
                    },
                    "required": True
                },
                "responses": {
                    "200": {
                        "description": "Successful Response",
                        "content": {
                            "application/json": {
                                "schema": {}
                            }
                        }
                    },
                    "422": {
                        "description": "Validation Error",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/HTTPValidationError"
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    "components": {

    }
}

doc = Document()
doc.add_heading('API Documentation', 0)

# Add API information
doc.add_heading('API Information', level=1)
doc.add_paragraph(f"Title: {openapi_data['info']['title']}")
doc.add_paragraph(f"Version: {openapi_data['info']['version']}")

# Add path information
doc.add_heading('API Endpoints', level=1)
for path, methods in openapi_data['paths'].items():
    for method, details in methods.items():
        doc.add_heading(f"{method.upper()} {path}", level=2)
        doc.add_paragraph(f"Summary: {details.get('summary', 'No summary')}")
        doc.add_paragraph(f"Description: {details.get('description', 'No description')}")
        if 'requestBody' in details:
            doc.add_heading('Request Body', level=3)
            for content_type, content in details['requestBody']['content'].items():
                doc.add_paragraph(f"Content-Type: {content_type}")
                schema_ref = content['schema'].get('$ref', None)
                if schema_ref:
                    schema_name = schema_ref.split('/')[-1]
                    schema = openapi_data['components']['schemas'][schema_name]
                    doc.add_paragraph(f"Schema: {schema_name}")
                    doc.add_paragraph(f"Description: {schema.get('description', 'No description')}")
                    doc.add_paragraph(f"Required: {', '.join(schema.get('required', []))}")
                    doc.add_paragraph(f"Properties:")
                    for prop, prop_details in schema.get('properties', {}).items():
                        doc.add_paragraph(f"- {prop} ({prop_details.get('type', 'unknown')}): {prop_details.get('title', '')}")

        if 'responses' in details:
            doc.add_heading('Responses', level=3)
            for status_code, response in details['responses'].items():
                doc.add_paragraph(f"Status Code: {status_code}")
                doc.add_paragraph(f"Description: {response.get('description', 'No description')}")

# Save the document to a BytesIO buffer
buffer = BytesIO()
doc.save(buffer)
buffer.seek(0)

# Save the file to disk (or you can return it as a download in a web app)
with open("api_documentation.docx", "wb") as f:
    f.write(buffer.read())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

trust Tomorrow

感谢支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值