FastAPI文档加Basic Auth后仅显示认证端点,如何展示实际API文档?
问题:FastAPI文档认证后无法展示业务API端点
我通过Basic Auth实现API文档的认证访问,自定义了数据库查询与密码校验逻辑。未配置认证前,/docs可正常展示所有业务API端点(如cliente、produto等);配置完成后,访问/docs仅显示/docs和/openapi.json这两个认证相关端点,无法展示实际业务API的文档。
相关代码
主代码文件
from fastapi import FastAPI from routers import cliente, produto, faturaVenda, autoDocumentation app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) app.include_router(cliente.router) app.include_router(produto.router) app.include_router(faturaVenda.router) app.include_router(autoDocumentation.router) @app.get("/test", tags=["Hello World"]) def hello_world() -> None: return {"Hello my first FastAPI api"}
文档认证端点代码
import sys sys.path.insert(1, "/Users/user/Desktop/Api") from fastapi.openapi.docs import get_swagger_ui_html from fastapi.openapi.utils import get_openapi from authentication.autoDocumentationAuthentication import check_entity_credencials from fastapi import Depends, APIRouter router = APIRouter() @router.get("/docs") async def get_documentation(username: str = Depends(check_entity_credencials)): return get_swagger_ui_html(openapi_url="/openapi.json", title="docs") @router.get("/openapi.json") async def openapi(username: str = Depends(check_entity_credencials)): return get_openapi(title = "FastAPI", version="0.1.0", routes=router.routes)
认证逻辑代码
import sys sys.path.insert(1, "/Users/user/Desktop/project/Api") from fastapi.security import HTTPBasicCredentials, HTTPBasic from fastapi import Depends, HTTPException, status from repository.configuration.databaseConfigurationAndQuery import DatabaseConnectorAndQuery from utils.hasher import hashString, verifyHash security = HTTPBasic() def check_entity_credencials(credentials: HTTPBasicCredentials = Depends(security)): correctEntityId = check_entity_id_in_db(credentials.username) correct_password = check_entity_password_in_db(correctEntityId) if correctEntityId != None and correct_password != None: if verifyHash(credentials.password, correct_password): return credentials.username else: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Password or ID passed is incorrect", headers={"WWW-Authenticate": "Basic"}, )
问题原因
生成OpenAPI文档时,openapi函数里指定了routes=router.routes,这里仅包含当前APIRouter下的两个端点(/docs和/openapi.json),没有包含主应用中注册的业务路由(cliente、produto等),所以Swagger UI只显示这两个认证相关端点。
解决方案
修改文档认证端点代码,在生成OpenAPI文档时传入主应用的所有路由,而不是当前路由实例的路由。
修改后的文档认证端点代码
import sys sys.path.insert(1, "/Users/user/Desktop/Api") from fastapi.openapi.docs import get_swagger_ui_html from fastapi.openapi.utils import get_openapi from authentication.autoDocumentationAuthentication import check_entity_credencials from fastapi import Depends, APIRouter from main import app # 导入主应用的app实例 router = APIRouter() @router.get("/docs") async def get_documentation(username: str = Depends(check_entity_credencials)): return get_swagger_ui_html(openapi_url="/openapi.json", title="docs") @router.get("/openapi.json") async def openapi(username: str = Depends(check_entity_credencials)): return get_openapi(title = "FastAPI", version="0.1.0", routes=app.routes) # 使用app的所有路由
说明
- 确保主应用的文件名为
main.py,如果不是,调整导入路径中的文件名。 - 修改后,/openapi.json会生成包含所有业务路由的OpenAPI文档,Swagger UI(/docs)就能正常展示所有API端点了。
内容的提问来源于stack exchange,提问作者ivaldir
相关产品推荐
相关产品推荐

