URL设计restful api [英] URL design restful api

查看:64
本文介绍了URL设计restful api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我想构建一个安静的 api,它应该将项目添加到购物车.我认为最直接的方式是这样的:

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.

现在我会像这样设计api:

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?

推荐答案

如果我理解正确的话,有两个资源需要管理,ShoppingCarts 和 Items.如果业务逻辑是在向购物车添加商品之前创建购物车...那么,下面的设计应该可以工作.

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) 创建购物车

  • 发布:/shoppingcarts/
  • 返回:{shoppingcart-id}

B) 然后创建/添加商品到购物车

  • 发布:/shoppingcarts/{shoppingcart-id}/
  • BODY:{关于项目的数据}
  • 返回:{item-id}

或者可以更具体地在网址中使用项目".

  • 发布:/shoppingcarts/{shoppingcart-id}/items/
  • BODY:{关于项目的数据}
  • 返回:{item-id}

C) 获取购物车中的所有商品

  • 获取:/shoppingcarts/{shoppingcart-id}/items/
  • 返回:{所有项目的数据}

D) 获取购物车中的特定商品

  • 获取:/shoppingcarts/{shoppingcart-id}/items/{item-id}/
  • 返回:{项目数据}

E) 从购物车中删除商品.

  • 删除:/shoppingcarts/{shoppingcart-id}/items/{item-id}/

还有 PUT 是修改现有资源而不是创建新资源.比如如果需要更新已经存在的item的数量,会做如下操作.

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, {其余物品信息}}

或者您可以使用 PATCH 来更新数量.

OR you can use PATCH to just update the quantity.

  • 补丁:/shoppingcarts/{shoppingcart-id}/items/{item-id}/
  • 身体:{数量:2}

希望有帮助!

这篇关于URL设计restful api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆