Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why having an id parameter in URI when updating a resource?

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?

like image 943
LuckyLuke Avatar asked Apr 21 '13 17:04

LuckyLuke


People also ask

Does HTTP PUT require an ID?

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.

What is resource URI in REST API?

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.


3 Answers

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.

like image 52
Stuart M Avatar answered Nov 08 '22 02:11

Stuart M


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.

like image 27
radai Avatar answered Nov 08 '22 02:11

radai


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

like image 27
Mik378 Avatar answered Nov 08 '22 01:11

Mik378