URL design restful api

怎甘沉沦 提交于 2019-12-02 19:49:25

问题


Lets assume that i want to build a restful api which should add items to a shoppingcart. I think the most straight forward way would be like this:

POST /shoppingcarts/{shoppingCartId}/items - to generate an itemId
PUT /shoppingcarts/{shoppingCartId}/items/{itemId}

Now it is possible that a shoppingcart does not exist when i want to add an item to it. There is also a requirement that the client must not create a shopping cart. If the client adds an item and a shoppingcart does not exist then it should be created.

Now i would design the api like this:

POST /shoppingcartitems - to generate a shoppingcartItem
PUT /shoppingcartitems/{shoppingcartItems}

Does this makes sense at all? Or is there another way to do this.

A follow up question would be that when an item is created the complete shopping cart should be returned. Returning the complete shopping cart when creating an item seems wrong since it is a different resource. I would probably just add a hypermedia link into the body of the created item which points to the shopping cart. Would that be also correct?


回答1:


If I understand it correctly, there are two resources to manage, ShoppingCarts and Items. If the business logic is to create a shoppingCart before adding items to it... Then, the following design should work.

A) To create a shopping cart

  • POST: /shoppingcarts/
  • return: {shoppingcart-id}

B) Then create/add item to the shopping cart

  • POST: /shoppingcarts/{shoppingcart-id}/
  • BODY: {data about the item}
  • return: {item-id}

Or can be more specific with "items" in the url.

  • POST: /shoppingcarts/{shoppingcart-id}/items/
  • BODY: {data about the item}
  • return: {item-id}

C) To get all items in the shopping cart

  • GET: /shoppingcarts/{shoppingcart-id}/items/
  • return: {data for all items}

D) To get a specific item in the shopping cart

  • GET: /shoppingcarts/{shoppingcart-id}/items/{item-id}/
  • return: {data for the item}

E) To delete an item from the shopping cart.

  • DELETE: /shoppingcarts/{shoppingcart-id}/items/{item-id}/

Also PUT is to modify an existing resource not to create a new resource. Like if need to update the quantity for the item that already exists, will do the following.

  • PUT: /shoppingcarts/{shoppingcart-id}/items/{item-id}/
  • BODY: {quantity: 2, {the rest of the item info} }

OR you can use PATCH to just update the quantity.

  • PATCH: /shoppingcarts/{shoppingcart-id}/items/{item-id}/
  • BODY: {quantity: 2}

Hope it helps!



来源:https://stackoverflow.com/questions/46008871/url-design-restful-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!