RESTful API设计:用于创建多对多关系的PUT或POST? [英] RESTful API Design: PUT or POST for creating many-to-many relationships?

查看:165
本文介绍了RESTful API设计:用于创建多对多关系的PUT或POST?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设计和创建RESTful API时,会出现以下问题:

For designing and creating a RESTful API the following question occurs:

API支持GET(用于查询),POST(用于创建),PUT(用于更新)和DELETE(用于删除).

The API supports GET (for queries), POST (for creating), PUT (for updates) and DELETE (for deleting).

让我们假设在数据库中我们已经有一个文章和一个商店.

Lets assume in the database we have an article and a shop both already existing.

现在,我们需要一个rest调用来将商品实例链接到shop实例.下列哪个解决方案是最好/最简洁的REST设计:

Now we need a rest call to link the article instance to the shop instance. Which of the following solutions is the best / most clean REST design:

  1. /shop/id/article/id/->使用POST
  2. /shop/id/article/id/->使用PUT
  3. /shoparticlerelation/-->带有POST(主体中具有id的对象)
  4. /shoparticlerelation/->与PUT(体内具有id的对象)

如果没有明确的答案或所有解决方案都一样好,那么如果有明确的理由,这也可能是有效的答案.

If there is no clear answer or all solutions are equally good this may also be a valid answer if there is a clear argumentation why.

推荐答案

在这种情况下,我假设您已经有一个shop的集合和一个article的集合,并且您只希望将两个链接在一起.

I presume in this situation you already have a collection of shops and a collection of articles, and you just wish to link two together.

一个选项是公开更多的数据库,例如资源",以显示此链接,并进行类似的操作

One option is to expose a more db like 'resource' that presents this link, and have operations like

POST /shopArticleLinks HTTP/1.1

{ "shop"  : xxx,
  "article: YYY
}

我个人希望将其作为商店和/或商品的财产公开在更自然的庄园中,例如

I would personally look to expose it as a property of the shops and/or articles in a more natural manor, like

PUT /shop/<ID> HTTP/1.1

{ /* existing details */
  "articles": [ /* list of articles */ ]
}

我在那里使用过JSON,但是当然要使用您要使用的任何格式.我也坚持使用您所说的PUT,但是请记住,使用PUT您应该发送新的修改版本的完整替代品,可以使用PATCH发送部分更新,但是随后您需要考虑如何做这样,也许像

I've used JSON there, but of course use what ever format you want to use. I've also stuck with using PUT as you stated, but keep in mind that with PUT you should send a full replacement for the new modified version, PATCH can be used to send partial updates, but then you need to consider how you want do that, may something like

PATCH /shops/<ID>/articleLinks HTTP/1.1

{ "add"   : [],
  "remove : []
}

别忘了在服务器端,您可以查看所引用的articles并确保它们具有正确的后向指针.

Don't forget that server side you can look at what articles are being refereed to and ensure they have a proper back pointer.

其他想法

关于第二种方法,您将链接公开为shop和/或article资源的属性.请记住,在更新给定shop中的链接时,也更新了相应articles中的链接也是完全可以接受的(在这种情况下,这是相当合适的).

Regarding the second method, where you expose the link as a property of the shop and/or article resources. Keep in mind that it is perfectly acceptable (and in this case rather appropriate) that when you update the links in a given shop that the links in the corresponding articles are also updated.

这篇关于RESTful API设计:用于创建多对多关系的PUT或POST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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