I'm trying to create a REST API that allows the user to:
- create a resource if it doesn't exist.
- update a resource if it exists.
with the same request.
Given an example: I have a company that has many employees. I know that the way that usually an employee is inserted is using something like do a post request to /employees/
URL with a body that represents the employee to be created and as result, I will get similar content with a field that identifies the created resource. In most cases, if I try to insert another employee with data that conflicts with the first created employee, like the fiscal document code, I will get a 400 or 409 response that indicates a conflict with an existent resource. But if I want to create a permissive API that instead updates the present resource according to an attribute that I know that uniquely identifies the resource, what is the best approach?
A
POST
request means that the request is not idempotent, but an "upsert" request is idempotent. So I think that design the API using thePOST
method is not adequated.A
PUT
request is idempotent but refers to a specific resource or a set of resources. Semantically, do aPUT /employees/
means that all existing employees are matched in this request.Use something like
PUT /employees/123
, that 123 is an identifier of the employee is not possible when its identifier is synthetic and generated by the service. The user cannot know what identifier to use in this case.
Is possible to create a RESTful API that allows this kind of "upsert" request? If possible, how can I do?
PUT /employees/{employeeUuid}
endpoint, generate the identifier on the client and create a resource if it does not yet exist, otherwise update it (with access checks, if necessary).