一些基于rest的服务使用不同的资源uri进行更新/获取/删除和创建。如

Create -在某些地方使用/resource(单数)使用POST方法使用/resources(复数) 更新-使用PUT方法使用/resource/123 Get -使用Get方法使用/resource/123

我对这个URI命名约定有点困惑。我们应该用复数还是单数来创建资源?决定的标准应该是什么?


当前回答

对我来说,最好有一个模式,你可以直接映射到代码(容易自动化),主要是因为代码是什么将在两端。

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) 

其他回答

为什么不遵循数据库表名的流行趋势,通常采用单数形式?有过这样的经历,让我们重新使用。

表命名困境:单数和复数名称

我很惊讶地看到这么多人会追随复数名词的潮流。在实现单数到复数的转换时,是否注意到不规则复数名词?你喜欢疼痛吗?

看到 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)

使用单数,并利用英语惯例,如:“商业目录”。

很多东西都是这样读的:“书柜”、“狗窝”、“美术馆”、“电影节”、“汽车场”等等。

这方便地从左到右匹配url路径。左边的项目类型。在右侧设置类型。

GET /users真的获取过一组用户吗?不是很经常。它获取一组存根,其中包含一个密钥,也许还有一个用户名。所以它不是/users。它是一个用户索引,或者你可以称之为“用户索引”。为什么不这么叫呢?它是/user/index。由于我们已经命名了set类型,我们可以有多个类型来显示用户的不同投影,而无需求助于查询参数,例如user/phone-list或/user/mail -list。

那么用户300呢?仍然是/user/300。

GET /user/index
GET /user/{id}

POST /user
PUT /user/{id}

DELETE /user/{id}

最后,HTTP对单个请求只能有一个响应。路径总是指一个单数的东西。

请参阅谷歌的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   |
|--------------------------+---------------+-------------------+---------------+--------------|

如果你正在思考这个问题,这本书值得一读。

在所有方法中使用复数至少在一个方面更实用: 如果你正在使用Postman(或类似的工具)开发和测试资源API,当从GET切换到PUT再切换到POST时,你不需要编辑URI。