前置作業
安裝 pipx 指令。
1 | brew install pipx |
安裝 poetry 指令。
1 | pipx install poetry |
建立專案
建立專案。
1 | mkdir fastapi-example |
使用 Poetry 初始化專案。
1 | poetry init |
啟動虛擬環境。
1 | poetry shell |
安裝檢查工具
安裝依賴套件。
1 | poetry add ruff |
新增 ruff.toml 檔。
1 | line-length = 120 |
修改 .vscode/settings.json 檔。
1 | { |
實作
安裝依賴套件。
1 | poetry add "fastapi[standard]" |
新增 main.py 檔。
1 | from typing import Union |
啟動網頁伺服器。
1 | fastapi dev main.py |
前往 http://localhost:8000/docs 瀏覽,並使用文件測試 API 端點。
建立端點
修改 main.py 檔。
1 | from typing import List, Optional |
前往 http://localhost:8000/docs 瀏覽,並使用文件測試 API 端點。
提交修改
新增 .gitignore 檔。
1 | __pycache__ |
提交修改。
1 | git init |
測試端點
安裝 Bruno 工具。
建立一個集合:
- Name:
fastapi-example - Location:
~/path-to-your-project/fastapi-example - Name:
bruno
建立請求
List Items
- Name:
list-items - Method:
GET - URL: http://localhost:8000/api/items
Create Item
- Name:
create-item - Method:
POST - URL: http://localhost:8000/api/items
Get Item
- Name:
get-item - Method:
GET - URL: http://localhost:8000/api/items/:id
Update Item
- Name:
update-item - Method:
PUT - URL: http://localhost:8000/api/items/:id
Delete Item
- Name:
delete-item - Method:
DELETE - URL: http://localhost:8000/api/items/:id