Incrementing resource counter in a RESTful way: PUT vs POST

后端 未结 4 1317
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-31 18:15

I have a resource that has a counter. For the sake of example, let\'s call the resource profile, and the counter is the number of views

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-31 18:50

    An alternative might be to add another resource to the system to track the viewings of a profile. You might call it "Viewing".

    To see all Viewings of a profile:

    GET /profiles/123/viewings

    To add a viewing to a profile:

    POST /profiles/123/viewings #here, you'd submit the details using a custom media type in the request body.

    To update an existing Viewing:

    PUT /viewings/815 # submit revised attributes of the Viewing in the request body using the custom media type you created.

    To drill down into the details of a viewing:

    GET /viewings/815

    To delete a Viewing:

    DELETE /viewings/815

    Also, because you're asking for best-practice, be sure your RESTful system is hypertext-driven.

    For the most part, there's nothing wrong with using query parameters in URIs - just don't give your clients the idea that they can manipulate them.

    Instead, create a media type that embodies the concepts the parameters are trying to model. Give this media type a concise, unambiguous, and descriptive name. Then document this media type. The real problem of exposing query parameters in REST is that the practice often leads out-of-band communication, and therefore increased coupling between client and server.

    Then give your system a uniform interface. For example, adding a new resource is always a POST. Updating a resource is always a PUT. Deleting is DELETE, and getiing is GET.

    The hardest part about REST is understanding how media types figure into system design (it's also the part that Fielding left out of his dissertation because he ran out of time). If you want a specific example of a hypertext-driven system that uses and doucuments media types, see the Sun Cloud API.

提交回复
热议问题