Files
WonderQ-Project/WonderQ-Admin/app/main.py
duanshuwen e082bd2d98 feat(api): 实现三端统一的JSON API响应契约
- 新增`api_response.py`统一响应封装工具类,提供标准成功/错误响应构造方法
- 重构WonderQ-Admin全局异常处理器,将所有异常转换为标准响应格式
- 修改所有公共和管理端接口的返回逻辑,统一使用`code`(与HTTP状态码一致)、`msg`和`data`的三层结构
- 新增`api-response-contract.md`文档,定义完整的三端统一JSON响应规范
- 更新所有领域API文档,明确业务数据需位于`data`字段内,补充响应格式说明
- 为WonderQ-MiniAPP和WonderQ-Admin-UI新增响应解析逻辑和类型定义,自动完成协议校验和错误处理
- 更新所有测试用例,适配新的响应结构确保接口符合契约要求
- 新增`module-config-api.md`模块配置API文档,补充站点模块配置的接口约定
- 更新项目README文档,调整文档分类顺序将响应契约置于首位
2026-08-19 22:02:20 +08:00

49 lines
1.8 KiB
Python

import logging
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from .api_response import error_response, exception_parts
from .config import get_settings
from .routers import admin, public
def create_app() -> FastAPI:
settings = get_settings()
logging.basicConfig(level=settings.log_level.upper())
app = FastAPI(title="WonderQ Admin API")
origins = ["*"] if settings.cors_origins == "*" else [item.strip() for item in settings.cors_origins.split(",") if item.strip()]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(_request: Request, exc: RequestValidationError):
first = exc.errors()[0] if exc.errors() else {}
return error_response(
400,
str(first.get("msg", "请求参数不正确")),
error_code="VALIDATION_ERROR",
)
@app.exception_handler(HTTPException)
async def http_exception_handler(_request: Request, exc: HTTPException):
message, error_code, details = exception_parts(exc.detail)
return error_response(exc.status_code, message, error_code=error_code, details=details)
@app.exception_handler(Exception)
async def unhandled_exception_handler(request: Request, exc: Exception):
request.app.logger.exception(exc) if hasattr(request.app, "logger") else logging.exception(exc)
return error_response(500, "服务暂时不可用", error_code="INTERNAL_SERVER_ERROR")
app.include_router(public.router)
app.include_router(admin.router)
return app
app = create_app()