目的
開發(fā)了幾個項目用了幾種 API URL約定/規(guī)范。
沒有好壞,順手即可,寫這個鬼,有時候有更好的方便自己對比一下。
一,方法型
其中 GET POST
或用新得 GET POST PUT DELETE 因人而異, 能用新的當然自我感覺好點
GET /article/findById 詳情 ?id=1
/article/add 添加 {id:'',title:'xxxx'}
/article/list 查詢 ?keyword=xxx&size=0&page=1 | title=%xxxx%&size=x&page=1 查詢也能用自己公司習慣技術(shù)來衍生.
/article/edit 編輯 {id:'1',title:'bbbb'}
/article/delete 刪除 [1,2,3]
/article/createByChatGpt 通過CPT創(chuàng)建一個文章
二,資源型/目錄型一
把url當成文件來處理
這種resetful 風格基本都是 查詢GET, 編輯PUT, 創(chuàng)建 POST,刪除 DELETE
/articles/:id 詳情
/articles 列表
/articles 添加 POST {id:'',title:'xxxx'}
/articles 添加 PUT {id:'1',title:'xxxx'}
/articles 刪除 DELETE [1,2,3]}
/articles/:id/products 文章下面商品列表
/articles/1/products 添加 POST {id:'',goodName:'xxxx'}
/articles/1/products 修改 PUT {id:'1',goodName:'xxxx'}
如果商品下面還有,也就是有三級
/articles/:id/products/:goodsId/items
第三方調(diào)用變得有點惡心,需要在URL放入articleId 和 goodsId。用起來不舒服
Resetful風格描述非 CURD
/articles/:id/like 喜歡 POST
/articles/:id/like 取消喜歡 DELETE
/articles/add/chatgpt 通過Chatgpt 創(chuàng)建文章 POST {'senetance: 'xxxx'}
另外一個擴展導致我燒了CPU。例如
/articles/:id/bundles 不合理,因為bundles先于articles,
退其次 使用
bundles/:id/articles 使用中間表這周縫合 bundleArticles (類似 linux 文件管理 映射的概念)
把bundle設(shè)計成 ariticle 上級當然沒問題,但是如果還有其他資源也需要有自己的集合那么就GG
當然新的業(yè)務(wù)約定是,一個功能越能兼容多的功能是更好的 滿足 control v c
也就是bundles 能集合文章或產(chǎn)品等 。。
二,資源型/目錄型二
對比起一型, 去除了URL上面 ID們, 讓我們操作多級對象時 不需要去改URL,
一級對象還是遵循Resetful風格, 二級及以上去除了復數(shù)描述,也能解決articles 需要擴展bundle時可以直接放在article 目錄下
/article/articles/:id 詳情
/article/articles 列表
/article/articles 添加 POST {id:'',title:'xxxx'}
/article/articles 添加 PUT {id:'1',title:'xxxx'}
/article/articles 刪除 DELETE [1,2,3]}
/article/products 文章下面商品列表 GET
/article/products/:id 商品詳情 GET
/article/products 添加 POST {id:'',aritcleId:'1',goodName:'xxxx'}
/article/products 修改 PUT {id:'1',aritcleId:'1',goodName:'xxxx'}
/article/bundles
/article/bundles/:id
/article/bundle/articles ? bundleId=1&title=%xx%
關(guān)于API 版本
有人喜歡用 /v1/article** 這種感覺輕一點
有人喜歡在 head 里面加入version:v1 這種來進行描述,
關(guān)于業(yè)務(wù)級別/權(quán)限
基礎(chǔ)接口使用 resources 進行管理員權(quán)限控制
動作型
/login
/login/wechat/mp
/login/weibo
/search 全局搜索
用戶個人前綴
/home/**
/home/articles 我的文章
/home/notifications 我的通知
監(jiān)聽/第三方
/listener/wechats/:id/pay 支付事件
/listener/wechats/:id/click 點擊事件
/listener/orders/status/change 狀態(tài)更改
開放級別
/open/**
/open/aritcles/hots 熱門文章 (也是使用 linux 映射的概念)
/open/aritcles/hots/weekly 熱門文章 (也是使用 linux 映射的概念)
帶權(quán)限開放接口
參考 http authorization type
URL 還沒找到好的約定前綴
MVVM
如果mvvm與后臺restful 同步就可以避免 url post item的時候需要手工去組裝 文章id 到url里面
POST /home/articles/文章id/item
總結(jié)
還有些地方?jīng)]考慮全