搜尋
首頁後端開發Python教學如何在FastAPI中使用Swagger UI展示API文檔

如何在FastAPI中使用Swagger UI展示API文檔

Jul 30, 2023 am 10:45 AM
fastapiapi文檔swagger ui

如何在FastAPI中使用Swagger UI來展示API文件

導言:
在現代Web開發中,API是不可或缺的一部分。為了方便開發和維護,我們需要提供一個友好且易於使用的API文檔,以便其他開發人員可以了解和使用我們的API。 Swagger是一種受歡迎的API文件格式和工具,它提供了一個互動的UI介面,可以直觀地展示API的細節。在本文中,我將向您展示如何在FastAPI中使用Swagger UI來展示API文件。

  1. 安裝依賴
    首先,我們需要安裝FastAPI和相關的依賴。可以使用以下命令進行安裝:

    pip install fastapi[all]

    這將安裝FastAPI及其所需的所有依賴項,包括Swagger UI。

  2. 建立FastAPI應用程式
    接下來,我們將建立一個FastAPI應用程式。在一個新的Python檔案中,編寫以下程式碼:

    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/")
    async def root():
     return {"message": "Hello World"}

    這個簡單的應用程式定義了一個根路由,用於傳回一個簡單的「Hello World」訊息。

  3. 新增Swagger UI
    為了加入Swagger UI到我們的應用程式中,我們需要匯入相關的FastAPI元件。將以下程式碼加入我們的應用程式檔案:

    from fastapi import FastAPI
    from fastapi.openapi.utils import get_openapi
    from fastapi.openapi.docs import get_swagger_ui_html
    
    app = FastAPI()
    
    @app.get("/")
    async def root():
     return {"message": "Hello World"}
    
    def custom_swagger_ui_html(*, request):
     openapi_url = app.openapi_url
     swagger_url = openapi_url.replace("/openapi.json", "/swagger")
     return get_swagger_ui_html(
         openapi_url=openapi_url,
         title=app.title + " - Swagger UI",
         oauth2_redirect_url=swagger_url + "/oauth2-redirect.html",
         swagger_js_url="/static/swagger-ui-bundle.js",
         swagger_css_url="/static/swagger-ui.css",
     )
    
    app.openapi = get_openapi(title="My API")
    
    @app.get("/swagger", include_in_schema=False)
    async def swagger_ui_html(request: Request):
     return custom_swagger_ui_html(request=request)
    
    app.mount("/static", StaticFiles(directory="static"), name="static")

    在程式碼中,我們建立了一個名為custom_swagger_ui_html的自訂函數。這個函數將會使用FastAPI提供的get_swagger_ui_html函數來產生Swagger UI的HTML頁面。我們也為Swagger UI定義了一些URL和靜態檔案的路徑。

  4. 運行應用程式
    現在我們的應用程式已經準備就緒,可以運行它了。在終端機中,使用以下命令來啟動應用程式:

    uvicorn main:app --reload

    這將啟動我們的應用,並使其運行在本地的預設位址http://localhost:8000上。

  5. 查看API文件
    在瀏覽器中開啟http://localhost:8000/swagger,你會看到一個互動式的Swagger UI介面。它將顯示您的API的詳細信息,包括路由、請求和回應模型等等。

結論:
透過使用FastAPI和Swagger UI,我們可以輕鬆地展示和瀏覽我們的API文件。這使得開發人員可以更方便地了解和使用我們的API。希望這篇文章能對您在FastAPI中使用Swagger UI展示API文件有所幫助。

以上就是如何在FastAPI中使用Swagger UI來展示API文件的指南。希望本文能對您有幫助。謝謝閱讀!

以上是如何在FastAPI中使用Swagger UI展示API文檔的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

說明如何將內存分配給Python中的列表與數組。說明如何將內存分配給Python中的列表與數組。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python數組中指定元素的數據類型?您如何在Python數組中指定元素的數據類型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什麼是Numpy,為什麼對於Python中的數值計算很重要?什麼是Numpy,為什麼對於Python中的數值計算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

討論'連續內存分配”的概念及其對數組的重要性。討論'連續內存分配”的概念及其對數組的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy陣列上可以執行哪些常見操作?在Numpy陣列上可以執行哪些常見操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的數據分析中如何使用陣列?Python的數據分析中如何使用陣列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具