GET 作業

FastAPI 入門

Matt Eckerle

Software and Data Engineering Leader

GET 作業複習

HTTP 通訊協定有多種作業。

  • 最常見是 GET。

範例:https://www.google.com:80/search?q=fastapi

GET 請求的重點部分:

  • 主機,例如 www.google.com
  • 連接埠,例如 80(預設)
  • 路徑,例如 /search
  • 查詢字串,例如 ?q=fastapi
FastAPI 入門

FastAPI 的 GET 作業

最簡單的 FastAPI 應用:

from fastapi import FastAPI

# 建立應用程式實例 app = FastAPI()
# 處理根路徑的 GET 請求 @app.get("/") def root(): return {"message": "Hello World"}
1 https://fastapi.tiangolo.com/tutorial/first-steps/
FastAPI 入門

使用 cURL 網頁用戶端

cURL 主要選項:

$ curl -h
Usage: curl [options...] <url>
 -v, --verbose               Make the operation more talkative
 -H, --header <header/@file> Pass custom header(s) to server
 -d, --data <data>           HTTP POST data

使用範例:

$ curl http://localhost:8000
{"message":"Hello World"}
FastAPI 入門

查詢參數(Query Parameters)

新端點:

  • 路徑:「/hello」
  • 查詢參數:「name」
    • 預設值:「Alan」
@app.get("/hello")
def hello(name: str = "Alan"):
    return {"message": f"Hello {name}"}

請求中未提供名稱: 終端機顯示未提供 name 的 curl 請求。回應訊息為「Hello Alan.」。

請求中提供名稱: 終端機顯示提供 name 的 curl 請求。回應訊息為「Hello Steve.」。

FastAPI 入門

一起來練習吧!

FastAPI 入門

Preparing Video For Download...