带有部分json的rest api更新资源 [英] rest api update resource with partial json

查看:115
本文介绍了带有部分json的rest api更新资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想了解设计REST API的良好做法

Want to understand good practice to design REST API

如果需要部分更新资源,哪个更好? PUT或PATCH

If a resource needs to be update partially, which is better? PUT or PATCH

如果我的理解正确,请提出建议

Please advice if my understanding is correct

POST -使用2个地址保留客户

POST - to persist Customer with 2 address

{"custId":"1", "name":"Rocky", 
"address":[{"id":"1","zip":"1234"}, 
{"id":"2","zip":"12345"}]
}

现在<地址> 1的更新邮政编码

PUT -将完整的JSON发送到REST API是必需的吗?

PUT - full JSON is a requirement to be sent to REST API ?

{"custId":"1", "name":"Rocky", 
"address":[{"id":"1","zip":"9876"}, 
{"id":"2","zip":"12345"}]
}

PATCH -是否可以将部分(或全部)JSON发送到REST API?

PATCH - partial (or full) JSON can be sent to REST API ?

{"custId":"1", "name":"Rocky", 
"address":[{"id":"1","zip":"9876"}]
}

推荐答案

您的理解基本上是正确的,但是您的示例暗示了您的思维中可能存在的问题.您正在讨论的文档实际上是具有地址集合的客户.每个地址都可以看作一个单独的文档,因为它具有ID.因此,您的api应该允许您更新单个地址而无需更新客户.您的示例中缺少的是资源的URI.因此,您应该使用customer/1这样的名称来标识客户,也许应该使用customer/1/address/1这样的名称来标识地址.

Your understanding seems basically correct, but your example hints at a possible problem in your thinking. The document you're talking about is actually a customer with a collection of addresses. Each address could be seen as a separate document, because it has an ID. Therefore, your api should allow you to update a single address without updating a customer. What you're missing in your example is the URI for the resources. So, you should have something like customer/1 to identify the customer and maybe something like customer/1/address/1 to identify the address.

这篇关于带有部分json的rest api更新资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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