Reputation: 845
I have a rest API in which you can POST a new resource & sub-resource f creation of a resource, what happens to the sub-resource when I send PUT request to the resource ?
E.g. I have a Employee resource and Salary as sub-resource
Lets assume I POST http://api/v1/employees
and it creates an employee and return id 1
Further I POST http://api/v1/employees/1/salaries
and it enter salary for the employee 1
Now, If I do a PUT http://api/v1/employees
it will replace the employee object entirely, but what happens to the salary resource, should it be deleted or leave it as it is ?
Upvotes: 4
Views: 400
Reputation: 21
From RFC-7231:
HTTP does not define exactly how a PUT method affects the state of an origin server beyond what can be expressed by the intent of the user agent request and the semantics of the origin server response. [...]
It does not define how resource state is "stored", nor how such storage might change as a result of a change in resource state, nor how the origin server translates resource state into representations.
Generally speaking, all implementation details behind the resource interface are intentionally hidden by the server.
The specification doesn't define the internals of how to implement the replacement of the resource performed with a PUT operation, just the expected result:
A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation.
As you mentioned, you replace the entire employee resource with the employee representation that you sent with PUT:
The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload.
Conclusion:
The salary representation could be part of the new employee representation or not. If it's part of the new employee representation and contains all salary details required to create a new salary resource, the old salary resource should be replaced, otherwise the employee should not have salary resource associated, so the old salary resource should be removed.
If the new employee representation contains a salary identifier matching the old salary resource identifier, then the old salary resource should be kept.
The internals on how to implement the operation (removing or keeping the old salary resource) would depend on the representation of the new employee.
Upvotes: 2