fastapi swagger
时间: 2023-09-04 09:09:29 浏览: 113
FastAPI 是一个现代化的 Web 框架,它基于 Python 3.6+,并使用了一些最新的技术,如 type hints、asyncio 和 Pydantic。FastAPI 可以让你快速地构建高性能的 Web 应用程序和 API。
Swagger 是一种 API 文档和交互式测试工具,它可以帮助开发者快速地了解和测试 API。FastAPI 集成了 Swagger UI,使开发者可以通过浏览器轻松地查看和测试 API。
在 FastAPI 中,只需要使用少量的代码就可以生成 Swagger 文档。你可以使用 FastAPI 内置的 `FastAPIOpenAPI` 和 `FastAPISwaggerUI` 类来集成 Swagger UI,代码示例如下:
```python
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse, HTMLResponse
app = FastAPI()
# 静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")
# 模板文件
templates = Jinja2Templates(directory="templates")
# 路由
@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
return templates.TemplateResponse("index.html", {"request": request, "title": "FastAPI"})
@app.get("/docs", response_class=HTMLResponse)
async def read_docs(request: Request):
return templates.TemplateResponse("docs.html", {"request": request, "title": "API 文档"})
@app.get("/openapi.json", response_class=JSONResponse)
async def get_open_api_endpoint():
return JSONResponse(get_openapi(title="FastAPI", version="0.1.0", app=app))
# 启动 FastAPI
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
```
在上面的代码中,我们创建了一个 `FastAPI` 实例,并使用 `app.mount` 方法来加载静态文件。然后,我们使用 `Jinja2Templates` 类来加载模板文件。接下来,我们定义了三个路由:`/`、`/docs` 和 `/openapi.json`。其中,`/` 和 `/docs` 路由返回 HTML 页面,`/openapi.json` 路由返回 Swagger 文档。
最后,我们使用 `uvicorn` 模块来启动 FastAPI。启动后,我们可以通过浏览器访问 `http://localhost:8000/docs` 来查看 Swagger UI。