FastAPI-Docs是一個用於自動生成API文檔的工具,它可以高效地生成交互式文檔,同時支持多種格式,包括OpenAPI(以前稱為Swagger)和ReDoc。在FastAPI中使用FastAPI-Docs非常簡單,只需在定義API路由時啟用Docs即可。在這篇文章中,我們將從多個方面對FastAPI-Docs進行詳細的闡述。
一、使用FastAPI-Docs快速生成API文檔
要使用FastAPI-Docs快速生成API文檔,我們只需在定義API路由時啟用Docs。以下是一個示例代碼:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
在這個示例中,我們只定義了一個根路由,它將返回一個JSON響應,並在應用程序啟動時使用Uvicorn啟動。
要啟用FastAPI-Docs,只需要在路由定義中添加一個參數“docs_url”並設置為’/docs’。這將啟用一個自動生成的文檔站點,網址為’http://localhost:8000/docs’。以下是修改後的代碼:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000, docs_url="/docs")
現在訪問’http://localhost:8000/docs’就可以看到自動生成的API文檔了。在FastAPI中使用FastAPI-Docs非常簡單,只需啟用路由定義中的“docs_url”參數即可。接下來,我們將進一步了解FastAPI-Docs的各個方面。
二、快速生成OpenAPI文檔
在 FastAPI中使用FastAPI-Docs,你可以快速生成 OpenAPI 文檔,以便於與其他開發者共享。以下是一個示例代碼,演示如何使用FastAPI-Docs生成OpenAPI文檔:
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="Custom title",
version="2.5.0",
description="This is a very custom OpenAPI schema",
routes=app.routes,
)
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000, docs_url="/docs")
在這個示例中,我們定義了一個名為 custom_openapi 的函數。該函數作為 app.openapi 的值設置,這是一個包含 OpenAPI Schema 的字典。在此示例中,我們設置了一個自定義標題、自定義版本和自定義說明,以及將 app.routes 作為參數傳遞給 FastAPI-Docs。如果你希望使用 FastAPI-Docs 更改你的 API 的文檔,那麼這非常有用。
三、文檔頁面的定製
FastAPI-Docs不僅支持一鍵生成文檔,還支持自定義文檔頁面的外觀和行為。以下是示例代碼,演示如何自定義文檔頁面:
from fastapi import FastAPI, Response
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.route("/redoc")
async def redoc(request: Request):
return get_redoc_html(
openapi_url="/openapi.json",
title="Custom Redoc",
redoc_js_url="/static/redoc.standalone.js",
redoc_favicon_url="/static/favicon.png",
)
@app.route("/docs", methods=["GET"])
async def get_docs(request: Request):
return get_swagger_ui_html(
openapi_url="/openapi.json",
title="Custom Swagger UI",
swagger_js_url="/static/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui.css",
swagger_favicon_url="/static/favicon.png",
)
@app.route("/openapi.json")
async def get_open_api_endpoint(request: Request):
return JSONResponse(app.openapi())
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000, docs_url="/docs")
在這個示例中,我們定義三個路由,’redoc’,’docs’和’openapi.json’。在’get_docs’路由中,我們返迴響應,其中包含自定義的Swagger UI。在’redoc’路由中,我們返迴響應,其中包含自定義的Redoc實例。在’get_open_api_endpoint’路由中,我們返回包含OpenAPI Schema的響應。上面這個示例代碼的網址為’http://localhost:8000/redoc’和’http://localhost:8000/docs’。
四、在文檔中附加模型類
在 FastAPI-Docs 中,你可以將模型類附加到文檔中。以下是一個示例代碼,演示如何在文檔中附加模型類:
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000, docs_url="/docs", schema_url="/schema")
在這個示例中,我們定義了一個名為 Item 的模型類,並將其作為參數傳遞給 API 路由。FastAPI-Docs將自動生成與 Item 模型類相關的 JSON Schema。還可以通過在啟動應用程序時設置 “schema_url” 來生成該模式。這將返回一個包含 JSON Schema 的響應,網址為’http://localhost:8000/schema’。
五、使用FastAPI-Docs自定義認證和授權頁面
FastAPI-Docs 還支持自定義認證和授權頁面。以下是一個示例代碼,演示如何自定義認證和授權頁面:
from fastapi import FastAPI
from fastapi.openapi.docs import (get_swagger_ui_html, get_redoc_html)
from fastapi.openapi.utils import get_openapi
from fastapi.responses import HTMLResponse, JSONResponse
app = FastAPI()
@app.get("")
async def read_root():
return {"Hello": "World"}
@app.post("/token")
async def login():
return {"access_token": "johndoe_token"}
# Documentation URLs
@app.get("/docs", response_class=HTMLResponse)
async def get_documentation():
return get_swagger_ui_html(
openapi_url="/openapi.json",
title="docs"
)
@app.get("/redoc", response_class=HTMLResponse)
async def get_documentation():
return get_redoc_html(
openapi_url="/openapi.json",
title="redoc"
)
@app.get("/openapi.json", response_class=JSONResponse)
async def get_openapi():
return get_openapi(
title="Custom Title",
version="2.5.0",
description="This is a custom OpenAPI schema",
routes=app.routes,
)
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, port=8000, host="0.0.0.0", debug=True, use_colors=True)
在這個示例中,我們定義了兩個認證和授權路由 (“/” 和 “/token”),以及三個文檔路由 (“/docs”、”/redoc” 和 “/openapi.json”)。在”/token”掛載的路由中驗證用戶,若驗證成功,我們返回一個授權令牌。API 文檔將顯示一個“Authorize”按鈕,就像默認情況下一樣,但是我們在“Authorize”框中輸入的“Bearer ”後面輸入上面返回的授權令牌。使用 FastAPI-Docs,我們可以輕鬆地自定義認證和授權頁面。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/227812.html