Should HTTP PUT create a resource if it does not exist?

后端 未结 2 1956
渐次进展
渐次进展 2021-02-02 17:39

Lets suppose that someone performs a PUT request on my endoint:

/resources/{id}

However there is not resource with the given id st

2条回答
  •  伪装坚强ぢ
    2021-02-02 18:30

    In short, it depends wheter the payload you want to store violates any constraint the server has for resources or not.

    In general I'd say it should attempt it as the client explicitly expresses his intent to store that particular representation at the target URI. The server should though perform constraint checks before! Usually, in a real REST scenario though, the client should use URI that are provided by the server and not just chose any URI on its own. Thereby, a server should be in control of its namespace, as such using PUT to create resources is not recommended here by default.

    With that being said, as PUT is idempotent while POST being not, some clients might want to benefit from this property. Here a POST-PUT creation pattern has evolved, where a client is attempting to create a new resource via POST until it receives a confirmation via a Location header in the response and afterwards attempts the update of that resource's state via PUT. This way the client can be sure that in case of transmission problems the representation was only created once. Depending on the stance, some people might consider the actual update of the resource as the actual resource creation, though as the client beforehand received the respective link, this is not quite the case.

    Note that a server also has the right to transform the representation to something different if i.e. the server is configured to provide specific representations for certain URI endpoints. Think of uploading an image via PUT to a URI and the server embedds the image into a HTML page

提交回复
热议问题