There is a common REST API design practice developers often apply without much thinking.
When implementing a POST or PUT endpoint, we usually return the created or updated entity in the HTTP response body.
I am not sure about the origin of this convention, but I suspect it can be related to the urge to reuse data models: We already have a model for the entity that is used in the request and in the GET response, so why not use it also for the POST and PUT responses? I once wrote a blog post where I show how reusing too much can lead to an incorrect API design.
There is nothing in the HTTP protocol or REST architecture telling us to echo back what we got in a POST or PUT request. On the contrary, there are some arguments against it:
- waste of network bandwidth and increase of response time, especially for large entities
- the client already has the data because it has just sent them in the request
- it can lead to incorrect assumptions on the client side that the returned data are always up-to-date, but that might not be true if some other request on the same entity is performed in parallel
Someone pointed out that there can be some "additional processing" happening on the server and therefore it may be necessary to return the entity after that processing. For sure, if a new entity with a new ID is created in a POST request, we should return the URL of the new resource (or at least its ID).
But even if there is some more information generated on the server, why do we automatically assume that the client needs the modified parts or the whole entity data? It goes against the single responsibility and CQRS (Command-Query Responsibility Segregation) principle: a POST or PUT is expected to do a create/update. If the client needs to read the data, it can use a GET request.
Remember, APIs, like all interfaces, should be minimal. Only expose what needs to be exposed. Adding stuff to an API data model is easy (non-breaking), but removing it is hard.
What do you think? Do you return the entity as the response from your POST and PUT endpoints? Always? Sometimes?
Top comments (0)