rest api update resource with partial json

2019-09-14 10:25发布

问题:

Want to understand good practice to design REST API

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

Please advice if my understanding is correct

POST - to persist Customer with 2 address

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

Now to update zip code for address id 1

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 - partial (or full) JSON can be sent to REST API ?

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

回答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.