--- title: Web API tags: API --- # 名詞定義 - LSUD (Large Set of Unknown Developers) 大批你所不知道的開發人員 - SSKD (Small Set of Known Developers) 少量你所知道的開發人員 ### [OpenAPI-Specification](`https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/3.0.0.md`) # API 設計規範 - URI - 短小便於輸入 - 容易識別 - 避免大小寫混用,使用 - 或 _ - 修改方便 (Hackable) - 不暴露 Server 端架構 - 規則統一 ``` http://api.example.com/friends?id=100 // bad http://api.example.com/friends/100 http://api.example.com/friends/100/message ``` - HTTP Method | Method | 說明 | | ------ | --- | | GET | 獲取資源 | | POST | 新增資源 | | PUT | 更新已有資源 | | DELETE | 刪除資源 | | PATCH | 更新部分資源 | | HEAD | 獲取資源的原訊息 | *目前大多數的主流用法都是 POST 打天下* # 數據結構 - 目前主流為 JSON or XML - 數據格式指定方式 - 查詢參數: `http://api.example.com/v1/users?format=json` - 通常使用 alt 或 format 作為參數名稱 - 副檔名: `http://api.example.com/v1/users.json` - HTTP Header 指定 Accept: ```http GET /v1/users Host: api.example.com Accept: application/json ``` ## 數據內部結構的思考方法 - Web API 不僅是訪問數據庫的接口,也是訪問程式的接口 - Chatty API : 為了完成一項任務需要多次訪問 API 的設計方式 (難用) - API 呼叫的數據量愈小越好,包含盡可能多的資料 - 數據盡可能的扁平化 # 錯誤訊息 ### 通過 Status Code 表示錯誤訊息 | Status Code | 含義 | | --- | --- | | 1xx | 訊息 | | 2xx | 成功 | | 3xx | 重新定向 | | 4xx | Client端引發的錯誤 | | 5xx | Server端引發的錯誤 | ### 詳細的錯誤訊息 - 將訊息放入 HTTP Header ```http X-ERROR-CODE: 2013 X-ERROR-MESSAGE: Bad Authentication token X-ERROR-INFO: http://docs.example.com/v1/authentication ``` - 將訊息放在 Response body ```json { "errors": [ { "code": 215, "message": "Bad authentication data", "info": "http://docs.example.com/v1/authentication" } ] } ``` # 數據暫存 通過反向代理伺服器暫存訊息以有效減少伺服器端的負載 ### 暫存模型 - 過期模型: 在 HTTP Header 內描述該次呼叫的時間點跟何時過期的訊息,在尚未過期時代理伺服器會直接返回暫存的資料。 - 驗證模型: 代理伺服器依然每次都會詢問Server端,不過在訊息仍然新鮮時只會回覆資源狀態仍然新鮮。 ### 不實施暫存的方式 在 HTTP Header 內對 Cache-Control 做設定 `Cache-Control: no-cache`: 至少需要使用驗證模型來驗證數據 `Cache-Control: no-store`: 完全不實施暫存 # API 版本定義方針 - 在 URI 內串上版本資訊 ```http http://api.example.com/v1/users ``` - 在查詢參數內帶入版本資訊 ```http http://api.example.com/users?ver=1.0 ``` - 使用 Content-type ```http POST /users HTTP/1.1 Host: api.example.com Content-Type: application/vnd.example.v2+json ``` - 使用私有 HTTP Header ```http POST /users HTTP/1.1 Host: api.example.com Content-Type: application/json GData-Version: 2.0 ``` # API 安全性 - 使用 HTTPS 加密通訊 - 明確定義 Content-Type 避免 XSS 攻擊 - IE8 需設置 X-Context-Type-Options,往前的版本沒救 - 不通過 GET 修改 Server 端的數據 - 讓 API 只允許 XMLHttpRequest 和非瀏覽器Client端訪問 - JSON 數據以 Object `({...})` 形式返回,避免 JSON 被當作 JavaScript 執行 - 在 JSON 開頭帶上`for(;;);`,醜 但非常有效
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up