I'm developing a JAX-RS API that includes a simple "Person" table with fields "id" and "name", where the "id" is tied to an autonumber in a mysql database. A typical use case would be to POST a new person.
A POST of a JSON message {"name":"Bob"}
might return, for example, {"id":101,"name":"Bob"}
.
What if the caller requests a POST of an object that includes an identifier? It seems my options are to:
The last option seems dodgy from a security perspective. If I'm using mysql, a malicious user could ramp my autonumber up to a max value in one request.
How should the inclusion of an id in a POST request be handled in a REST API?
You should definitely reject all the requests that are hitting /users/
endpoint. First of all for security reasons (at DB level), secondly this is not the client's job to generate/suggest the IDs.
So the answer is to reject the request as invalid along with appropriate status code (400
) and a message explaining the reason of rejection.
The second option is unintuitive, one that is sending and ID (which as I as wrote already is a bad idea) - would not expect to receive different ID that it posted. Sending ID in a body, makes sense for PUT
request and it assumes that the object is already created/existing - this is an update.
The third option will not be RESTful - there's no upsert in REST - POST
creates new resources. The fourth option doesn't make sense at all - this is not client's job to provide IDs.