fastAPI swagger报错的一种解决方案

项目描述

最近有一个需要快速部署的项目,比较急,所以使用了python的fastAPI,说直接点就是面向DB编程了:-)
但是swagger打不开,因为框架是同事搭的,第一个版本是可以使用的,可是后来我拉代码之后,就莫名其妙的打不开了。
image.png

报错内容

Unable to render this definition

The provided definition does not specify a valid version field.

Please indicate a valid Swagger or OpenAPI version field. Supported version fields are `swagger: "2.0"` and those that match `openapi: 3.0.n` (for example, `openapi: 3.0.0`).

main.py

from fastapi import Depends, FastAPI
from dependencies import get_query_token, get_token_header
#导入具有 APIRouter 的其他子模块
from internal import admin
from routers import items, users
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import (
    get_redoc_html,
    get_swagger_ui_html,
    get_swagger_ui_oauth2_redirect_html,
)

# app = FastAPI(dependencies=[Depends(get_query_token)])
app = FastAPI(title='xxxxxx',docs_url=None, redoc_url=None)
# app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

解决办法

本地的包我没有动过,开发服务器上的就不知道了,根据报错大概能猜出来是版本的问题,但是翻了一下文档,发现是这样解释的

The path to the automatic interactive API documentation. It is handled in the browser by Swagger UI.The default URL is /docs. You can disable it by setting it to None.If openapi_url is set to None, this will be automatically disabled.

这是关闭了的意思吗?但是发现openapi.json是有响应的
image.png

尝试去掉docs_url=None, 参数,发现问题解决了,但是为什么解决了呢?

决定查看一下服务器上的openapi版本,发现版本不高,我本的的是最新版本的,尝试降级,也解决了问题。

最后发现低版本的fastapiOAS版本是3,而最新版的是3.1,看来还是版本不一致导致的。

结论

尝试去掉main.py中的docs_url=None, 参数

降低fastapi版本

评论 0

还没有评论,来说点什么吧。

提交后需要审核才会公开。