I am creating an API and I wonder why it is common to have a id parameter in URI for PUT?
Such as PUT /cars/5
Why don't have PUT /cars
? The request entity contains an id field isn't that enough? I can get the id from that entity, or is it some downsides to this, and is it considered bad to do it?
The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload. So you can't send a PUT without the ID.
A URI is a Universal Resource Identifier, identifying where a specific resource can be found, such as a page or a document. They are used in REST APIs to address resources to developers using an API.
Because if you were to send a PUT
request to /cars
, semantically that would imply you are trying to modify attributes about the set of cars, rather than modifying attributes of an individual car. The URI in a RESTful API should indicate the exact resource the action is acting upon, so if you are modifying a resource, your URI should exactly indicate that resource.
Also, from RFC 2616:
The URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource.
So the spec indicates that if the client knows the resource's unique ID, it should be included in the URI.
this comes from rest "ideology".
the idea is that a url uniquely represents an entity - so you must PUT the entity youre creating/editing to the url of that entity.
to quote from the wikipedia page:
Identification of resources
Individual resources are identified in requests, for example using URIs in web-based REST systems. The resources themselves are conceptually separate from the representations that are returned to the client.
PUT
aims to udpate ONE precised entity.
With merely using /cars
, you aren't focus on a specific entity.
And on the contrary of what you wrote, your full entity isn't passed in a basic String (URI).
Excepted if your targeted method focus on a hard-coded car
id
... but I don't think so..
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