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())