0

so i started learning backend recently, with node/expres. Im building a small REST API for learning purposes, with the following routes:

GET /api/products >> to display a list of products
GET /api/cart >> to display list of items inside the cart 
DELETE /api/cart/:id >> to delete an item from the cart 

now, i want to be able to add an item to the cart, with the POST method ofcourse, should it be:

/api/cart >> and pass the item id in the body, so req.body.id 

or

/api/cart/:id >> and pass the item id with req.prams.id ?? 

I understand that both work, but i've been told that with POST method, it's better to pass it via the body, so i would like to understand why, since in this specific case i am not creating a whole new item(in that case i would pass the data via the body of course), but i already have the item in the products list, so i just want to retrieve it and add it to the cart. Is it that if i create the frontend side for this api, one of them will work better ? or how does the whole thing work? what's the preferred method?

Thank you

  • Your patterns are correct. In the second case, which is the update of a record, we normally use the PUT method by convention. But with POST it would also work. – Cássio Lacerda Apr 21 '21 at 16:44

1 Answers1

0

You can fit more (diverse) data in the body than in the url. You can pass any string (special characters) in the body, while encoding them in the url would get you vulnerable to status 414 (Request-URI Too Long). And it's a lot easier to use the body when passing arrays and complex objects :)

SimonC
  • 59
  • 3