REST - 是否将 ID 放入正文? [英] REST - put IDs in body or not?

查看:59
本文介绍了REST - 是否将 ID 放入正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想为人们提供一个 RESTful 资源,客户端可以在其中分配 ID.

Let's say I want to have a RESTful resource for people, where the client is able to assign ID.

一个人看起来像这样:{"id": <UUID>, "name": "Jimmy"}

现在,客户端应该如何保存(或PUT")它?

Now, how should the client save (or "PUT") it?

  1. PUT/person/UUID {"id": <UUID>, "name": "Jimmy"} - 现在我们有这个讨厌的重复,我们必须一直验证:正文中的 ID 与路径中的 ID 匹配吗?
  2. 非对称表示:
    • PUT/person/UUID {"name": "Jimmy"}
    • GET/person/UUID 返回 {"id": <UUID>, "name": "Jimmy"}
  1. PUT /person/UUID {"id": <UUID>, "name": "Jimmy"} - now we have this nasty duplication that we have to verify all the time: Does the ID in body match the one in path?
  2. Asymmetric representation:
    • PUT /person/UUID {"name": "Jimmy"}
    • GET /person/UUID returns {"id": <UUID>, "name": "Jimmy"}
  • PUT/person/UUID {"name": "Jimmy"}
  • GET/person/UUID 返回 {"name": "Jimmy"}

常见的模式和解决方法有哪些?仅位置 ID 似乎是最教条正确的方法,但它也使实际实施变得更加困难.

What are the common patterns and ways to solve it? IDs only in location seems like the most dogmatically correct way, but it also makes the practical implementation harder.

推荐答案

拥有不同的读/写模型并没有错:客户端可以编写一个资源表示,然后服务器可以返回另一个包含添加/计算元素的表示它(或者甚至是完全不同的表示形式——任何规范中都没有反对它,唯一的要求是 PUT 应该创建或替换资源).

There is nothing wrong in having different read/write models: the client can write one resource representation where after the server can return another representation with added/calculated elements in it (or even a completely different representation - there is nothing in any spec against that, the only requirement is that PUT should create or replace the resource).

所以我会在(2)中采用非对称解决方案,并在编写时避免服务器端的讨厌的重复检查":

So I would go for the asymmetric solution in (2) and avoid the "nasty duplication check" on the server side when writing:

PUT /person/UUID {"name": "Jimmy"}

GET /person/UUID returns {"id": <UUID>, "name": "Jimmy"}

这篇关于REST - 是否将 ID 放入正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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