Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 526
phatfingers Avatar asked Oct 31 '15 14:10

phatfingers


People also ask

Does POST require ID?

When you pick up an item at the post office, you will need to show acceptable identification. It must be original, valid, government-issued photo ID with a unique identifier number.

What is rest ID?

Your rest-api-id is the identifier before 'execute-api' in your endpoint URL.

What happens if you use POST instead of get?

Using POST instead of GET would prevent the client from having to worry about encoding values and data size, since data would be sent in the body, rather than as a URL parameter.

How do I contact API POST?

To make a POST request to an API endpoint, you need to send an HTTP POST request to the server and specify a Content-Type request header that specifies the data media type in the body of the POST request. The Content-Length header indicates the size of the data in the body of the POST request.


1 Answers

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.

like image 116
Opal Avatar answered Oct 15 '22 14:10

Opal