Which HTTP method to use for RESTful api for "add to cart" an existing item already in cart? - rest

I have started designing addToCart method as HTTP POST in my RESTful API. This looks good when the client adds to cart a product first time (POST create a new entry on server). But, the same HTTP rule breaks when the client browses through the site and adds the same item again; where we should not create a new entry but only update the quantity of existing item.
Isn't using POST to update resource wrong? What is the way to implement this? or how to interpret this situation.
Note: Client/UI front which uses my api would not remember if its already there on server. Please consider any ecommerce application's addtocart as example.

I think the difficulties here are already present in how you add the original item to the cart.
When you add an item to cart, are you creating a new object (the item)? Or are you modifying an existing item (the cart)? To me it makes more sense to say the latter. POSTing an item seems like it should be reserved for a different situation, when you add a new item to your store.
Conceptually, the cart is then like a vector of all the items in your store, associated with a number (0 for almost all of them). Adding something to the cart means incrementing this number for one of the items, regardless of whether it is already more than 0.

You can use PATCH to send a part object / update to an existing object.

It's based on your model. IMHO a POST is also fine if you are modelling a new intent or cart-operation with it, which can be basically anything.

Related

API Validating basket on get request

What would be the best approach to handle Model State Errors for the the basket to the user that loads the basket from the API ?
Scenario:
User adds product to the basket ( basket is valid at the time of creating it )
The product is taken off ( for example has been set as not available or the price has changed since the user added to the basket )
( this can be done outside API )
Should the client make two requests:
Get The basket
Validate the basket
( a little bit RPC style )
Another way of doing it might be
extending the response view model with 'errors' that might get populated
whenever user GET it via API.
Not sure though if this is good practice though.
What would be the RESTful way of solving this problem ?
Thanks in advance for help
What would be the RESTful way of solving this problem ?
How would you do it with a web page?
It would probably be a single web page, right? Containing
a list of items in the basket, and...
a list of problems that might prevent the order from growing through
and maybe also some links to other resources that might help resolve these problems.
otherwise forms, or links to forms, to aid in performing the next step of the ordering protocol.
Another way of doing it might be extending the response view model with 'errors' that might get populated whenever user GET it via API. Not sure though if this is good practice though.
It's fine - the resource model is not the domain model is not the data model. Your "resources" are documents that support interacting with the domain.
See also: Webber 2011.

Sub routing best practices

I am building an api which has a route: /market/items/{category}, it returns items from a category. If a user clicks on an item I have a route /item/{id}/ which returns information about the item. I'm wondering if this is a bad practice when creating a restful api. because often I would see routes like /market/items/{category}/{id}. What do you think?
If only the id is needed in order to retrieve the item (in other words, the id by itself uniquely identifies the item without any other information), then there's no reason to require a category in the URL also so this:
/item/{id}/
would be just fine for a restful API.
If, on the other hand, there are multiple types of items, each with overlapping item identifiers, then you may need something else in the URL to uniquely identify which type of item and thus which pool of item identifiers to look in.
One reason you may see some web sites doing something like this in their web page URLs:
/market/items/{category}/{id}
is for search indexing where they want the category name to be associated with the item for purposes of search engine indexing. But, if this is just a restful API, not visible web pages, then you probably aren't trying to optimize that for search hits.

Best frontend practice for saving object to a backend before or after creation

situation: Lets's think about basic process of object creation on a client (with CRUD backend).
Let's imagine that we have two "Create" buttons on a page.
first case:
Clicking on the first button will cause to redirect to /create route, where our form located.
After we fill the form with data, we post it to a backend and it retrieves an id of a newly created object.
second case:
Clicking on the second button will cause to send creation request to the backend, then after we got a new object id, we will be redirected to /edit/:id, where our form located (same form).
After we fill the form with data, we send it to a backend and save already existed object (post by id).
question:
What's the pros and cons of those two cases, when to use each of them?
In the first case you can include the validation of the fields in the time of creation
and you only need to create an insert so one database call.
In the second case you are creating an empty entry that will appear in the grids of an application with no data.
Also if your database has required fields, you have to fill them with default data.
Validation will be more difficult since you need to allow empty ex Mobile in data entry
while phone might be required.
Another problem with this is that that you are basically doing two operations. One if for the Insert of the row and one is for the update of the row
However this methodology is easier to implement the live update of text when typing so any disconnects etc will not lose any data. This methodology is also good for collaboration between two clients using websockets ex inserting the row at the same time.

Restful API: Is it meaningful to send PUT without enclosed entity?

Consider the following scenario:
There are two existing entity: shopping card #1 and item #1. I want to add item #1 to shopping card #1. There are two possible ways to design a Restful api:
1:
Without body:
PUT http://myshoppingsite.com/api/shoppingcards/1/items/1
Host: myshoppingsite.com
2: With body (having enclosed-entity):
PUT http://myshoppingsite.com/api/shoppingcards/1/items/
Host: myshoppingsite.com
{itemId: "1"}
Actually, I cannot decide which one is better and is more meaningful in terms of restfulness. Any idea?
(Note: I believe the http method should be PUT because of idempotency, but this is not my question here.)
PS: The problem I have with the first design is that there is no such enclosed entity in the request. Linguistically put is a transitive verb, so I expect somebody puts something somewhere. I think the same story somehow is in the HTTP world.
PUT is a HTTP verb that is supposed to create or replace the target URI, so this makes your first option immediately wrong. This request should replace all the items in your shopping cart:
PUT http://myshoppingsite.com/api/shoppingcards/1/items/
Since you want to add something to your shopping cart, this is not an option. This leaves effectively two options. First: the common one:
POST http://myshoppingsite.com/api/shoppingcards/1/items/
POST can mean many things, but in the context of REST services it's often used to append something to a collection. However, you mention that you want idempotence. You have two options here, first you can still use POST and within the context of your API guarantee that the request will be idempotent. Using POST does not mean that it's per definition non-idempotent, it just means that the HTTP spec alone does not guarantee it. That does not prevent you from making the request idempotent.
The other option is indeed PUT:
PUT http://myshoppingsite.com/api/shoppingcards/1/items/1
Your have a concern with that though, because in the context of your API you say that the request body would end up empty.
The reason for this is that you attach special to the last /1 in the url, and I think this what's wrong. If you want to follow REST best practices, then urls should not have any special meaning.
I think a saner way to do this, if you insist on using PUT is to get rid of the notion of "an id". That concept only exists in your database and should not make its way to the API.
Instead, I imagine that your service has a list of products such as this one:
http://myshoppingsite.com/products/1
To add a product to a shopping cart using PUT, this request might look something like this:
PUT http://myshoppingsite/api/shoppingcards/1/items/[completely-arbitrary-string-or-perhaps-a-uuid]
Content-Type: application/json
{
"product" : "http://myshoppingsite.com/products/1",
"quantity" : 5
}
Personally, I would just use POST though.
Q: there should be some information about the product you are addisng, no? Yes and that information is part of Uril. Why is it bad?
I'm not saying it's bad, I'm saying it's not RESTful. Pick up any book about REST and you will see this confirmed. This might also be a good place to start reading more about what REST is:
http://martinfowler.com/articles/richardsonMaturityModel.html
I would personally say that very little people build true RESTful services. This is why I also want to specifically point out that I don't want to say this is bad or good for your specific API, it's simply not RESTful.
What if I don't care about these principles and want to keep my special-meaning url scheme?
Well that's a fair point, but then we've gone beyond the original question here. If you want to design an API where the last bit of the url is actually the 'representation' of the item in your shopping cart, then yes I agree that having it also in the body is redundant.
In that situation I'd say, keep the request body empty. Just don't call it REST I guess.

Saving changes to DB made in a webpage

I rewrote the title and content 3 times before posting it, I don't find the right way to ask this :P
I have a page that manage a list of notes, I have a CRUD on that page but the items are created and saved in javascript (using knockoutjs).
I create a new note, I add it to the model in javascript and it show up in the page.
The way Im saving the notes to the database is when I add it to the model, I send it via Ajax (async) to the server. So I have my note on screen and in the database really fast.
I send a note without Id to the server and EF will take care of the Id.
So far so good.
Imagine that I add a note but I dont refresh the webpage, so the note is in the database, is in the javascript model too but in the model it doesn't have the id yet.
I make some changes to the note and yeah, I want to update the note in the database... but... how?
I send my note to the server with the changes, but remember, the item still have no Id so I can't say:
Hey EF, give me the note with the ID == xx and we are going to update that note.
The others properties can be changed on the webpage so I have nothing that identifies the note apart from the Id, who doesn't work here.
I tried this:
Send the new note to the server, insert it on the database, retrieve it again (to pick the Id), send it back to javascript and update the object with the Id. So when I edit, I have the Id. Yeah, but the "save" call need to be sync and that destroy the experience.
Any ideas?
EDIT: The sync options is not that slow at the end but there have to be a async way and meh, the thing of "Insert on database", "Retrieve the last item I inserted" and "return back to the client" is a little hackish.
You could return the id of the new record in your asynch call. If you are using jQuery you can subscribe to the "success" callback and as long as your controller returns a JSON with the id of the new record you could update your model on the client side.
Even with this approach, you will need to have a way to identify the item updated on the client side (which is really the root of your question.) For that you can probably generate a random GUID on the client side, send it to the server when saving, and return it to jQuery when returning the ID so that you can identify the correct element to update on the page.