URL design restful api

后端 未结 1 1085
粉色の甜心
粉色の甜心 2021-01-28 23:43

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 /shopping         


        
相关标签:
1条回答
  • 2021-01-28 23:55

    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!

    0 讨论(0)
提交回复
热议问题