路徑、路由處理
## FastAPI 中的路徑與路由
在 FastAPI 中:
- **路徑(Path)**:指 URL 中的路徑部分,例如 `/users`、`/items/123`
- **路由(Route)**:指「某個 HTTP 方法 + 路徑」對應到哪一個 Python 函式
例如:
```text
GET /hello
```
可以設定成由 `hello()` 函式處理。當使用者以瀏覽器或其他 HTTP 用戶端請求 `/hello` 時,FastAPI 就會執行該函式並回傳結果。
常見的 HTTP 方法包括:
- `GET`:取得資料
- `POST`:新增資料
- `PUT`:更新資料
- `DELETE`:刪除資料
## 基本程式範例
建立 `main.py`:
```python
from fastapi import FastAPI
# 建立 FastAPI 應用程式物件
app = FastAPI()
# 設定 GET / 路由
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
# 設定 GET /hello 路由
@app.get("/hello")
def say_hello():
return {"message": "你好,FastAPI!"}
```
啟動服務:
```bash
uvicorn main:app --reload
```
說明:
- `main`:代表 `main.py`
- `app`:代表檔案中的 `FastAPI()` 物件
- `--reload`:修改程式後自動重新載入
啟動後可以造訪:
```text
http://127.0.0.1:8000/
http://127.0.0.1:8000/hello
```
例如造訪:
```text
http://127.0.0.1:8000/hello
```
會得到 JSON 回應:
```json
{
"message": "你好,FastAPI!"
}
```
FastAPI 也會自動提供 API 文件:
```text
http://127.0.0.1:8000/docs
```
在此頁面可以直接查看並測試已設定的路由。
相關學習地圖、教學課程
Python 後端工程、資料庫