Should I use PATCH or PUT in my REST API?

前端 未结 6 1096
予麋鹿
予麋鹿 2020-11-30 16:33

I want to design my rest endpoint with the appropriate method for the following scenario.

There is a group. Each group has a status. The group can be activated or in

6条回答
  •  半阙折子戏
    2020-11-30 16:57

    I would recommend using PATCH, because your resource 'group' has many properties but in this case, you are updating only the activation field(partial modification)

    according to the RFC5789 (https://tools.ietf.org/html/rfc5789)

    The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

    Also, in more details,

    The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource
    identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the
    origin server, and the client is requesting that the stored version
    be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the
    origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it
    also MAY have side effects on other resources; i.e., new resources
    may be created, or existing ones modified, by the application of a
    PATCH.

    PATCH is neither safe nor idempotent as defined by [RFC2616], Section 9.1.

    Clients need to choose when to use PATCH rather than PUT. For
    example, if the patch document size is larger than the size of the
    new resource data that would be used in a PUT, then it might make
    sense to use PUT instead of PATCH. A comparison to POST is even more difficult, because POST is used in widely varying ways and can
    encompass PUT and PATCH-like operations if the server chooses. If
    the operation does not modify the resource identified by the Request- URI in a predictable way, POST should be considered instead of PATCH
    or PUT.

    The response code for PATCH is

    The 204 response code is used because the response does not carry a message body (which a response with the 200 code would have). Note that other success codes could be used as well.

    also refer thttp://restcookbook.com/HTTP%20Methods/patch/

    Caveat: An API implementing PATCH must patch atomically. It MUST not be possible that resources are half-patched when requested by a GET.

提交回复
热议问题