一些基于rest的服务使用不同的资源uri进行更新/获取/删除和创建。如
Create -在某些地方使用/resource(单数)使用POST方法使用/resources(复数) 更新-使用PUT方法使用/resource/123 Get -使用Get方法使用/resource/123
我对这个URI命名约定有点困惑。我们应该用复数还是单数来创建资源?决定的标准应该是什么?
一些基于rest的服务使用不同的资源uri进行更新/获取/删除和创建。如
Create -在某些地方使用/resource(单数)使用POST方法使用/resources(复数) 更新-使用PUT方法使用/resource/123 Get -使用Get方法使用/resource/123
我对这个URI命名约定有点困惑。我们应该用复数还是单数来创建资源?决定的标准应该是什么?
当前回答
我很惊讶地看到这么多人会追随复数名词的潮流。在实现单数到复数的转换时,是否注意到不规则复数名词?你喜欢疼痛吗?
看到 http://web2.uvcs.uvic.ca/elc/studyzone/330/grammar/irrplu.htm
不规则复数有很多种,但以下是最常见的:
形成复数形式的
Ends with -fe Change f to v then Add -s
knife knives
life lives
wife wives
Ends with -f Change f to v then Add -es
half halves
wolf wolves
loaf loaves
Ends with -o Add -es
potato potatoes
tomato tomatoes
volcano volcanoes
Ends with -us Change -us to -i
cactus cacti
nucleus nuclei
focus foci
Ends with -is Change -is to -es
analysis analyses
crisis crises
thesis theses
Ends with -on Change -on to -a
phenomenon phenomena
criterion criteria
ALL KINDS Change the vowel or Change the word or Add a different ending
man men
foot feet
child children
person people
tooth teeth
mouse mice
Unchanging Singular and plural are the same
sheep deer fish (sometimes)
其他回答
如何:
/resource/(不是/resource)
/resource/意味着它是一个包含“resource”的文件夹,它是一个“resource”文件夹。
而且我认为数据库表的命名惯例是相同的,例如,一个叫“user”的表就是一个“user”表,它包含了一个叫“user”的东西。
请参阅谷歌的API设计指南:资源名称以了解另一种命名资源的方法。
该指南要求集合以复数形式命名。
|--------------------------+---------------+-------------------+---------------+--------------|
| API Service Name | Collection ID | Resource ID | Collection ID | Resource ID |
|--------------------------+---------------+-------------------+---------------+--------------|
| //mail.googleapis.com | /users | /name@example.com | /settings | /customFrom |
| //storage.googleapis.com | /buckets | /bucket-id | /objects | /object-id |
|--------------------------+---------------+-------------------+---------------+--------------|
如果你正在思考这个问题,这本书值得一读。
为什么不遵循数据库表名的流行趋势,通常采用单数形式?有过这样的经历,让我们重新使用。
表命名困境:单数和复数名称
对我来说,最好有一个模式,你可以直接映射到代码(容易自动化),主要是因为代码是什么将在两端。
GET /orders <---> orders
POST /orders <---> orders.push(data)
GET /orders/1 <---> orders[1]
PUT /orders/1 <---> orders[1] = data
GET /orders/1/lines <---> orders[1].lines
POST /orders/1/lines <---> orders[1].lines.push(data)
复数
简单-所有url都以相同的前缀开头 逻辑——订单/获取订单的索引列表。 标准——被绝大多数公共和私有api广泛采用的标准。
例如:
GET /resources -返回资源项的列表
POST /resources -创建一个或多个资源项
PUT /resources—更新一个或多个资源项
PATCH /resources—部分更新一个或多个资源项
DELETE /resources -删除所有资源项
对于单个资源项:
GET /resources/:id -根据:id参数返回一个特定的资源项
POST /resources/:id—用指定的id创建一个资源项(需要验证)
PUT /resources/:id -更新一个特定的资源项
PATCH /resources/:id—部分更新特定的资源项
DELETE /resources/:id -删除指定的资源项
对于单数的提倡者,可以这样想:你会向某人要一份订单,并期待一件事,还是一份清单?那么,当您键入/订单时,为什么期望服务返回一列东西呢?