API Design

本文章用于內(nèi)部分享時做PPT用,所以內(nèi)容并不詳盡

Why do you need API ?

在C/S 結(jié)構的網(wǎng)絡應用中, 兩邊的行為需要預先商定.

What is a good API definition ?

Easy to learn and easy use.
Easy to be extended

RESTful 讓人欲罷不能的好處?

nil

Then Why RESTful ?

目前使用 HTTP 的接口太多, 很多設計上不太好.
充分利用 HTTP 的各種特性 (HTTP Verbs, Status Codes).
Clearly definition of endpoints (Using URL).

RESTful 3 層神功

Richardson Maturity Model

實際多數(shù)應用只修煉到第二層.
Why? Resembles OSI 7 Layer Model.

RESTful 三層神功
Level 0:

POX (plain old xml)

Request:

  HTTP1.1 POST https://test.host.com/get-profile?token=xxx

Response:

  {"code": "0",
   "msg": {
     "name": "Shawn Liu",
     "birthday": "1991-2-2",
     "id": 4302
   }
  }
Level 1:

Resources

Request:

  HTTP1.1 POST https://test.host.com/users/4302/profile?token=xxx

Response:

  {"code": "0", "user": {"name": "Shawn Liu", "birthday": "1991-2-2", ...}}

We can also define other resources like "posts", "comments"...
Now different resources can be served by different services.
It is easier to test and scale you application.

Level 2:

Verbs and status codes
HTTP Status Code

Request:

  HTTP1.1 GET https://test.host.com/users/4302/profile?token=xxx

Response:

  HTTP1.1 200 OK
  {"user": {"name": "Shawn Liu", "birthday": "1991-2-2", ...}}

  HTTP1.1 403 Forbidden
  {"msg": "You are not a good man, get out of here!"}


Request:

  HTTP1.1 POST https://test.host.com/users
  {"user": {
     "name": "Terry",
     "birthday": "1991-2-2"
   }
  }

Response:

  HTTP1.1 201 Created
  {"user": {
     "id": 4303
     "name": "Terry",
     "birthday": "1991-2-2"
   }
  }


Request:

  HTTP1.1 GET https://test.host.com/users/4303/profile?token=xxx

Response:

  HTTP1.1 200 OK
  {"user": {"name": "Terry", "birthday": "1991-2-2", ...}}
Level 3:

Verbs and status codes

Request:

  HTTP1.1 POST https://test.host.com/users

Response:

  HTTP1.1 201 Created
  {"user": {
     "id": 4303
     "name": "Terry",
     "birthday": "1991-2-2"
   },
   "links": [
     {
       "rel": "user.profile"
       "href": "https://test.host.com/users/4303/profile"
     },
     {
       "rel": "user.delete"
       "href": "https://test.host.com/users/4303"
     }
   ]
  }

Swagger

swagger 官網(wǎng)

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容