17611538698
webmaster@21cto.com

REST API 命名约定和最佳实践

编程语言 0 810 2022-09-23 11:09:22

在 REST 中的主数据被称为资源,而正确命名的资源将使 API 易于使用和直观访问。同样的 API,如果实施不正确,可能会让调用者感觉很复杂,并且难以使用和理解。

以下内容将帮助开发者构建正确的 API 构建资源 URI。

使用名词来表示资源/不是动词

始终确保你的 URI 以名词命名指定资源,而不是使用动词。

URI 应指明相关 CRUD(创建、读取、更新、删除)操作。另外请避免动词-名词组合:hyphenated、snake_case、camelCase。

命名不好的例子:

http://api.example.com/v1/store/CreateItems/{item-id}❌ http://api.example.com/v1/store/getEmployees/{emp-id}❌ http://api. example.com/v1/store/update-prices/{price-id}❌ http://api.example.com/v1/store/deleteOrders/{order-id}❌


命名很好的例子:

http://api.example.com/v1/store/items/{item-id} ✅http://api.example.com/v1/store/employees/{emp-id} ✅http://api. example.com/v1/store/prices/{price-id} ✅http://api.example.com/v1/store/orders/{order-id} ✅


使用复数名词表示资源


尽可能使用复数表示资源,除非它们是单例资源。

命名不好的例子(典型和单例资源):

http://api.example.com/v1/store/item/{item-id}❌ http://api.example.com/v1/store/employee/{emp-id}/address❌

命名很好的例子(典型和单例资源):

http://api.example.com/v1/store/items/{item-id} ✅http://api.example.com/v1/store/employees/{emp-id}/address ✅


使用连字符 (-) 来提高 URI 的可读性


注意,不要使用下划线。用连字符分隔单词会让自己和其他人更容易理解。当涉及到长路径分段 URI 时,它更加显得用户友好。

命名不好的例子:

http://api.example.com/v1/store/vendormanagement/{vendor-id}❌ http://api.example.com/v1/store/itemmanagement/{item-id}/producttype❌ http:// api.example.com/v1/store/inventory_management❌


命名很好的例子:

http://api.example.com/v1/store/vendor-management/{vendor-id} ✅ http://api.example.com/v1/store/item-management/{item-id}/product-输入✅ http://api.example.com/v1/store/inventory-management ✅

使用正斜杠 (/) 表示层次结构,但不要在尾部使用


正斜杠用于显示单个资源和集合之间的层次结构。

命名不好的例子:

http://api.example.com/v1/store/items/❌

命名很好的例子:

http://api.example.com/v1/store/items ✅


避免使用文件扩展名

这些扩展名不是必要的,并且会增加 URI 的长度和复杂性。

命名不好的例子:

http://api.example.com/v1/store/items.json❌ http://api.example.com/v1/store/products.xml❌

命名很好的例子:

http://api.example.com/v1/store/items ✅http://api.example.com/v1/store/products ✅

版本化 API

始终对你的 API 进行版本控制。你可以通过对 API 进行版本控制来提供升级路径,而无需对现有 API 进行任何彻底性更改。你还可以让用户知道 API 的更新版本可通过以下完全限定的 URI 访问。

http://api.example.com/v1/store/employees/{emp-id}
使用 /v2 可以避免引入任何重大的更新。
http://api.example.com/v1/store/items/{item-id} http://api.example.com/v2/store/employees/{emp-id}/address


使用查询条件过滤 URI 集合


开发者会经常遇到要求根据特定资源属性对一组资源进行排序、过滤或限制的需求。无需创建额外的 API,而是在资源集合 API 中启用排序、过滤和分页,并将输入参数作为查询参数来满足此需求。

http://api.example.com/v1/store/items?group=124 http://api.example.com/v1/store/employees?department=IT®ion=USA

请看如下例子:


GET — 读取员工 ID 为 8345 的员工

example.com/employees/8345
POST——创建员工
example.com/employees
PUT - 使用员工 ID 8345 更新员工信息
example.com/employees/8345
DELETE — 删除员工 ID 为 8345 的员工记录
example.com/employees/8345


作者:李龙飞


评论