一些基于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)

其他回答

为了简单和一致性,我更喜欢使用单数形式。

例如,考虑以下url:

/客户/ 1

我将把客户视为客户集合,但是为了简单起见,集合部分被删除了。

另一个例子:

/设备/ 1

在这种情况下,equipment不是正确的复数形式。因此,为了简单起见,将其视为设备集合和删除集合,使其与客户案例一致。

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

最重要的事情

当你在接口和代码中使用复数时,问问你自己,你的约定是如何处理这些词的:

/pants, /eye-glasses——是单数还是复数? /radii -你知道它的唯一路径是/radius还是/radix吗? /index -你知道它的复数路径是/indexes或/indexes或/indexes吗?

理想情况下,约定的规模应该没有不规则性。英语复数就不会这样,因为

它们也有例外,比如某物被称为复数形式,以及 没有简单的算法可以从一个词的单数中得到一个词的复数,从复数中得到一个词的单数,或者判断一个未知名词是单数还是复数。

这也有缺点。我脑海中最突出的是:

The nouns whose singular and plural forms are the same will force your code to handle the case where the "plural" endpoint and the "singular" endpoint have the same path anyway. Your users/developers have to be proficient with English enough to know the correct singulars and plurals for nouns. In an increasingly internationalized world, this can cause non-negligible frustration and overhead. It singlehandedly turns "I know /foo/{{id}}, what's the path to get all foo?" into a natural language problem instead of a "just drop the last path part" problem.

与此同时,一些人类语言甚至没有名词的单数形式和复数形式。他们还行。你的API也可以。

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

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

如何:

/resource/(不是/resource)

/resource/意味着它是一个包含“resource”的文件夹,它是一个“resource”文件夹。

而且我认为数据库表的命名惯例是相同的,例如,一个叫“user”的表就是一个“user”表,它包含了一个叫“user”的东西。