iT邦幫忙

0

# Day 04 使用 Python FastAPI 建立專案骨架與健康檢查 API

n8n
  • 分享至 

  • xImage
  •  

在前三天的實戰中,我們已經完整搭建了自動化與推論的基礎設施:

  1. Docker Desktop & WSL 2:本地容器化運行環境。
  2. n8n & Dify:視覺化工作流與串接 Google Gemini 的 AI 核心大腦。
  3. ngrok:打通公網至本地服務的 HTTPS 隧道。

從今天開始,我們將正式進入 AI Agent 核心後端服務的開發!為了讓外部通訊端點、商業邏輯計算與 AI 流程之間具備高彈性與高效能,我們選擇現代 Python 開發中最主流的高效能非同步框架——FastAPI 作為我們的核心微服務架構。

今天目標是從零建立 Python 虛擬環境、建置標準專案骨架,並實作第一個具備健康檢查(Health Check)與自動化 Swagger API 文件的後端端點!


一、為什麼選擇 FastAPI 作為 Agent 後端?

在開發 AI Agent 與自動化系統時,後端通常需要頻繁與第三方 API、資料庫及 LLM 進行 I/O 溝通。FastAPI 具備以下核心優勢:

  • 原生非同步支援(async/await):高併發效能極佳,非常適合等待 LLM 串流回應或外部 Webhook 回調。
  • Pydantic 強型別驗證:自動解析與校驗請求參數(Request Body),大幅降低資料傳輸錯誤。
  • 自動生成互動式 API 文件:內建 Swagger UI,在開發階段無需額外配置即可直接在瀏覽器測試 API。

二、環境建置與依賴安裝

在 Windows 環境下,建議為專案建立獨立的 Python 虛擬環境(Virtual Environment),以避免套件版本衝突。

Step 1:建立專案資料夾與虛擬環境

請打開 PowerShell,進入昨天的專案目錄或建立專案資料夾:

# 進入專案目錄
cd C:\Users\1124l\food-agent

# 建立專案資料夾
mkdir agent-backend
cd agent-backend

# 建立 Python 虛擬環境(命名為 .venv)
python -m venv .venv

# 啟動虛擬環境
.\.venv\Scripts\Activate.ps1

注意:若執行腳本時遇到權限限制錯誤(ExecutionPolicy),可先在 PowerShell 執行 Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass 後再啟動虛擬環境。終端機前綴出現 (.venv) 即代表啟用成功。

Step 2:安裝核心套件

在啟用虛擬環境的狀態下,安裝 FastAPI 以及 ASGI 伺服器 Uvicorn:

pip install fastapi uvicorn[standard] pydantic

三、專案結構規劃與程式碼實作

為了後續幾天串接資料模型、n8n Webhook 與 LLM Agent,我們規劃清晰模組化的專案骨架:

agent-backend/
├── app/
│   ├── __init__.py
│   ├── main.py          # 程式進入點與 FastAPI 實例
│   └── routers/         # API 路由模組
│       ├── __init__.py
│       └── health.py    # 健康檢查與系統狀態端點
├── requirements.txt     # 套件清單
└── README.md
  1. 建立健康檢查路由 (app/routers/health.py)
    建立 app/routers/health.py,定義系統健康度檢查的資料模型與端點:
from fastapi import APIRouter
from pydantic import BaseModel
from datetime import datetime

router = APIRouter(
    prefix="/api/v1",
    tags=["Health Check"]
)

class HealthResponse(BaseModel):
    status: str
    service: str
    timestamp: str

@router.get("/health", response_model=HealthResponse)
async def check_health():
    """
    提供系統心跳檢測(Health Check),用於確認微服務狀態
    """
    return HealthResponse(
        status="ok",
        service="food-agent-backend",
        timestamp=datetime.utcnow().isoformat()
    )
  1. 建立主應用程式進入點 (app/main.py)
    在 app/main.py 實例化 FastAPI,並掛載健康檢查路由:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.routers import health

app = FastAPI(
    title="Food Agent Microservice API",
    description="智慧餐飲推薦與工作流核心後端服務",
    version="1.0.0"
)

設定跨來源資源共用 (CORS)

    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

註冊路由模組

app.include_router(health.router)

@app.get("/")
async def root():
    return {
        "message": "Welcome to Food Agent API",
        "docs_url": "/docs"
    }
  1. 凍結相依套件 (requirements.txt)
    將當前環境所安裝的套件規格導出,方便日後部署或容器化:
pip freeze > requirements.txt

四、本地啟動與測試驗收

Step 1:啟動開發伺服器

在 agent-backend 目錄下執行 Uvicorn,並啟用 --reload 熱重載模式:

uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload

當終端機顯示以下資訊即代表伺服器運行中:

INFO:     Uvicorn running on [http://0.0.0.0:8000](http://0.0.0.0:8000) (Press CTRL+C to quit)
INFO:     Started reloader process [...] using StatReload
INFO:     Started server process [...]
INFO:     Application startup complete.

Step 2:透過 Swagger UI 驗證

打開瀏覽器造訪:http://localhost:8000/docs
畫面會呈現自動生成的 Swagger UI 互動式文件。

點開 GET /api/v1/health 端點,點擊 Try it out ➜ Execute。

確認伺服器回應狀態碼為 200 OK,並回傳格式化 JSON:

  "status": "ok",
  "service": "food-agent-backend",
  "timestamp": "2026-10-05T10:08:47.123456"
}

今日結語與明日預告
今天我們順利建立了 Python FastAPI 的標準微服務專案骨架,完成了第一個健康檢查 API,並驗證了 Swagger 文件的自動生成功能。

目前為止,本地已經具備了三大服務:

FastAPI 核心後端:http://localhost:8000

n8n 自動化流程:http://localhost:5678

Dify AI 應用大腦:http://localhost

明天 Day 05,我們將開始設計餐飲推薦的核心資料結構:使用 Pydantic 定義餐飲資料模型(Schema),並實作第一隻餐點推薦模擬 API,敬請期待!


*提醒邦友,使用第三方服務/API 時,請務必評估資安風險與隱私保護
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言