Home > OS >  Which method would be more appropriate here POST or PATCH?
Which method would be more appropriate here POST or PATCH?

Time:11-13

Let's say I have a db collection with users and I want to ADD an object to an array inside one document. It was like this:

{
_id: "636e8e1dd710eed71565741c",
username: "test",
password: "$2b$10$/s9.kRYSax380Xrxf3xyVO9Z6Otc/WVx5kBSLKfu43/wYP.TSnzvW",
tasks: [{name: task1, status: "finished"}]
}

And I am going to make it look like this:

{
_id: "636e8e1dd710eed71565741c",
username: "test",
password: "$2b$10$/s9.kRYSax380Xrxf3xyVO9Z6Otc/WVx5kBSLKfu43/wYP.TSnzvW",
tasks: [{name: task1, status: "finished"}, {name: task2, status: "unfinished"}]
}

So which method would be more appropriate here since I'm adding a new object to an embedded array and not updating one which already exists? Thank you.

CodePudding user response:

The choice between POST and PATCH depends on the path of the URL. If the path contains the _id, I'd prefer

POST /collection/636e8e1dd710eed71565741c/tasks
Content-Type: application/json

{"name": "task2", "status": "unfinished"}

However, if the _id is part of the payload, I'd prefer

PATCH /collection
Content-Type: application/json

{"_id": "636e8e1dd710eed71565741c",
 "tasks@add": [{"name": "task2", "status": "unfinished"}]}

But this payload format relies on "naming conventions":

  • The _id serves to identify the entry to be patched.
  • The suffix @add means that the tasks are added to the existing array.
  • "tasks@change": [{"name": "task1", "status": "archived"}] would instead update the existing task.

If the server knows that each task is identified by its name, the suffixes would not be necessary:

PATCH /collection
Content-Type: application/json

{"_id": "636e8e1dd710eed71565741c",
 "tasks": [{"name": "task1", "status": "archived"},
           {"name": "task2", "status": "unfinished"}]}

updates the existing task and adds a new one. Or even

PATCH /collection/636e8e1dd710eed71565741c/tasks
Content-Type: application/json

[{"name": "task1", "status": "archived"},
 {"name": "task2", "status": "unfinished"}]

I hope these examples help you find a suitable pattern.

  • Related