787

Some RESTful services use different resource URIs for update/get/delete and Create. Such as

  • Create - using /resources with POST method (observe plural) at some places using /resource (singular)
  • Update - using /resource/123 with PUT method
  • Get - Using /resource/123 with GET method

I'm little bit confused about this URI naming convention. Should we use plural or singular for resource creation? What should be the criteria while deciding that?

starball
  • 20,030
  • 7
  • 43
  • 238
JPReddy
  • 63,233
  • 16
  • 64
  • 93
  • 13
    Following this topic, I've collected a few examples of famous REST APIs in an article: http://inmensosofa.blogspot.com/2011/10/look-into-various-rest-apis.html. – jjmontes Nov 13 '11 at 11:33
  • 11
    The conclusion I reached after reading all the answers below: Always use singular because (a) it's consistent, (b) it maps directly to singular class and table names, (c) some plural nouns are irregular (unpredictable) in English – Will Sheppard Aug 28 '18 at 11:43
  • See [this answer](https://stackoverflow.com/a/21066411/137948) for a link to singular table naming conventions, and there is another an article that mentions this exact issue [Rest API Developer's Dilemma](https://metamug.com/article/rest-api-developers-dilemma.php) - thank you @Sorter – Will Sheppard Aug 28 '18 at 11:45
  • I would suggest using the Richardson Maturity Model. This helps solve this problem https://restfulapi.net/richardson-maturity-model/ – thxmike Dec 13 '21 at 14:12

27 Answers27

839

For me is better to have a schema that you can map directly to code (easy to automate), mainly because code is what is going to be at both ends.

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) 
Anton
  • 12,285
  • 20
  • 64
  • 84
jla
  • 9,684
  • 2
  • 21
  • 18
  • 34
    The difficulty or ease of this is due to not respecting HATEOS. It shouldn't matter whether it's plural or singular or anything else. You should respect the uri's sent from the server and not "build up" your uri's on the client. Then you have 0 mapping to do for your code. – richard Apr 06 '15 at 23:01
  • 14
    @richard The client still has to do mapping. In HATEOS they would have to map to a name that represents the relationship (rel) to the URI construction. The rel, method (verb) and Content-Type then make up the resource media. This does not preclude the need for a good URI design. Even though the client might give precedence to the rel name the developers of the API still need a good human-readable standard for URI construction. –  Aug 21 '15 at 19:27
  • 6
    This is a better answer in my opinion. Except that I have always preferred to use Singular instead of plural. User.getList(), User.getById, User.delete etc. – Eastern Monk Mar 30 '16 at 02:07
  • 3
    I like the simplicity. The mapping also has the benefit of making documentation and tests on routes incredibly easy to write. – thanos Mar 31 '17 at 08:15
  • 6
    This makes sense to me. However, we're a database-first shop, meaning we generate code and api entities from our database schema. And database standards tend to advocate singular table names, so we're going with that, but still under the same logic as this answer. – André C. Andersen Nov 24 '17 at 12:01
  • 1
    I was looking for arguments to choose a convention from the two answers. EasternMonk and André C. Andersen voted for this one, actually giving arguments against it. Entities are intended to be named as singulars. But you can't use singular as universal path part, because it is not suitable to GET multiple entities. So Will Hartung 's convention is less controversial. – Zon May 08 '20 at 12:36
  • If the answer points to "natural language" it's partially correct, because `POST /orders` has no sense to me in another way that "post many orders" (not a single one), `POST /order`, I think, is the correct way. – Andrés Morales Jan 07 '22 at 20:16
  • @AndrésMorales having only one referenced name is easier for memory. – I think the use case you mean is already covered by `PUT /orders/1` (*CreateOrderAt* & *UpdateOrderAt*). While we can [`POST` one or more `orders` to the collection](https://stackoverflow.com/q/32098423/3088045) (*Add* some orders, and return the created indexes). – Kamafeather Jan 07 '22 at 23:36
  • I tend to disagree with the last two lines, as they mix the /`$objectModel`/`$objectInstance` semantic with object content selection. The designated object can become quite complex (e.g., with sub-collections) and a pure `/` notation may not be sufficient. I'd leave that to the request body (with JSON or JSON-patch payload). – user1931751 Jan 22 '23 at 11:56
  • I didn't study JSON-path yet, I'll check it out further, thanks for the hint. And yes, it seems that your suggestion is a valid alternative. – Although imho (and as you mention) is more appropriate when dealing with more complex APIs or resource hierarchies; for simple APIs I'd rather prefer to identify resources exclusively via URI, with the semantic above. – Kamafeather Jan 24 '23 at 08:10
400

The premise of using /resources is that it is representing "all" resources. If you do a GET /resources, you will likely return the entire collection. By POSTing to /resources, you are adding to the collection.

However, the individual resources are available at /resource. If you do a GET /resource, you will likely error, as this request doesn't make any sense, whereas /resource/123 makes perfect sense.

Using /resource instead of /resources is similar to how you would do this if you were working with, say, a file system and a collection of files and /resource is the "directory" with the individual 123, 456 files in it.

Neither way is right or wrong, go with what you like best.

Will Hartung
  • 115,893
  • 19
  • 128
  • 203
  • 78
    Great answer! But "default" directories in Windows have **plural** names. Like "Program Files", "Users", "Documents", "Videos" etc. Also I have encountered plural names in website urls much more often. – Dmitry Gonchar Apr 12 '13 at 16:33
  • 84
    the defacto convention pretty much most people and APIs out there take is keeping it plural at all times. Ids specify ONE resource cars/id – PositiveGuy Aug 31 '15 at 13:54
  • 324
    "Neither way is right or wrong, go with what you like best.". Ah the famous line I hear so often and get sick and tired of hearing from people. Conventions matter and SHOULD be debated constructively amongst the community, that's where better solutions come about and good practices. When you are using both plural and singular for resource names in URIs, it complicates your code and the API because the user and the code behind the API has to account for that in routes and logic to differentiate single vs. plural whereas if you just stick with plural all the time you have no problems. – PositiveGuy Aug 31 '15 at 13:59
  • 4
    @WTF this is completely not true. the URI templates should be completely opaque. Here's a quote from Roy Fielding's dissertation "At no time whatsoever do the server or client software need to know or understand the meaning of a URI". It should not be necessary to construct or deconstruct a URI on clients and servers. A good API should work equally well even with all URLs using GUIDs like `http://example.org/{GUID}`. This is because URLs should be communicated as links. Client's don't care how server assigns identifiers and server-side routing can be mitigated by using complete URLs as ids – Tomasz Pluskiewicz Dec 30 '15 at 18:06
  • 34
    @TomaszPluskiewicz You are entirely right that _clients_ do not care. As _software developers_ we **should** care -- and for that I agree with WTF's comment that constructive debates about convention are valuable. – Travis D Feb 19 '16 at 22:24
  • @TravisD you are right that constructive debate is valuable. but in this case common arguments, such as WTF saying that *using both plural and singular for resource names in URIs, complicates your code* is out of place. The client should never construct the identifiers thus it is not a good argument – Tomasz Pluskiewicz Feb 20 '16 at 10:44
  • 5
    I would advice that stick to either one of them. Singular plural is something that English-speaking humans can understand easily but it is not trivial for the machine to understand. Is Inventory singular or plural ? Why is User's plural is User+s but for Baby it is Babies? This makes it very inconsistent. for a machine. – Eastern Monk Mar 30 '16 at 02:05
  • 30
    So can someone just put a one word answer and have it accepted so I don't have to read this all (again). – Ben George Sep 27 '16 at 04:58
  • 2
    Usually the slash '/' at the end of a URL represents a container. I.e the container /resource/ basically has sub-resources /resource/12 and /resource/23.. – Sven R. Kunze Jan 30 '17 at 14:46
  • how do you create a url for search on resources .. /resources/search?queryParam – user1428716 Sep 24 '17 at 10:32
  • 4
    I believe you should be using plural when referring to a single item. Maybe both are accepted as REST best practices but plural is more common. GET /resources (list of all of them) GET /resources/{id} (a single resource) – gimbel0893 Jan 25 '18 at 19:54
  • 4
    I disagree with having different URLs for a single GET vs GET list. This means users need to manage additional URL's depending on their method. Keep it all the same for the best ease of use – Goldfish Mar 25 '19 at 20:30
  • 2
    Let's take StackOverflow as a point of reference. The current URL is stackoverflow.com/questions/6845772/title-of-the-question-with-hyphens I believe this somewhat elaborates a bit more on the good practices used by tech giants. – Patrick Younes Feb 23 '20 at 12:47
  • Everyone does so - is not an argument. I've tried to find convincing arguments in both answers and comments. See - https://stackoverflow.com/questions/6845772/rest-uri-convention-singular-or-plural-name-of-resource-while-creating-it#comment109100628_21809963 – Zon May 08 '20 at 12:40
333

I don't see the point in doing this either and I think it is not the best URI design. As a user of a RESTful service I'd expect the list resource to have the same name no matter whether I access the list or specific resource 'in' the list. You should use the same identifiers no matter whether you want use the list resource or a specific resource.

Jan Deinhard
  • 19,645
  • 24
  • 81
  • 137
  • 95
    This is the best answer as far as I'm concerned. I appreciate that API designers like the linguistic correctness of saying "get resource #123", but it's extra coding hassle when writing clients of the API as well as help documentation. (GET /api/people vs. GET /api/person/123? euuuchh.) .... instead of thinking of it like "get resource #123", phrase it in your head like "get from the collection of resources that matches #123". – Warren Rumak Mar 06 '14 at 21:36
  • @WarrenRumak actually there should be no hassle if APIs were hypermedia-driven. Alas, most aren't. Anyway, in such case naming would be of secondary importance during implementation – Tomasz Pluskiewicz Dec 07 '14 at 10:22
  • 5
    Distinguishing plural/singular resources is not about linguistic correctness but about scale. /employees/12 reads to me as the subset of the employees resource with id '12' (it could mean anything, for instance a saved search query on recently fired employees). If you read the above as the employee with id '12', how would you represent the subset? The only option is by making URI's more complex ore distinguishing collections containing objects from the objects themselves (i.e. singular vs plural). – Erik Dec 23 '14 at 12:07
  • 10
    Choosing /employees/12 to represent a search query on recently fired employees (or any subset) would be bad design I think. If you want to represent subsets of any kind than I suggest to introduce them as resources (with proper names) in their own right. – Jan Deinhard Feb 05 '15 at 12:17
  • @WarrenRumak you are thinking in terms for the client building up the urls. If the API is implementing proper HATEOS and the client is consuming it with that expectation, it shouldn't matter whether it's people or person or anything else...the uri is determined by the server. – richard Apr 06 '15 at 22:55
  • @Erik It's not a good uri because it doesn't properly establish a vector. You are correct...what does 12 represent? Better is to use vectors, i.e. /employee/id/12. Then you can do /employees/fired?top=12 or /employees/hired?top=12 or /employees/hr?top=12 etc. and veer off into any other meaningful (for your domain) set of vectors. – richard Apr 06 '15 at 23:00
  • 1
    It shouldn't matter, @richard, but it -does-, for a variety of reasons. One important one is language itself: It's more challenging for non-native speakers of the language which you specify your REST API in. Japanese, e.g., has no pluralization of nouns, and many nouns have the same word either way (Romanian for both 'name' and 'names' is 'nume'). And what's the plural of acronyms like "BIOS" supposed to be? If your goal is to communicate "many" via a URI, you're going to run into hard failures like this from time to time. The extra complication is best avoided -- it wins you exactly nothing. – Warren Rumak Apr 08 '15 at 01:00
  • @WarrenRumak Your comment above says " I appreciate that API designers like the linguistic correctness of saying "get resource #123", but it's extra coding hassle when writing clients of the API as well as help documentation." Your previous point being that while linguistically more correct, it's extra coding hassle etc. But now you say it's more linguistically difficult - which is it? I think being consistent with the language you are writing in is easier for non-native speakers to understand than deviating from the language to compensate non-issues (coding hassle). – richard Apr 08 '15 at 02:13
  • 2
    You're having difficulty understanding my position, richard? Okay, I'll try to simplify it for you: It is not 'more consistent', 'easier to program', 'easier to maintain' or 'easier to monitor' a program where you use two different words to represent one type of resource. Consider "person" vs. "people": Whether you're a sysadmin scanning a logfile, a Chinese developer weak with English, or any developer learning your API for the first time, this presents a roadblock that increasing learning time while providing ZERO BENEFIT to the functioning of the app. – Warren Rumak Apr 09 '15 at 12:38
  • 4
    This has nothing to do with understandability for the clients. It's about addressing different things with different URLs. And being able to respond to all HTTP methods without being in conflict. You can have a resource that is a collection of items, and a resource that represents an item itself. For all I care the collections resource could be https://example.org/166316e2-e1and one particular item in that collection https://example.org/20d68348-ccc-001c4200de. The client should not construct URLs (that obviously doesn't scale, it isn't RESTful and that's what link relation types are for). – Erik Apr 13 '15 at 13:53
  • 4
    If you don't think arbitrary URLs are pretty, feel free to identify a collection resource with a plural name and an individual item with a singular name. If you don't like english URLs and your natural language doesn't support that way of singualr/plural notation use something else to define it in your preferred language I suppose all languages enable you to somehow distinguish '/the-collection-of-bla/2321' versus 'bla/61' in writing. And each of those two different resources represent completely different results when sending GET/PUT/DELETE/POST/PATCH and others. – Erik Apr 13 '15 at 13:53
159

Plural

  • Simple - all urls start with the same prefix
  • Logical - orders/ gets an index list of orders.
  • Standard - Most widely adopted standard followed by the overwhelming majority of public and private APIs.

For example:

GET /resources - returns a list of resource items

POST /resources - creates one or many resource items

PUT /resources - updates one or many resource items

PATCH /resources - partially updates one or many resource items

DELETE /resources - deletes all resource items

And for single resource items:

GET /resources/:id - returns a specific resource item based on :id parameter

POST /resources/:id - creates one resource item with specified id (requires validation)

PUT /resources/:id - updates a specific resource item

PATCH /resources/:id - partially updates a specific resource item

DELETE /resources/:id - deletes a specific resource item

To the advocates of singular, think of it this way: Would you ask a someone for an order and expect one thing, or a list of things? So why would you expect a service to return a list of things when you type /order?

Eric Knudtson
  • 2,204
  • 2
  • 18
  • 12
  • 23
    **Singular**: In case, when part of your system is only one object (0-1, exists or not) e.g. users/1/avatar you can use singular form for label this single object (e.g. avatar) - more detailed example here: https://stackoverflow.com/a/38296217/860099 . BTW - very nice answer :) – Kamil Kiełczewski May 09 '18 at 14:05
  • 1
    What about mapping to class and table names, which should be singular? (see [other answer](https://stackoverflow.com/a/33824071/137948)) – Will Sheppard Aug 28 '18 at 11:20
  • 3
    @WillSheppard - Class names are best in singular form and table names are best in plural form. For example `Order` is a good name for a class that deals with singular instances of objects referring to one order. `OrderList` is a name for a class that deals with multiple `Order` instances. `Orders Table` is a good name for a database table of many orders. – Eric Knudtson Aug 29 '18 at 23:51
  • I want to GET /orders but I only want /1 – jim smith Oct 15 '18 at 00:18
  • @jim-smith then why don’t you request /1 from the collection of users with GET /users/1? – tim-phillips Mar 05 '20 at 15:08
  • @EricKnudtson I completely agree with your answer. But your last example is not perfect, here is another one: if you take a file with label `order` you may expect multiple ones inside, because you know it's a folder. But still plural wins, even in this case. – kiedysktos Sep 02 '20 at 10:57
  • 5
    The plural vs singular debate for table names has always been complicated by the fact that a table defines both its schema/structure(implying singular) as well as being the container/collection for the data(implying plural). You don't have this problem in a programming language because the class definition is singular, but a property holding a collection would be plural. Point being, don't even try to apply class naming conventions to table, and in turn don't apply table naming conventions to rest services. – AaronLS Sep 27 '21 at 20:10
  • What about creating a new (single) resource (without pre-existing id) vs creating a bunch of new resources (batch operation)? – vladich Nov 17 '22 at 23:22
88

Singular

Convenience Things can have irregular plural names. Sometimes they don't have one. But Singular names are always there.

e.g. CustomerAddress over CustomerAddresses

Consider this related resource.

This /order/12/orderdetail/12 is more readable and logical than /orders/12/orderdetails/4.

Database Tables

A resource represents an entity like a database table. It should have a logical singular name. Here's the answer over table names.

Class Mapping

Classes are always singular. ORM tools generate tables with the same names as class names. As more and more tools are being used, singular names are becoming a standard.

Read more about A REST API Developer's Dilemma

For things without singular names

In the case of trousers and sunglasses, they don't seem to have a singular counterpart. They are commonly known and they appear to be singular by use. Like a pair of shoes. Think about naming the class file Shoe or Shoes. Here these names must be considered as a singular entity by their use. You don't see anyone buying a single shoe to have the URL as

/shoe/23

We have to see Shoes as a singular entity.

Reference: Top 6 REST Naming Best Practices

Sorter
  • 9,704
  • 6
  • 64
  • 74
  • 58
    *Singular names are always there* `/clothe/12/trouser/34` :) – Gert Arnold Feb 20 '16 at 15:33
  • 24
    @GertArnold the word `clothe` is a verb. Rest APIs generally stick to nouns when talking about resources and use verbs when describing actions. The singular form is `clout`, but is archaic and would likely be more suitably replaced by `garment`. – Steve Buzonas Jun 14 '17 at 19:58
  • 2
    @SteveBuzonas And for trousers and sunglasses? – Koray Tugay May 07 '20 at 00:47
  • 2
    And the contrary /fish/fish{id}. There are also problems when grouping due to the use of mass nouns which can be archaic also : /murders/murder{id}/crow{id}; /gaggles/gaggle{id}/goose{id}. So it is also possible to pluralise a plural. A 'simple standard rule' will never work, there will always be a mismatch between the rule and the 'natural' human expressiveness of language somewhere. The real question is whether to a) accept a clumsy uri design as a de facto standard b) reject a crude and over simplistic 'standard convention'. – Jon Guiton Nov 26 '20 at 07:41
  • 1
    @Koray Tugay trousers are interesting because they are historically considered a pair (one for each leg), not always necessary connected at the top throughout history. So they are more like socks or shoes that always are a pair. – einord Aug 10 '21 at 06:42
  • Singular names are not becoming standard and most of this answer is based on personal preference. – Software Engineer Mar 31 '22 at 17:29
41

Why not follow the prevalent trend of database table names, where a singular form is generally accepted? Been there, done that -- let's reuse.

Table Naming Dilemma: Singular vs. Plural Names

Community
  • 1
  • 1
Slawomir
  • 3,194
  • 1
  • 30
  • 36
  • 10
    Das Auto is way better than Die Autos. Also, English plural conventions are not consistent. – FlavorScape Jun 12 '14 at 16:05
  • 11
    The resource namespace is a matter of semantics, not implementation. So, using the DB tables analogy, is not very fortunate. Also when working with DB-s you are manipulating only tables, though of course you can affect the content (rows), but in REST there is no constraint to manipulate a **single** resource directly. – arpadf Jun 23 '14 at 06:44
  • 5
    I think this is a good analogy, but more important than deciding whether to go singular or plural is to be consistent with whichever you choose. You're not going to insert into Users and then select from User. Same rule should apply to REST resources - don't rename them depending what you're doing. – Todd Menier Mar 03 '15 at 18:34
  • 5
    Its not just table names, its also comparable to class names in OO (my class would be called Customer not Customers). – bytedev Apr 06 '17 at 13:04
  • In this case, semantic is too much important to simply accept "already defined" trends – Cattani Simone Jan 16 '18 at 09:12
  • we are node developers. we are smarter than database admins :-D – Josh Woodcock Aug 19 '19 at 10:10
  • This. Standardizing the convention throughout the stack makes it so much easier to navigate as a dev that is unfamiliar with the project, or simply forgot because they haven't worked on it for a long time. – Natalie Jan 26 '23 at 14:41
36

Whereas the most prevalent practice are RESTful apis where plurals are used e.g. /api/resources/123 , there is one special case where I find use of a singular name more appropriate/expressive than plural names. It is the case of one-to-one relationships. Specifically if the target item is a value object(in Domain-driven-design paradigm).

Let us assume every resource has a one-to-one accessLog which could be modeled as a value object i.e not an entity therefore no ID. It could be expressed as /api/resources/123/accessLog. The usual verbs (POST, PUT, DELETE, GET) would appropriately express the intent and also the fact that the relationship is indeed one-to-one.

Carrie Kendall
  • 11,124
  • 5
  • 61
  • 81
redzedi
  • 1,957
  • 21
  • 31
  • 6
    Nice try. But it would be better as "accessLogEntries". :-) – Tom Russell Oct 02 '16 at 11:15
  • 10
    @TomRussell why? The implications of this are important. I understand why you would use plural even when you're accessing a resource by an identifier, but for a many-to-one or one-to-one it's quite misleading. Consider an api that manages staff members for a multi-location company. Each staff member works at one location. `GET /users/123/location` should fetch the location that the user works at. Isn't `GET /users/123/locations` really misleading as a consumer? – Carrie Kendall Jan 27 '17 at 14:39
  • 1
    @CarrieKendall I see your point. Since `accessLog` is modeled as an attribute, or value, rather than an entity it should be singular. If you're given to over-engineering, then a log entry would be an entity and you'd have `/api/accessLogEntries?resource=123`. – Tom Russell Jan 31 '17 at 19:24
  • Agreed, although, I think it does break convention of pluralize all the things. It's a tricky one. To me, it's important than an API be straight-forward ie documentation should compliment an already straight-forward implementation. – Carrie Kendall Jan 31 '17 at 19:27
  • 1
    I'm more of a programmer than a systems or database person so I like an API that tells a story rather than adheres to convention. The implications for automated documentation are real, though. – Tom Russell Jan 31 '17 at 19:56
  • This makes sense to me. If you think of the file system/website analogy, plurals represent folder names whereas singular names represent files. A [PUT should be used for both creation and updating](https://stackoverflow.com/q/630453/120955) on the `api/resources/123/accessLog` endpoint: since there's no need for an ID or a new URL to represent the accessLog after it's created, a POST doesn't make sense there. – StriplingWarrior Nov 28 '17 at 17:18
29

I am surprised to see that so many people would jump on the plural noun bandwagon. When implementing singular to plural conversions, are you taking care of irregular plural nouns? Do you enjoy pain?

See http://web2.uvcs.uvic.ca/elc/studyzone/330/grammar/irrplu.htm

There are many types of irregular plural, but these are the most common:

Noun type Forming the plural Example

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)
Lizzy
  • 2,033
  • 3
  • 20
  • 33
  • 16
    I don't understand the concern here. We are not supposed to change singular to plural programatically. Most of above plural forms are well known, and should not be a concern. If someone has poor English knowledge, he is going to spell any part of your variable incorrectly. Also, going by your logic, do you also recommend using singular forms to refer collections in source code as well? – kishor borate Apr 18 '19 at 05:58
  • 4
    There are English words which are irregular to the point where it's often a problem even within the Anglosphere and they're commonly used terms such as index/indexes/indices, vertix/vertixes/vertices, matrix/matrixes/matrices, radius/radiuses/radii, etc. I don't see the point in making REST paths plural anyway, because if they're all consistently singular, it's just more obvious to everyone. – damd Nov 08 '19 at 10:44
  • 2
    @kishorborate, Using plural as URI is more error-prone, even for native English speakers. As damd indicates, plurals like index/indexes/indices are introducing more problems. And there are uncountable nouns. Mixing uncountable nouns with plurals is another problem. Why make it harder for programmers to spend more time on these? I suggest using singulars for everything. If there is an /{id}, then the API should return a single record. If there is not an /{id} that follows, then API should return the collection. – Daming Fu Nov 28 '19 at 08:46
  • 3
    @DamingFu Singular resource may not always have id associated with it. eg. /user/{id}/nickName By looking at it, it's not clear, whether it will return list of nickNames or single nickName? Hence, APIs are more intuitive when it uses plural forms. Yes, few words will have irregular plural forms. For someone who is reading the plural form, is not an issue. It's issue only when writing the API signature. But frequency of such words is not high, also, finding the plural form of any word is not time consuming. It's trade off we should accept, to make APIs more intuitive. – kishor borate Dec 06 '19 at 11:03
  • @kishorborate "We are not supposed to change singular to plural programatically." This is wrong - inconsiderate of the needs of API *users* (and everyone upvoting that comment is guilty of the same unless they're upvoting it just because the answer could be better by preemptively addressing that shortsighted objection). Think ahead to what your user's code might need to do. Is there *never* (or rarely enough to disregard) a use-case where given the URL to one thing, code will need to look up many of that thing, or where given the URL to many things, code will need the URL to one thing? – mtraceur Aug 31 '22 at 20:07
  • @kishorborate 2) the minimum necessary programmatic difficulty is *inherently a representation of objective difficulty* - irregular English plurals is something English speakers consistently take long to learn and get wrong, precisely because they have to gradually train this table/algorithm into their subconscious cognition - what you'd have to do programmatically is a representation of the overhead you're potentially inflicting on your users (which, increasingly, are not going to be fluent and precisely correct English speakers). – mtraceur Aug 31 '22 at 20:15
  • @kishorborate 3) indexes/indeces/indices - which of those is the "correct" plural? Trick question, there is substantial disagreement in real world usage, so it doesn't matter - what matters is that for any given API using plurals, any one of those could've been chosen! And when your user types one of them and it happens to be different than the one the developer thought was right, it's not an intuitive experience, it's a frustrating one. – mtraceur Aug 31 '22 at 20:20
  • @kishorborate I *do* agree with you that there *is* an intuition improvement to plurals - `/cars` obviously returns a plural, `/car` seems like it does not. But API users are programmers, and it's not unreasonable for the API to ask them to think in ways that are generally useful and already necessary for programming. `car` is *a type* - we don't pluralize `int` or `bool` types in programming languages when working with arrays. – mtraceur Aug 31 '22 at 20:33
  • @kishorborate And yes, I know we could solve the conversion problems for both users and code in other ways - for example, by having resources always return links to their plural and singular forms in their data. But that's not *free* - it has an implementation and maintenance cost. So at best we just take the cost of this intuition improvement into our API implementation instead of inflicting it onto our users. Except it's not a strict intuitiveness improvement for everyone, and embracing plurals in an API will eventually bite people once one of the edge cases crosses their path. – mtraceur Aug 31 '22 at 20:46
  • @kishorborate Oh, also, your point about `/user/{id}/nickname` is good, but it *is* clear in the everything-is-singular world: it returns a list of course, because it doesn't have another `/{id}` after it. Even if your system only ever has one nickname for a user, and you can predict that you will never need to have more than one, it's very reasonable to just make a new nickname entry every time it changes, for many reasons, so `/nickname` could just list whichever of those entries the user wants and is allowed to see. – mtraceur Aug 31 '22 at 23:17
29

See Google's API Design Guide: Resource Names for another take on naming resources.

The guide requires collections to be named with plurals.

|--------------------------+---------------+-------------------+---------------+--------------|
| 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   |
|--------------------------+---------------+-------------------+---------------+--------------|

It's worthwhile reading if you're thinking about this subject.

Shannon Matthews
  • 9,649
  • 7
  • 44
  • 75
  • One of the few posts citing an authority. So many other posts make well reasoned arguments, but don't demonstrate the long term effects of their proposal with real-world empirical evidence of how it works out in practice. An organization like Google has a lot of APIs and use cases so this seems worthy of our attention. – Tristan Apr 24 '23 at 14:31
26

From the API consumer's perspective, the endpoints should be predictable so

Ideally...

  1. GET /resources should return a list of resources.
  2. GET /resource should return a 400 level status code.
  3. GET /resources/id/{resourceId} should return a collection with one resource.
  4. GET /resource/id/{resourceId} should return a resource object.
  5. POST /resources should batch create resources.
  6. POST /resource should create a resource.
  7. PUT /resource should update a resource object.
  8. PATCH /resource should update a resource by posting only the changed attributes.
  9. PATCH /resources should batch update resources posting only the changed attributes.
  10. DELETE /resources should delete all resources; just kidding: 400 status code
  11. DELETE /resource/id/{resourceId}

This approach is the most flexible and feature rich, but also the most time consuming to develop. So, if you're in a hurry (which is always the case with software development) just name your endpoint resource or the plural form resources. I prefer the singular form because it gives you the option to introspect and evaluate programmatically since not all plural forms end in 's'.

Having said all that, for whatever reason the most commonly used practice developer's have chosen is to use the plural form. This is ultimately the route I have chosen and if you look at popular apis like github and twitter, this is what they do.

Some criteria for deciding could be:

  1. What are my time constraints?
  2. What operations will I allow my consumers to do?
  3. What does the request and result payload look like?
  4. Do I want to be able to use reflection and parse the URI in my code?

So it's up to you. Just whatever you do be consistent.

cosbor11
  • 14,709
  • 10
  • 54
  • 69
  • 2
    Seems like the *plural* form has been chosen because developers seem to assume that all resources are inherently part of some collection. However, the "accepted convention" seems to indicate that `POST /users` should create a single user, adding it to the collection. I disagree. `POST /users` should create a list of users (even if that is a list of 1), where as `POST /user` should create exactly one user. I see no reason why both plural and singular resource endpoints can't co-exist. They describe different behaviors, and shouldn't surprise anyone of their function. – crush Nov 03 '15 at 03:20
  • Isn't there a convention for specifying a resource id in the path? If so, it seems to be widely neglected. For instance, `POST users/` would create a new user. – Tom Russell Oct 02 '16 at 19:20
  • 2
    @TomRussell usually the server creates the id, so you wouldn't know the id to POST to yet. – Alex Feb 16 '17 at 02:02
  • 4
    @TomRussell, when the client determines (a kind of) id when creating a new resource, it is more common to use `PUT /users/` instead of `POST`. `POST` has the interpretation "add this to the collection, and determine the id as part of that". `PUT` has the interpretation "update (or add) this resource with this id." See http://restcookbook.com/HTTP%20Methods/put-vs-post/ for a longer explanation of this principle. – Jochem Schulenklopper Sep 13 '17 at 15:25
  • I don't believe the comparison to Twitters API is fair as they use the Plural form for all their endpoints. They do not mix Plural and Singular for the same Elements. – Andrew T Finnell Jul 19 '19 at 19:23
  • @AndrewTFinnell - thats the point I was mentioning about twitter – cosbor11 Jul 22 '19 at 23:07
  • Sorry but I voted this down because it violates REST best practices to have two independent URLs that can refer to the same resource. /resource/x and /resources can BOTH include the /resource/x but are independent URLs. Consider a caching system that sees GET /resources, then PUT /resource/x, then GET /resources again. It would be valid for the caching system to presume that a PUT to anything under /resource doesn't affect anything in /resources and thus provided a cached response of the first GET for the second one. – DaBlick Oct 18 '19 at 15:27
  • 1
    @DaBlick - can you site your "best practices" source? – cosbor11 Oct 28 '19 at 21:55
13

An id in a route should be viewed the same as an index to a list, and naming should proceed accordingly.

numbers = [1, 2, 3]

numbers            GET /numbers
numbers[1]         GET /numbers/1
numbers.push(4)    POST /numbers
numbers[1] = 23    PUT /numbers/1

But some resources don't use ids in their routes because there's either only one, or a user never has access to more than one, so those aren't lists:

GET /dashboard
DELETE /session
POST /session
GET /users/{:id}/profile
PUT /users/{:id}/profile
TiggerToo
  • 635
  • 7
  • 24
  • 1
    Do not use POST /login. Use POST /sessions to add a session to sessions collection (effectively log the user in) and use DELETE /sessions to remove a session from sessions collection (effectively log the user out) – Henno Jan 03 '22 at 20:48
  • 3
    I think using session for the login POST makes sense, but I don't agree about pluralizing it. Your user/browser combo never has access to more than one session at a time. You have one, and when you're done it gets deleted. There's no piece of code on either the front end or back end that's ever going to refer to multiple sessions for the user. That to me makes it singular. – TiggerToo Jan 09 '22 at 14:14
  • Sorry Henno, but I am siding with TiggerToo on this one. My variable name for these is usually user_list or session_list perse. It may sound redundant but I think it's a good habbit when using a dynamically typed language. And many plurals are not regular, so I stick to singulars. – tacan Oct 01 '22 at 16:33
9

My two cents: methods who spend their time changing from plural to singular or viceversa are a waste of CPU cycles. I may be old-school, but in my time like things were called the same. How do I look up methods concerning people? No regular expresion will cover both person and people without undesirable side effects.

English plurals can be very arbitrary and they encumber the code needlessly. Stick to one naming convention. Computer languages were supposed to be about mathematical clarity, not about mimicking natural language.

Guichito
  • 127
  • 1
  • 6
  • 3
    This addresses code that tries to "auto generate/mangle" endpoints (there are many opinionated libraries that assume plurality/singularity and attempt to map); however, this does to apply to *explicitly* chosen endpoint names any more than the picking the right word (regardless of how it's pluralized). – user2864740 Mar 11 '18 at 20:34
  • Compute languages are meant for people to easily read and understand it! – Walnussbär Nov 23 '22 at 17:08
8

I prefer using singular form for both simplicity and consistency.

For example, considering the following url:

/customer/1

I will treat customer as customer collection, but for simplicity, the collection part is removed.

Another example:

/equipment/1

In this case, equipments is not the correct plural form. So treating it as a equipment collection and removing collection for simplicity makes it consistent with the customer case.

ivxivx
  • 81
  • 1
  • 1
  • 3
    POST /customer sounds like it's going to replace the one and only customer. This is my biggest grief with using singular resource names. – Andrew T Finnell Apr 03 '18 at 14:43
  • 2
    @andrew-t-finnell Isn't `POST /customer` supposed to do the very thing - insert a single customer? – donmutti Apr 22 '19 at 01:01
  • It inserts a single Customer into a collection of Customers. `POST /customer` reads to me as though it is POST'ing to `the` customer. Not a collection of Customers. However, I'll admit that Plural or not Plural is a preference. As long as they aren't mixed like the other Answer has. That would be incredibly confusing. – Andrew T Finnell Jul 19 '19 at 18:25
  • "POST'ing to the customer" doesn't make sense in this case. POST doesn't replace, it inserts. Maybe if it were POST /customer/1 I could see the dilemma, but even that doesn't make much sense from a REST perspective, because what are you inserting? It would be /customer/1/invoice or /customer/1/receipt, etc. – damd Nov 08 '19 at 10:47
  • As you'll ultimately end up using OOP classes at some point, validation, linting and auto completion. In OOP you use classes are usually singular Objects, like Bike, User, Car... To make classes match the API name... I use singular. Some languages require a seperate word for plural, it's no different than Child-duren or Child.find() or `GET child?q=""`. You need protections against accidental multi regardless, most endpoints should have multi... using singular doesn't change that. For REST native API's plural seems the standard. If rest is secondary to your application, singular is easier. – Ray Foss Dec 09 '21 at 17:33
7

The Most Important Thing

Any time you are using plurals in interfaces and code, ask yourself, how does your convention handle words like these:

  • /pants, /eye-glasses - are those the singular or the plural path?

  • /radii - do you know off the top of your head if the singular path for that is /radius or /radix?

  • /index - do you know off the top of your head if plural path for that is /indexes or /indeces or /indices?

Conventions should ideally scale without irregularity. English plurals do not do this, because

  1. they have exceptions like one of something being called by the plural form, and
  2. there is no trivial algorithm to get the plural of a word from the singular, get the singular from the plural, or tell if an unknown noun is singular or plural.

This has downsides. The most prominent ones off the top of my head:

  1. 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.
  2. 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.
  3. 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.

Meanwhile, some human languages don't even have different singular and plural forms for nouns. They manage just fine. So can your API.

mtraceur
  • 3,254
  • 24
  • 33
5

I don't like to see the {id} part of the URLs overlap with sub-resources, as an id could theoretically be anything and there would be ambiguity. It is mixing different concepts (identifiers and sub-resource names).

Similar issues are often seen in enum constants or folder structures, where different concepts are mixed (for example, when you have folders Tigers, Lions and Cheetahs, and then also a folder called Animals at the same level -- this makes no sense as one is a subset of the other).

In general I think the last named part of an endpoint should be singular if it deals with a single entity at a time, and plural if it deals with a list of entities.

So endpoints that deal with a single user:

GET  /user             -> Not allowed, 400
GET  /user/{id}        -> Returns user with given id
POST /user             -> Creates a new user
PUT  /user/{id}        -> Updates user with given id
DELETE /user/{id}      -> Deletes user with given id

Then there is separate resource for doing queries on users, which generally return a list:

GET /users             -> Lists all users, optionally filtered by way of parameters
GET /users/new?since=x -> Gets all users that are new since a specific time
GET /users/top?max=x   -> Gets top X active users

And here some examples of a sub-resource that deals with a specific user:

GET /user/{id}/friends -> Returns a list of friends of given user

Make a friend (many to many link):

PUT /user/{id}/friend/{id}     -> Befriends two users
DELETE /user/{id}/friend/{id}  -> Unfriends two users
GET /user/{id}/friend/{id}     -> Gets status of friendship between two users

There is never any ambiguity, and the plural or singular naming of the resource is a hint to the user what they can expect (list or object). There are no restrictions on ids, theoretically making it possible to have a user with the id new without overlapping with a (potential future) sub-resource name.

seh
  • 14,999
  • 2
  • 48
  • 58
john16384
  • 7,800
  • 2
  • 30
  • 44
  • In your example what would you expect `GET /user/{id}/friend` to represent? I like to ensure that if you remove a portion of the URL a resource is still returned, going on your example, I assume (rightly or wrongly) this would return all the friends of user `{id}` but this contradicts your use of plurals and nouns. – berimbolo Aug 27 '20 at 06:53
  • 2
    The plural version is in the answer `/user/{id}/friends`, and which would return all the friends. The singular version `/user/{id}/friend` would be a bad request 400, just like `/user`. – john16384 Aug 27 '20 at 22:38
4

With naming conventions, it's usually safe to say "just pick one and stick to it", which makes sense.

However, after having to explain REST to lots of people, representing endpoints as paths on a file system is the most expressive way of doing it.
It is stateless (files either exist or don't exist), hierarchical, simple, and familiar - you already knows how to access static files, whether locally or via http.

And within that context, linguistic rules can only get you as far as the following:

A directory can contain multiple files and/or sub-directories, and therefore its name should be in plural form.

And I like that.
Although, on the other hand - it's your directory, you can name it "a-resource-or-multiple-resources" if that's what you want. That's not really the important thing.

What's important is that if you put a file named "123" under a directory named "resourceS" (resulting in /resourceS/123), you cannot then expect it to be accessible via /resource/123.

Don't try to make it smarter than it has to be - changing from plural to singluar depending on the count of resources you're currently accessing may be aesthetically pleasing to some, but it's not effective and it doesn't make sense in a hierarchical system.

Note: Technically, you can make "symbolic links", so that /resources/123 can also be accessed via /resource/123, but the former still has to exist!

Narf
  • 14,600
  • 3
  • 37
  • 66
3

I know most people are between deciding whether to use plural or singular. The issue that has not been addressed here is that the client will need to know which one you are using, and they are always likely to make a mistake. This is where my suggestion comes from.

How about both? And by that, I mean use singular for your whole API and then create routes to forward requests made in the plural form to the singular form. For example:

GET  /resources     =     GET  /resource
GET  /resources/1   =     GET  /resource/1
POST /resources/1   =     POST /resource/1
...

You get the picture. No one is wrong, minimal effort, and the client will always get it right.

wynnset
  • 49
  • 3
  • 3
    If you are doing 302 redirects and your cache is storing everything twice, you have set up your cache wrong. Cache is not supposed to store 302 redirects. – wynnset May 06 '18 at 16:30
  • 2
    If you client always uses `/resources` and always get redirected to `/resource`, you've done it wrong. If someone else uses your API, they can either use the correct URL directly or be redirected (which works but is wrong) and it was you who opened the wrong way. – maaartinus May 07 '18 at 01:14
  • Not sure by what you mean "wrong" - that's very subjective. It's not really wrong because it does work. – wynnset May 17 '18 at 22:21
  • This increases the maintenance cost, and the cost of understanding, and the amount of code required. – Will Sheppard Aug 28 '18 at 11:25
3

Use Singular and take advantage of the English convention seen in e.g. "Business Directory".

Lots of things read this way: "Book Case", "Dog Pack", "Art Gallery", "Film Festival", "Car Lot", etc.

This conveniently matches the url path left to right. Item type on the left. Set type on the right.

Does GET /users really ever fetch a set of users? Not usually. It fetches a set of stubs containing a key and perhaps a username. So it's not really /users anyway. It's an index of users, or a "user index" if you will. Why not call it that? It's a /user/index. Since we've named the set type, we can have multiple types showing different projections of a user without resorting to query parameters e.g. user/phone-list or /user/mailing-list.

And what about User 300? It's still /user/300.

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

POST /user
PUT /user/{id}

DELETE /user/{id}

In closing, HTTP can only ever have a single response to a single request. A path is always referring to a singular something.

Samuel Danielson
  • 5,231
  • 3
  • 35
  • 37
3

Here's Roy Fielding dissertation of "Architectural Styles and the Design of Network-based Software Architectures", and this quote might be of your interest:

A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time.

Being a resource, a mapping to a set of entities, doesn't seem logical to me, to use /product/ as resource for accessing set of products, rather than /products/ itself. And if you need a particular product, then you access /products/1/.

As a further reference, this source has some words and examples on resource naming convention:

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
2

Using plural for all methods is more practical at least in one aspect: if you're developing and testing a resource API using Postman (or similar tool), you don't need to edit the URI when switching from GET to PUT to POST etc.

Paulo Merson
  • 13,270
  • 8
  • 79
  • 72
  • 1
    It's not an argument for me since Postman offers collections, so you can save all resources as different collection items and test them individually. All you do is selecting resource from collection, you don't have to edit parameters/methods/etc everytime. – Wirone Nov 30 '16 at 07:02
2

Great discussion points on this matter. Naming conventions or rather not establishing local standards has been in my experience the root cause of many long nights on-call, headaches, risky refactoring, dodgy deployments, code review debates, etc, etc, etc. Particularly when its decided that things need to change because insufficient consideration was given at the start.

An actual issue tracked discussion on this:

https://github.com/kubernetes/kubernetes/issues/18622

It is interesting to see the divide on this.

My two cents (with a light seasoning of headache experience) is that when you consider common entities like a user, post, order, document etc. you should always address them as the actual entity since that is what a data model is based on. Grammar and model entities shouldn't really be mixed up here and this will cause other points of confusion. However, is everything always black and white? Rarely so indeed. Context really matters.

When you wish to get a collection of users in a system, for example:

GET /user -> Collection of entity User

GET /user/1 -> Resource of entity User:1

It is both valid to say I want a collection of entity user and to say I want the users collection.

GET /users -> Collection of entity User

GET /users/1 -> Resource of entity User:1

From this you are saying, from the collection of users, give me user /1.

But if you break down what a collection of users is... Is it a collection of entities where each entity is a User entity.

You would not say entity is Users since a single database table is typically an individual record for a User. However, we are talking about a RESTful service here not a database ERM.

But this is only for a User with clear noun distinction and is an easy one to grasp. Things get very complex when you have multiple conflicting approaches in one system though.

Truthfully, either approach makes sense most of the time bar a few cases where English is just spaghetti. It appears to be a language that forces a number of decisions on us!

The simple fact of the matter is that no matter what you decide, be consistent and logical in your intent.

Just appears to me that mixing here and there is a bad approach! This quietly introduces some semantic ambiguity which can be totally avoided.

Seemingly singular preference:

https://www.haproxy.com/blog/using-haproxy-as-an-api-gateway-part-1/

Similar vein of discussion here:

https://softwareengineering.stackexchange.com/questions/245202/what-is-the-argument-for-singular-nouns-in-restful-api-resource-naming

The overarching constant here is that it does indeed appear to be down to some degree of team/company cultural preferences with many pros and cons for both ways as per details found in the larger company guidelines. Google isn't necessarily right, just because it is Google! This holds true for any guidelines.

Avoid burying your head in the sand too much and loosely establishing your entire system of understanding on anecdotal examples and opinions.

Is it imperative that you establish solid reasoning for everything. If it scales for you, or your team and/our your customers and makes sense for new and seasoned devs (if you are in a team environment), nice one.

kmjb
  • 164
  • 9
1

To me plurals manipulate the collection, whereas singulars manipulate the item inside that collection.

Collection allows the methods GET / POST / DELETE

Item allows the methods GET / PUT / DELETE

For example

POST on /students will add a new student in the school.

DELETE on /students will remove all the students in the school.

DELETE on /student/123 will remove student 123 from the school.

It might feel like unimportant but some engineers sometimes forget the id. If the route was always plural and performed a DELETE, you might accidentally wipe your data. Whereas missing the id on the singular will return a 404 route not found.

To further expand the example if the API was supposed to expose multiple schools, then something like

DELETE on /school/abc/students will remove all the students in the school abc.

Choosing the right word sometimes is a challenge on its own, but I like to maintain plurality for the collection. E.g. cart_items or cart/items feels right. In contrast deleting cart, deletes the cart object it self and not the items within the cart ;).

ruralcoder
  • 1,000
  • 1
  • 10
  • 18
  • Shouldn't this be split is /cart and /cart/item(s) anyway? Then you can address the whole cart (e.g. with a delete) or individual items? – Rob Grant Feb 08 '18 at 15:28
  • @RobertGrant Wouldn't that be "/carts/items/123"? (eg. why "cart" and not "carts" is the rule is 'always plural'?) – user2864740 Mar 11 '18 at 20:25
  • 2
    I'd argue that if production code is checked in that is able to perform a delete of everyone's cart items there are bigger issues than the naming convention. The likely hood they 'd remember an 's' over an ID is much less. – Andrew T Finnell Apr 03 '18 at 14:46
  • would anyone ever create an endpoint that simply deletes an entire collection? Seems extremely dangerous to me, and probably also why REST doesn't really support batch deletes. (you'd have to wrap the array into an object). If I absolutely needed an endpoint to delete an entire collection, I would make sure that URI was very very unique, and definitely not similar to POST – cnps Jan 10 '20 at 10:05
1

Both representations are useful. I had used singular for convenience for quite some time, inflection can be difficult. My experience in developing strictly singular REST APIs, the developers consuming the endpoint lack certainty in what the shape of the result may be. I now prefer to use the term that best describes the shape of the response.

If all of your resources are top level, then you can get away with singular representations. Avoiding inflection is a big win.

If you are doing any sort of deep linking to represent queries on relations, then developers writing against your API can be aided by having a stricter convention.

My convention is that each level of depth in a URI is describing an interaction with the parent resource, and the full URI should implicitly describe what is being retrieved.

Suppose we have the following model.

interface User {
    <string>id;
    <Friend[]>friends;
    <Manager>user;
}

interface Friend {
    <string>id;
    <User>user;
    ...<<friendship specific props>>
}

If I needed to provide a resource that allows a client to get the manager of a particular friend of a particular user, it might look something like:

GET /users/{id}/friends/{friendId}/manager

The following are some more examples:

  • GET /users - list the user resources in the global users collection
  • POST /users - create a new user in the global users collection
  • GET /users/{id} - retrieve a specific user from the global users collection
  • GET /users/{id}/manager - get the manager of a specific user
  • GET /users/{id}/friends - get the list of friends of a user
  • GET /users/{id}/friends/{friendId} - get a specific friend of a user
  • LINK /users/{id}/friends - add a friend association to this user
  • UNLINK /users/{id}/friends - remove a friend association from this user

Notice how each level maps to a parent that can be acted upon. Using different parents for the same object is counterintuitive. Retrieving a resource at GET /resource/123 leaves no indication that creating a new resource should be done at POST /resources

Steve Buzonas
  • 5,300
  • 1
  • 33
  • 55
1

Just be consistent.

Use either singular:

POST /resource
PUT  /resource/123
GET  /resource/123

or plural:

POST /resources
PUT  /resources/123
GET  /resources/123
cezary
  • 64
  • 5
1

As another reference, stackoverflow uses the plural form:

https://stackoverflow.com/questions/6845772/should-i-use-singular-or-plural-name-convention-for-rest-resources

Sanan Fataliyev
  • 612
  • 8
  • 16
0

How about:

/resource/ (not /resource)

/resource/ means it's a folder contains something called "resource", it's a "resouce" folder.

And also I think the naming convention of database tables is the same, for example, a table called 'user' is a "user table", it contains something called "user".

chrisyue
  • 195
  • 1
  • 9
-1

I prefer to use both plural (/resources) and singular (/resource/{id}) because I think that it more clearly separates the logic between working on the collection of resources and working on a single resource.

As an important side-effect of this, it can also help to prevent somebody using the API wrongly. For example, consider the case where a user wrongly tries to get a resource by specifying the Id as a parameter like this:

GET /resources?Id=123

In this case, where we use the plural version, the server will most likely ignore the Id parameter and return the list of all resources. If the user is not careful, he will think that the call was successful and use the first resource in the list.

On the other hand, when using the singular form:

GET /resource?Id=123

the server will most likely return an error because the Id is not specified in the right way, and the user will have to realize that something is wrong.

pberggreen
  • 928
  • 6
  • 13
  • 1
    Why are you mixing idioms here? You use the proper URI notation in the first paragraph and then switch to query parameters? Using query parameters to obtain a resource with an ID of 123 is wholly off base here. – Andrew T Finnell Apr 03 '18 at 14:47
  • That was clearly a mistake. I have updated my answer now. Thanks for noticing it. – pberggreen Apr 04 '18 at 06:52
  • After being downvoted again, I looked at what I wrote and I realized that the original post was correct. My point was exactly that if the user does the wrong thing, then using plural+singular will in fact give a better error message that using plural only. – pberggreen May 23 '18 at 13:29
  • I still feel this is confusing the issue at hand. The idea of using plural is that it’s a collection. And the number on the end is an index into the collection. What if you GET /resource by itself? Using both plural and singular together is quite confusing. Saying /resources/123 says: Get my resource 123 in the resources bucket. – Andrew T Finnell Jul 15 '18 at 14:02