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

查看:27
本文介绍了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 调用来将文章实例链接到商店实例.以下哪个解决方案是最好/最干净的 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 : []
}

不要忘记服务器端你可以查看哪些文章被引用并确保它们有一个正确的返回指针.

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天全站免登陆