http://www.troyhunt.com/2014/02/your-api-versioning-is-wrong-which-is.html
這篇文章寫得很好,介紹了三種實現web api版本化的三種方式。我從評論裏又收集到兩種方式,所以一共是5種:
方式一:利用URL
- HTTP GET:
- https://haveibeenpwned.com/api/v2/breachedaccount/foo
方式二:利用用戶自定義的request header
- HTTP GET:
- https://haveibeenpwned.com/api/breachedaccount/foo
- api-version: 2
方式三:利用content type
- HTTP GET:
- https://haveibeenpwned.com/api/breachedaccount/foo
- Accept: application/vnd.haveibeenpwned.v2+json
方式四:利用content type
- HTTP GET:
- https://haveibeenpwned.com/api/breachedaccount/foo
- Accept: application/vnd.haveibeenpwned+json; version=2.0
這個方式和方式三的小不同的地方是,把版本號分離出來了。
方式五:利用URL裏的parameter
- HTTP GET:
- https://haveibeenpwned.com/api/breachedaccount/foo?v=2
作者說他最喜歡第三種方式,因爲
- URL不用改變
- 客戶端應該通過accept header來表明自己想接收的是什麼樣的數據。
我個人最喜歡的是第二種方式,因爲這個用spring mvc實現最容易,也最簡潔。
因爲只要在Controler上用@RequestMapping標明版本即可。不用再去各種匹配,各種識別。
如果是自己寫一個Annotation來識別的話,也要花些功夫,而且怎麼無縫地轉發到原有的Spring mvc的配置也是個問題。
- @Controller
- @RequestMapping(headers="apt-version=2")
- public class TestControllerV2 {
- }
另外這個網站列舉了很多國外的有名網站是如何實現web api版本控制的。
http://www.lexicalscope.com/blog/2012/03/12/how-are-rest-apis-versioned/
https://github.com/cailin186/restapi-versioning-spring/blob/master/src/main/java/com/mindhaq/apiversions/web/AddressController.java
http://stackoverflow.com/questions/20198275/how-to-manage-rest-api-versioning-with-spring
參考
http://ningandjiao.iteye.com/blog/1990004
讓SpringMVC支持可版本管理的Restful接口
http://www.cnblogs.com/jcli/p/springmvc_restful_version.html
restAPI 設計指南
http://www.ruanyifeng.com/blog/2014/05/restful_api.html