本文章用于內部分享時做PPT用稳捆,所以內容并不詳盡
Why do you need API ?
在C/S 結構的網絡應用中, 兩邊的行為需要預先商定.
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 層神功
實際多數應用只修煉到第二層.
Why? Resembles OSI 7 Layer Model.
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"
}
]
}