為什麼選 FastAPI?

FastAPI 入門

Matt Eckerle

Software and Data Engineering Leader

什麼是 FastAPI?

先釐清一些術語

  1. API:Application Programming Interface——指使用 HTTP 傳輸結構化資料的網路應用
  2. 網路應用程式(Web Application):在網路上提供服務的應用
  3. 網頁框架(Web Framework):協助開發網路應用的軟體框架

FastAPI 可用 Python 快速打造高效能 API

FastAPI 入門

FastAPI 的關鍵特性

  • Fast:效能極高
  • 「低程式碼」、好上手:採用 Python 註釋與型別標註
  • 穩健:具備自動文件的可上線程式碼
  • 遵循標準:基於 OpenAPI 與 JSON Schema

FastAPI 標誌

OpenAPI 標誌

JSON 標誌

1 https://fastapi.tiangolo.com/
FastAPI 入門

FastAPI 與其他 Python 網頁框架

Flask

  • 開發網頁(GUI)應用
  • ORM 可選

FastAPI

  • 開發 API
  • ORM 可選

Django

  • 開發網頁(GUI)應用
  • 內建 ORM

主要差異

  • 適合不含資料庫操作的 API
  • 適用資料與機器學習服務
FastAPI 入門

用 FastAPI 建立第一個網路應用

1. 安裝 FastAPI

pip install fastapi

2. 在 main.py 建立你的應用

from fastapi import FastAPI

app = FastAPI()

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

3. 啟動伺服器

fastapi dev main.py

REPL 顯示 FastAPI 正在執行

FastAPI 入門

在練習 FastAPI 之前

注意事項

  1. 不能用「Run this code」按鈕啟動 FastAPI 伺服器
  2. 請在 Python 編輯器中將伺服器程式碼存為 main.py

  3. 在終端機以指令 fastapi dev main.py 執行

  4. 確認終端機日誌出現 Application startup complete.
  5. 在同一視窗按 Control + C 停止伺服器
  6. 建議在你自己的 Python 環境安裝 FastAPI,熟悉在那裡練習
FastAPI 入門

一起來練習吧!

FastAPI 入門

Preparing Video For Download...