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?
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.
Your rest-api-id is the identifier before 'execute-api' in your endpoint URL.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With