Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Which method would be more appropriate here POST or PATCH?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading