FastAPI-Docs空白詳解

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

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-09 21:21
下一篇 2024-12-09 21:21

相關推薦

  • 打包後頁面空白的解決方案

    當我們在調試階段時,我們的app可能看起來完美無缺,但當我們進行打包時,在運行app時,我們可能會遇到白屏或空白的問題。在這篇文章中,我們將探討如何解決這種問題。 一、檢查文件路徑…

    編程 2025-04-29
  • Gino FastAPI實現高效低耗ORM

    本文將從以下多個方面詳細闡述Gino FastAPI的優點與使用,展現其實現高效低耗ORM的能力。 一、快速入門 首先,我們需要在項目中安裝Gino FastAPI: pip in…

    編程 2025-04-27
  • Python輸出空白缺少類

    Python是一種高級編程語言,它被廣泛應用於Web應用程序開發、數據庫管理、網絡自動化等方面,在各行各業中佔據着重要的地位。但是,有時候在Python編程中,我們會遇到輸出空白缺…

    編程 2025-04-27
  • Python刪除字符串開頭和末尾的空白

    本文將對使用Python刪除字符串開頭和末尾的空白進行詳細的闡述。 一、strip()函數簡介 strip()函數是Python字符串中常用的函數之一,它可以用於刪除字符串開頭和末…

    編程 2025-04-27
  • Linux sync詳解

    一、sync概述 sync是Linux中一個非常重要的命令,它可以將文件系統緩存中的內容,強制寫入磁盤中。在執行sync之前,所有的文件系統更新將不會立即寫入磁盤,而是先緩存在內存…

    編程 2025-04-25
  • 神經網絡代碼詳解

    神經網絡作為一種人工智能技術,被廣泛應用於語音識別、圖像識別、自然語言處理等領域。而神經網絡的模型編寫,離不開代碼。本文將從多個方面詳細闡述神經網絡模型編寫的代碼技術。 一、神經網…

    編程 2025-04-25
  • Linux修改文件名命令詳解

    在Linux系統中,修改文件名是一個很常見的操作。Linux提供了多種方式來修改文件名,這篇文章將介紹Linux修改文件名的詳細操作。 一、mv命令 mv命令是Linux下的常用命…

    編程 2025-04-25
  • Python輸入輸出詳解

    一、文件讀寫 Python中文件的讀寫操作是必不可少的基本技能之一。讀寫文件分別使用open()函數中的’r’和’w’參數,讀取文件…

    編程 2025-04-25
  • git config user.name的詳解

    一、為什麼要使用git config user.name? git是一個非常流行的分布式版本控制系統,很多程序員都會用到它。在使用git commit提交代碼時,需要記錄commi…

    編程 2025-04-25
  • nginx與apache應用開發詳解

    一、概述 nginx和apache都是常見的web服務器。nginx是一個高性能的反向代理web服務器,將負載均衡和緩存集成在了一起,可以動靜分離。apache是一個可擴展的web…

    編程 2025-04-25

發表回復

登錄後才能評論