Fastapi交互式文档实现方法讲解
# applications.py class FastAPI(Starlette): def __init__( self, *, debug: bool = False, routes: List[BaseRoute] = None, title: str = "FastAPI", description: str = "", version: str = "0.1.0", openapi_url: Optional[str] = "/openapi.json", openapi_prefix: str = "", default_response_class: Type[Response] = JSONResponse, docs_url: Optional[str] = "/docs", redoc_url: Optional[str] = "/redoc", swagger_ui_oauth2_redirect_url: Optional[str] = "/docs/oauth2-redirect", swagger_ui_init_oauth: Optional[dict] = None, middleware: Sequence[Middleware] = None, exception_handlers: Dict[Union[int, Type[Exception]], Callable] = None, on_startup: Sequence[Callable] = None, on_shutdown: Sequence[Callable] = None, **extra: Dict[str, Any], ) -> None: self.default_response_class = default_response_class self._debug = debug self.state = State() self.router: routing.APIRouter = routing.APIRouter( routes, dependency_overrides_provider=self, on_startup=on_startup, on_shutdown=on_shutdown, ) self.exception_handlers = ( {} if exception_handlers is None else dict(exception_handlers) ) self.user_middleware = [] if middleware is None else list(middleware) self.middleware_stack = self.build_middleware_stack() self.title = title self.description = description self.version = version self.openapi_url = openapi_url self.openapi_prefix = openapi_prefix.rstrip("/") self.docs_url = docs_url self.redoc_url = redoc_url self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url self.swagger_ui_init_oauth = swagger_ui_init_oauth self.extra = extra self.dependency_overrides: Dict[Callable, Callable] = {} self.openapi_version = "3.0.2" if self.openapi_url: assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'" assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'" if self.docs_url or self.redoc_url: assert self.openapi_url, "The openapi_url is required for the docs" self.openapi_schema: Optional[Dict[str, Any]] = None self.setup()
FastAPI类进行初始化时,针对API文档会执行以下操作:
校验openapi_url、docs_url、redoc_url是否为空,也就是说文档标题、使用Swagger版本和OpenAPI路径必须提供,可以默认但不能为空
调用setup方法
setup方法接下来会调用openapi方法,再调用get_openapi方法,在此方法中完成以下操作:
解析文档标题、版本后、文档描述,接口路由、可用的重定义
调用get_openapi_path进行进一步解析校验
get_openapi_path方法主要完成:
方法解析校验
操作元数据(operation_id、operation_summary)解析校验
安全定义和操作安全解析
响应体解析
至此,文档相应模块参数解析完成,接下来就是网页的渲染
简而言之,API文档的生成在FastAPI初始化时,会先校验openapi_url/docs_url/redoc_url参数,然后启动setup方法,API文档生成包括两步:API文档参数解析和文档网页代码渲染,参数解析使用openapi.utils模块,网页渲染使用openapi.docs模块,网页渲染的顺序为交互式文档->oauth2重定向->可选文档。