POST or PUT

Should I use POST or PUT?

Again and again the question comes up: POST or PUT?

The answer is: it depends. Because both POST and PUT have their respective usage, which is different from each other in terms of content and logic.

When to use POST?

POST is a request to the server that is not idemponent.
This means that, unlike a PUT request, the server does not have to behave identically when identical requests are sent.

Real example: if you send ten requests to the server via PUT, the server would create ten different resources (with different ids, e.g. Guids).

POST is therefore used to create new resources; either directly to a collection (/api/tasks) or as a child collection (e.g. /api/tasks/123/persons) of an existing resource.

Technically, POST requests will not be cached.

When to use PUT?

The most important point: a PUT request is always idepontent.
This means: if a request is used in identical form multiple times to the server, then the API must behave exactly the same as if only one request was sent.\

Real example: if you send ten requests to the server via PUT, the server would only create a single resource.

  • When a PUT request is sent to a collection (/api/tasks) then that resource is added to the collection.
  • When a PUT request is sent to a resource identifier (/api/tasks/123) then that resource will be completely replaced (no update, there’s PATCH for that!).

Although a PUT request supports caching in principle, this is not recommended in most cases.

Conclusion

  • Use PUT for unique operations against a collection (“insert”) or resource (“replace”)
  • Use POST to add new resources to a collection (“add”)