Representational State Transfer,簡稱REST,它是一種網路架構風格,他並不是一種標準。
在 REST 樣式的 Web 服務中,每個資源都有一個位址。資源本身都是方法調用的目標,方法清單對所有資源都是一樣的。這些方法都是標準方法,包括 HTTP GET、POST、PUT、DELETE
一般的 API 可能長得像這樣
- /api/get_file/ ( 得到檔案 )
- /api/upload_file/ ( 新增檔案 )
- /api/update_file/ ( 更新檔案 )
- /api/delete_file/ ( 刪除檔案 )
RESTful API 則長得像這樣
- /api/files/ ( GET -> 得到檔案 )
- /api/files/ ( POST -> 新增檔案 )
- /api/files/ ( PUT -> 更新檔案)
- /api/files/ ( DELETE -> 刪除檔案 )
近幾年來RESTful Web Service已經成為API開發設計風格的主流,所以微軟也提供了Web API專案來符合此一開發風格。
新增一個Web API專案,我們可以在Controller看到Restful的設計風格
在Model新增一個簡單的產品類別
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
並新增一個API controller,名稱訂為ProductsController
建立商品資料查詢
執行專案後,可以在API的Help頁面看到目前可執行的API頁面
使用PostMan對API做查詢,可以得到以下回傳