REST URL naming convention /items/{id} vs /items?id={id}

泪湿孤枕 提交于 2019-12-03 12:52:41

I would use the following schemes.

/items/id

This uniquely addresses a resource of items with id id. We are not using parameters as a parameter to uniquely address this resource (as is the case with the other option). Just as miguelcobain suggests.

/parent/id/items

Here id is an id to uniquely address a resource of parent and from those we collect/retrieve the items it references. From what you have said in the question it seems that parent references multiple items, like a container or collection.

The convention I use for this is to narrow down the scope going from left to right. Therefore in case items could be active or inactive. Thusly items have a property or attribute to be active or inactive. Narrowing down on this I get the following scheme:

/items/active
/parent/id/active

For your first question:

/items/{id} should retrieve a single resource with the specified id or 404 if it doesn't exist.

/items/?id={id} should retrieve an array (even if only one in the array) because you are querying the collection.

For your second question:

I agree with @miguelcobain's assessment - if the item is a specific resource/entity, just use the proper resource path to retrieve it.

To make this easier on the consumer, create a link header with rel="parent" and/or include the uri in the child resource. For an example of link headers, see GitHub's pagination api.

Of course, REST principles don't care about aesthetic details on URLs. It just imposes that every resource should be uniquely addressable.

Furthermore, using the query parameters to uniquely address something "kind of" violates the semantics of a "parameter", doesn't it? A parameter should be something optional, something additional and parameterized. Something like a detailed search on a collection of items, for example.

What you wrote may make sense in some cases. It depends.

In your example, is the item really a resource? If not, you could just do GET(POST) /parents/{parentId}.

If parent is, say, a boolean, and you want to search the items that have parent equals to true, then using the parameters makes sense. But since you're explicitly saying that you want a parent with a specific id, I assume that parent is a resource itself and I would uniquely address that resource using your option 1.

I hope I made myself clear.

Damith Ganegoda

It seems to me there are no rules to follow.

items/{id} - this convention is suitable for GET item by given id. If user doesn't provide id then it returns 404 status code.

items/id={id}&name={name} - this type of convention is suitable for search multiple items by given criteria. If no items are found, it is not a 404 situation, you simply say "I successfully found nothing matching your search criteria"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!