Apigee Pragmatic API Design 1 – Keep API URL Simple
The orientation(定位) for APIs is to think about design choices from the application developer’s point of view. The application developer is the lynchpin(關鍵) of the entire API strategy.
- Application developer 是設計API時所參考的核心,因為他們纔是最終API的使用者,在設計API時要從他們的使用角度去思考。
The number one principle in pragmatic RESTful design is : keep simple things simple.
- RESTful的設計哲學就是簡單的事就應該保持簡單。
The point is that developers probably don’t need the chart to understand how the API behaves. They can experiment with and learn the API without the documentation.
- 簡單的設計哲學所要達成的目的就是寫出來的API不必讓developer須要花太多精力去學習瞭解API行為,他們只要靠著自己試驗而不需要文件就可以知道如何使用API。底下有三大原則用來達成API簡單化的目的。
Rule 1. Use two base URLs per resource.
- 第一點: 一個resource 代表一個Object,只需要兩個base url便可以運作該resource,其一是針對resource整體,另一是針對該resource的特定個體。
- For Example:
Base URL 1. /dogs
Base URL 2. /dogs/1234
- Dogs 是該URL的Resource,第一個URL應用對象是所有的狗;第二個對象編號為1234的狗。
Rule 2. Keep verbs out of your base URLs
- 第二點: 在URL 中我們以resource作為欲操作的Object,因此應該避免用動詞作為API名稱,這將會使API名稱變得複雜且清單冗長,對developer來說在選擇API時將會形成負擔
- For Example:
/getAllDogs : 取得所有狗狗清單
/verifyVeterinarianLocation : 驗證獸醫地址
/getSittingDog: 取得正坐著的狗狗清單
- 動詞加名詞以及修飾詞將使得API URL清單變得多且長。
Rule 3. HTTP verbs to operate on the collections and elements.
- 第三點: 利用HTTP Method來對Resource進行CRUD( Create, Read, Update, delete)
- HTTP 4個Method搭配Resource base URL便可以讓Developer輕易瞭解我們可以對每一個Resource做哪些事情,這樣就不用像第二點一樣用動詞列出每一支API造成視覺與記憶負擔。
Resource |
POST( Create) |
GET (Read) |
PUT (Update) |
DELETE (Delete) |
/dogs |
Create a new Dog |
List dogs |
Update all dogs |
Delete all dogs |
/dogs/1234 |
Error |
Show one dog |
Update one dog |
Delete one dog |
[參考] Web API Design - Crafting Interfaces tgat Develoers Love
https://pages.apigee.com/rs/apigee/images/api-design-ebook-2012-03.pdf
2018年6月5日星期二