RestAPI 設計

RESTful API 設計最佳實踐web

使用 restful api 做爲 web api,須要注意的以下幾點api

參考 OpenStack 的 port api 設計服務器

使用名詞定義接口,且是名詞複數restful

對於獲取全部用戶,應該使用
    /users

不該該使用
    /getAllUsers

使用子資源來表達資源間的關係,以下表示id24的用戶擁有的車子
    /users/24/cars

GET 方法和查詢參數不能改變資源狀態設計

若是要改變資源的狀態,使用 PUT, POST 和 DELETE。rest

API 版本化code

版本號使用簡單的序號,並避免點符號,如2.5等。正確用法以下:blog

/blog/api/v1

使用 HATEOAS 約束排序

當服務器發生了變化時,客戶端並不須要作出修改,由於資源的 URI 和其餘信息都是動態發現的。接口

{
      "id": 711,
      "manufacturer": "bmw",
      "model": "X5",
      "seats": 5,
      "drivers": [
       {
        "id": "23",
        "name": "Stefan Jauker",
        "links": [
         {
         "rel": "self",
         "href": "/api/v1/drivers/23"
        }
       ]
      }
     ]
    }

提供過濾、排序、字段選擇、分頁

過濾:
    GET /cars?color=red 
    GET /cars?seats<=2

排序:
    GET /cars?sort=-manufactorer,+model

字段選擇:
    GET /cars?fields=manufacturer,model,id,color

分頁:
    GET /cars?offset=10&limit=5
相關文章
相關標籤/搜索