Search code examples
javarestputidempotent

Is it RESTful to use URL resources specific to object members in REST APIs? PUT or PATCH?


This is a PUT vs PATCH question. The question title in other words: Normally, a URL of an underlying object exists at /object/{id}. Is it still idempotent to add a URL /object/{id}/member and call PUT on that specific member?

Minimal Example

If I have resource called Booking that looks like this

public class Booking {
    private bookingId;
    private name;
}
//accessors ...

I think the PUT and PATCH stuff is clear. My confusion stems from deciding on what idempotency refers to...

  • idempotency of response to a given URL? OPTION 1
  • idempotency of the underlying data objects (Java) as opposed to members? OPTION 2

If the first case is true, then I would expect that it is RESTful to create a specific call to an object member of Booking like this:

PUT /booking/{id}/name GRAY AREA HERE? (NORMALLY A PATCH OP AT booking/{id})

{
   name: "Joe Schmoe" 
}

In this case, the underlying object has been changed, but the resource remains idempotent (GET here would return the same and subsequent PUTs like above would not change anything), because the resource is specific to an object member? Or by altering a member, did I break the idempotency law?

If the second option is true, and URLs should not be made specific to object members, then I would expect to use PATCH on a member at a URL resource that represents the entire object to update specific object members like this:

PATCH /booking/{id}*

{
    name: "Joe Schmoe"
}

I expect that it is NOT RESTful to do the following. It would clearly break idempotency at of the resource URL. Let me know if I am mistaken here.

PUT /booking/{id}

{
   name: "Joe Schmoe"
}

Solution

  • First of all, keep in mind that idempotency is a property of HTTP methods (and not a property of the resources). Quoting the RFC 7231, which is the document that currently defines the semantics and content of the HTTP/1.1 protocol:

    4.2.2. Idempotent Methods

    A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent. [...]

    Have a look at my previous answer for further details on what idempotency is.

    So a request with an idempotent HTTP method can be performed multiple times and the same effect will be produced in the server. Understand effect as the state of the resource on the server, even if a resource has multiple identifiers.

    And bear in mind that status codes are not relevant from the idempotency point of view.