API Design

2018-02-03  本文已影响0人  Shawn_xiaoyu

本文章用于内部分享时做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 层神功

Richardson Maturity Model

实际多数应用只修炼到第二层.
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 官网

上一篇 下一篇

猜你喜欢

热点阅读