網頁表單互動
## FastAPI 使用 GET 接收表單參數
HTML 表單使用 `GET` 方法送出時,瀏覽器會將表單資料附加在網址後方,形成 Query String:
```text
/multiply?a=6&b=7
```
FastAPI 可以直接透過路由函式的參數名稱接收這些資料。例如,HTML 中的 `name="a"` 會對應到 FastAPI 的 `a` 參數。
---
## 1. 前端 HTML:`index.html`
```html
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>乘法計算</title>
</head>
<body>
<h1>乘法計算</h1>
<form action="http://127.0.0.1:8000/multiply" method="get">
<label>
第一個數字:
<input type="number" name="a" required>
</label>
<br><br>
<label>
第二個數字:
<input type="number" name="b" required>
</label>
<br><br>
<button type="submit">計算</button>
</form>
</body>
</html>
```
當使用者輸入:
```text
a = 6
b = 7
```
並按下按鈕後,瀏覽器會送出類似以下網址:
```text
http://127.0.0.1:8000/multiply?a=6&b=7
```
---
## 2. 後端 FastAPI:`main.py`
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/multiply")
def multiply(a: int, b: int):
result = a * b
return {
"a": a,
"b": b,
"result": result
}
```
---
## 3. 執行程式
先安裝套件:
```bash
pip install fastapi uvicorn
```
啟動 FastAPI:
```bash
uvicorn main:app --reload
```
接著用瀏覽器開啟 `index.html`,輸入兩個數字並送出。
例如輸入 `6` 和 `7`,後端會回傳:
```json
{
"a": 6,
"b": 7,
"result": 42
}
```
---
## 參數對應關係
HTML 的表單欄位:
```html
<input name="a">
<input name="b">
```
會對應到 FastAPI:
```python
def multiply(a: int, b: int):
```
其中:
- `name="a"` 對應 `a`
- `name="b"` 對應 `b`
- `int` 表示 FastAPI 會將資料轉成整數
- 如果輸入不是有效整數,FastAPI 會回傳驗證錯誤
使用 GET 的資料會顯示在網址列,因此適合查詢或簡單計算,不適合傳送密碼等敏感資料。
相關學習地圖、教學課程
Python 後端工程、資料庫