RESTful convention to update resource by id or by type and language

Viewed 47

Currently my GET request by type and language can return only one document:

GET /documents?type=invitation&language=en

id: 50
text: "I would like to invite..."

What is a correct restful convention to update resource?

PUT /documents?type=invitation&language=en

?? Or maybe I should update resource only by id?

PUT /documents/50
3 Answers

You generally use PUT when you're updating the whole resource. Here you're just sending a subset of resource data - so you should use PATCH.

Your URL should be:

PATCH /documents/{id}

Then you have all the data you want to update in the request payload:

{
   "type": "invitation",
   "language": "en"
}

So you're now updating only one object per request and using the appropriate method and resource notation.

What is a correct restful convention to update resource?

Normally, you want to use the same URI to request a change to a resource that you use to retrieve a copy of it.

The motivation for this is caching - HTTP has built into it rules for invalidating cached responses. It isn't a general purpose mechanism, but rather designed to handle a few very specific cases (invalidating responses based on target URI, Location field, and Content-Location field only).

Thus

GET /your-resource-identifier-here

Suggests that edits should be made via

POST /your-resource-identifier-here
PUT /your-resource-identifier-here
PATCH /your-resource-identifier-here

PUT /documents?type=invitation&language=en

That is a perfectly normal choice for a request that is sending a replacement representation of the resource (think "save file").

If you are intending that the request modify only part of the document, you might consider sending a patch document as the request body and using the HTTP method PATCH.

If your representation were JSON, then your request to modify the text might look like:

PATCH /documents?type=invitation&language=en
Content-Type: application/json-patch+json

[{
 "op": "replace",
 "path": "text",
 "value": "your new text here"
}]

It depends on what /documents?type=invitation&language=en gives back. If it is some sort of search and you expect multiple documents later, then PUT should update all of those documents and since it is a complete update not a partial, it does not make much sense. Using PATCH in this case is better, because it can do partial update even on multiple resources. If this URI is a unique identifier of this single resource, then you can use it instead of /documents/50 or along with it. You can have multiple identifiers for the same resource.

Related