FastAPI - Hello World



入門

建立 FastAPI 應用的第一步是宣告 FastAPI 類的應用程式物件。

from fastapi import FastAPI
app = FastAPI()

這個 app 物件是應用程式與客戶端瀏覽器互動的主要點。uvicorn 伺服器使用此物件來監聽客戶端的請求。

下一步是建立路徑操作。路徑是客戶端訪問時會呼叫對映 URL 的 URL,與 HTTP 方法之一相關聯的函式將被執行。我們需要將檢視函式繫結到 URL 和相應的 HTTP 方法。例如,index() 函式對應於‘/’ 路徑和‘get’ 操作。

@app.get("/")
async def root():
   return {"message": "Hello World"}

該函式返回 JSON 響應,但是,它也可以返回dict、list、str、int 等。它還可以返回 Pydantic 模型。

將以下程式碼儲存為 main.py

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

透過提及例項化 FastAPI 應用程式物件的檔案來啟動 uvicorn 伺服器。

uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.

開啟瀏覽器並訪問 https://:/8000。您將在瀏覽器視窗中看到 JSON 響應。

FastAPI Hello
廣告

© . All rights reserved.