Search code examples
restapi-design

Should a REST create request reject bodies with auto-generated fields or ignore those fields?


Given an entity has an auto-generated field, e.g. createdDate: in a POST request, would it be better practice to reject any requests where the body contains a createdDate value since the user shouldn't be trying to set this, or should I just ignore what the user has set, auto-generate the createdDate value and include the new value in the response?


Solution

  • Usually, values a client can or has to set for a certain resources should be taught by the server via form-like representations, such as HTML Web forms, where the affordance of the respective control elements allow a client to specify the correct values a server expects or supports. In such a case a client does not have any knowledge on the capabilities of a resource other than the ones which are told by the server directly.

    In case a server taught a client that a certain property supports a range, lets say between 0 and 100 and a client attempts to send a value less than 0 or larger than 100 or a non numerical value, I'd prefer to return an error hinting the inappropriate usage of some supported elements.

    In regards to whether to ignore certain input values for certain properties or return an error for properties that are not taught by the server directly, it is solely based on design choice IMO whether to return an error or simply ignore it. Via POST the payload is processed according to the resource own semantics. Here the best advice would be to point to the big cousin, the browsalbe Web, and ask how you would do it there and just use the same concept in a REST architecture. Here, the robustness priciple mandates:

    Be conservative in what you do, be liberal in what you accept from others

    Be conservative in what you send, be literal in what you accept

    So, I'd lean more towards ignoring properties a client shouldn't set but be precise in what you return to the client. However, if a client sends data that assumes some knowledge of the internals of a resource without being told so by the server, it violates REST principles alltogeter and thus points out a "non-RESTful" usage.