[問題] RESTful API 非 resource 的設計問題

作者: chan15 (ChaN)   2023-09-01 00:04:55
各位好,目前我使用 Laravel 當作 API Server 的開發,爬過很多關於 RESTful 的文章
,如果是 resource 確定的 crud 很容易處理,舉例來說如果是使用者 > 文章 > 留言
controller name
UserArticleCommentController.php
網址會是 GET www.example.com/users/{user_id}/articles/{article_id}/comments
但常常會有規格外的東西就會比較苦惱,我知道這沒有一定自己公司說好就可以遵守,但
還是想聽聽看有相關經驗的朋友可以提供一下想法,下面開始舉例。
場景一,建立 widget:
我今天要提供前端三隻 API 資料給前端的 widget 用,像是 login-records、votes、
stars,這三個名稱以及 widget 都沒有所謂的 resource 概念,每一隻都是多張表整理出
來的結果,那檔案跟網址命名該怎麼做才好。
1.1
WidgetController.php
function getLoginRecord()
function getVotes()
function getStars
1.2
WidgetLoginRecordController.php
function index()
WidgetVoteController.php
function index()
WidgetStarController.php
function index()
1.3
Widget/LoginRecordController.php
function index()
Widget/VoteController.php
function index()
Widget/StartController.php
function index()
如果以跟一般 RESTful resource 安排一樣的話,會是 1.2,但這隻 API 理論上都只有
index 這個 method,這樣是否有點浪費資源。
另外是 url 應該用 widgets/login-records 還是 widget/login-records,widget 有多
隻,但實際上他們不是像 users/{user_id} 這種從多個 users data 裡面抽出某一筆的概
念。
場景二:複合式動作的命名
假設要訂閱某個文章,他是拿 header 裡的 token 找出 user,然後帶入文章 id 後寫入
pivot table 那該怎麼命名。
2.1
ArticleController.php
function subscribe()
POST www.example.com/articles/{article_id}/subscription
還是應該更明確
2.2
ArticleController.php
function userSubscribe()
POST www.example.com/articles/{article_id}/user-subscription
場景三:特殊註況
以使用者密碼為例,密碼可能有重設密碼、忘記密碼
3.1
UserPasswordController.php
function reset()
users/password/reset
function forgot()
users/password/forgot
3.2
UserController.php
function resetPassword()
users/password-reset
function forgotPassword()
users/password-forgot
想請教各位會怎麼選擇。
作者: single4565 (leekdumpling韭菜水餃)   2023-09-01 02:46:00
可能這篇有幫助?https://stackoverflow.com/questions/3077229/restful-password-reset
作者: ian90911 (xopowo)   2023-09-01 11:15:00
也看過動詞用冒號接的方式 如user:resetpwd
作者: vi000246 (Vi)   2023-09-01 11:23:00
去讀clean code 或重構相關的書
作者: ssccg (23)   2023-09-02 21:10:00
浪費是什麼意思? 檔案多並不會浪費什麼資源啊第二個除非subscription有很多種不然沒差吧第三個看不懂你的forgot跟reset是差在哪,忘記密碼是使用者狀態不是系統要做的動作吧。當然你問只可能只是動詞要怎麼辦,個人會先考慮能不能PUT湊上去就夠用
作者: youtuuube000 (小孩)   2022-04-23 14:13:00
其實不用太糾結 restful resource的想法 有些操作本來就很難抽象化成資源 直接用動詞就好

Links booklink

Contact Us: admin [ a t ] ucptt.com