我应该如何更新 REST 资源? [英] How should I update a REST resource?

查看:42
本文介绍了我应该如何更新 REST 资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定应该如何更新 REST 资源的各个属性.考虑以下示例:

I'm not sure how I should go about updating individual properties of a REST resource. Consider the following example:

# HTTP GET to /users/1.xml
<?xml version="1.0" encoding="UTF-8" ?>
<response>
   <user>
      <id>1</id>
      <name>John Doe</name>
      <email>john@doe.com</email>
   </user>
</response>

我应该如何促进更新 John 的电子邮件?我想到了 HTTP PUT,但我会要求一个完整的 XML(匹配 HTTP GET 响应)来修改资源,这会让我的客户端变得困难.

How should I facilitate for updating John's email? HTTP PUT comes to mind, but I'd be making it hard on my clients by requiring a complete XML (matching the HTTP GET response) to modify the resource.

PUT 方法要求封闭实体存储在提供的请求 URI.如果请求 URI 指的是一个已经现有资源,封闭实体应该被认为是修改过的居住在源服务器.

The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server.

还有什么办法吗?

推荐答案

如果您的服务器框架足够灵活来处理它,您可以这样做:

If your server framework is flexible enough to handle it, you can do:

Request:
PUT /users/1/email
Content-Type: text/plain

john@newemail.com

Response:
200 OK
Content-Location: /users/1

通过使用 URL 将电子邮件作为其自己的资源引用,您可以使用简单的格式(如 text/plain)直接 PUT 到它.在响应中,Content-Location url 向客户端表明更改对用户资源产生了影响.

By using a URL to refer to the email as its own resource, you can PUT directly to it using a simple format like text/plain. In the response, the Content-Location url gives the client an indication that the change has had an impact on the user resource.

PATCH 方法也是您可以进行部分更新的另一种方式.这是一种新引入的方法,目前还没有用于发送 XML 差异文档的标准格式.因此,如果您采用这种方法,您将找不到太多指导.

The PATCH method is also another way that you can do partial updates. This is a newly introduced method and as yet there are no standard formats for sending XML diff documents. So, if you take this approach you will not find much guidance.

要考虑的另一件事是 REST 最适合大粒度的更新.如果您发现自己需要进行这些小改动,那么您可能需要重新考虑您的分布式架构.

The other thing to consider is that REST works best with large grained updates. If you find yourself needing to make these kinds of small changes, then maybe you need to rethink your distributed architecture.

这篇关于我应该如何更新 REST 资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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