Search code examples
restjax-rsautonumber

What to do when REST POST provides an ID?


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:

  • Reject the request as invalid
  • Delete the id from the request and continue to process
  • Treat the POST like an UPSERT (on update failure, delete the ID and insert)
  • Attempt to create the new record using the provided id

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?


Solution

  • 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.