Rest Standard: Path parameters or Request parameters

前端 未结 6 1523
孤独总比滥情好
孤独总比滥情好 2020-11-29 23:53

I am creating a new REST service.

What is the standard for passing parameters to REST services. From different REST implementations in Java, you can configure param

6条回答
  •  失恋的感觉
    2020-11-30 00:25

    tl;dr: You might want both.


    Item #42 exists:

    GET /items/42
    Accept: application/vnd.foo.item+json
    --> 200 OK
    {
        "id": 42,
        "bar": "baz"
    }
    
    GET /items?id=42
    Accept: application/vnd.foo.item-list+json
    --> 200 OK
    [
        {
            "id": 42,
            "bar": "baz"
        }
    ]
    

    Item #99 doesn't exist:

    GET /items/99
    Accept: application/vnd.foo.item+json
    --> 404 Not Found
    
    GET /items?id=99
    Accept: application/vnd.foo.item-list+json
    --> 200 OK
    [
    ]
    

    Explanations & comments

    1. /items/{id} returns an item while /items?id={id} returns an item-list.
    2. Even if there is only a single element in a filtered item-list, a list of a single element is still returned for consistency (as opposed to the element itself).
    3. It just so happens that id is a unique property. If we were to filter on other properties, this would still work in exactly the same way.
    4. Elements of a collection resource can only be named using unique properties (e.g. keys as a subresource of the collection) for obvious reasons (they're normal resources and URIs uniquely identify resources).
    5. If the element is not found when using a filter, the response is still OK and still contains a list (albeit empty). Just because we're requesting a filtered list containing an item that doesn't exist doesn't mean the list itself doesn't exist.

    Because they're so different and independently useful, you might want both. The client will want to differentiate between all cases (e.g. whether the list is empty or the list itself doesn't exist, in which case you should return a 404 for /items?...).

    Disclaimer: This approach is by no means "standard". It makes so much sense to me though that I felt like sharing.

    PS: Naming the item collection "get" is a code smell; prefer "items" or similar.

提交回复
热议问题