- 有明確的錯誤訊息
- 回傳有意義的 HTTP status code
- 能回傳指定的格式 (Multiple Output Formats)(accept: json/application)
- 好記的名字
- Deep Filtering (order, joins, pagination)
- Typed Values - response 有固定格式
- 好懂的文件 (Interactive Documentation better)
- 能夠有版本管理,有 deprecated warning
- High Performance
- High Availability
- Developer Community
- 規範有跡可循並且一致
- Sandbox mode
答案:沒有所謂的好跟壞,只有適合哪個場景。
所以要做出一個好的 API,最重要的是了解你的 API User 要拿這個 API 來做什麼。
業界常用的 Best Practice
## RESTful
常見的 API 規範:
RESTful, gRPC, GraphQL
以最常見的 RESTful (Representational State Transfer)為例說明
什麼是 RESTful? 網路上一堆複雜的說法,對我來說就是:
- 對應正確的 HTTP Request, 新增用 Post, 刪除用 Delete, 更新用 Patch, 查詢用 Get
- 每個 EndPoint 就是一個 Resource,`GET /user` 就應該回傳 User
## Authorization
* HTTP Authentication: Basic and Digest Access Authentication https://tools.ietf.org/html/rfc2617
```
Authorization: Basic xxxxxxx
```
* JWT token - https://jwt.io/
* OAuth(2)
我們? HTTP Auth + 自製 Token
## Response
* JSON format
* Error code, error message
* 正確的 status code
## Documentation
* API blueprint
* Swagger
我們:V0,V1: Test generated HTML document, can support Swagger or API blueprint. V2: Swagger
開發流程
1. 跟 Client 討論需要的數據
2. 用 Swagger 或是 API blueprint 先寫 document
3. Client 按照 document 先 mock 資料
4. Server 開發 API, 用自動化工具測試 API endpoint 是否符合 document (Bonus: easy to TDD)
5. Client & Server 一起完工,皆大歡喜
開發盲點
1. RESTful 代表我要把 Table 映射到 API response 嗎?
2. Client 要求跟 Server 的衝突,Client 想要一個request 拿到所有資訊,Server 想根據規定給 response, 例如 GET /user 還要順便拿 user.groups 的資訊
https://github.com/shieldfy/API-Security-Checklist
沒有留言:
張貼留言