Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I understand that in MVC pattern and in REST services it is common to use URIs like /items/{id} but what is bad thing about using query parameters in the URI?

GET /items/{id} vs GET /items?id={id}

Further, lets say an entity has 'referenceId' field that points to some related (say parent) entity, and I need to create REST service to get all items for parent entity, which way is better:

GET(POST) /items/parent/{parentId} 

or

GET(POST) /items?parent={parentId}

Will be grateful for insights that would help to resolve my subjective issues on constructing URLs for REST services.

like image 791
WHITECOLOR Avatar asked Jan 15 '13 17:01

WHITECOLOR


2 Answers

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
like image 55
Xeago Avatar answered Oct 10 '22 04:10

Xeago


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.

like image 42
codeprogression Avatar answered Oct 10 '22 03:10

codeprogression