REST API中的Patch請(qǐng)求大家都用錯(cuò)了,這才是正確姿勢(shì)
環(huán)境:SpringBoot3.2.5
1. 簡(jiǎn)介
HTTP PATCH 方法它允許我們對(duì) HTTP 資源進(jìn)行部分更新。
在篇文章,將帶你如何使用 HTTP PATCH 方法和 JSON Patch文檔格式對(duì) RESTful 資源進(jìn)行部分更新。
HTTP PATCH 請(qǐng)求正文(Request Body)描述了如何修改目標(biāo)資源以生成新版本。簡(jiǎn)而言之,JSON Patch 格式使用 "一系列操作 "來(lái)描述應(yīng)如何修改目標(biāo)資源。JSON Patch文檔是一個(gè) JSON 對(duì)象數(shù)組。數(shù)組中的每個(gè)對(duì)象正好代表一個(gè) JSON Patch操作。Request Body請(qǐng)求格式如下:
[
{
"op": "replace|add|remove|move|copy|test",
"path": "/xxx",
["value": "value"],
["from": "/yyy"]
},
...
]
op:具體的操作
path:資源路徑
value:變更值;根據(jù)操作op不同,決定是否有該屬性
from:資源路徑;根據(jù)操作op不同,決定是否有該屬性
接下來(lái),通過(guò)具體的示例來(lái)了解 JSON Patch操作。
2. JSON Patch操作
接下來(lái)的所有操作都基于下面的資源進(jìn)行:
{
"id": 1,
"telephone": "001-555-1234",
"favorites": ["Milk","Eggs"],
"communicationPreferences": {"post":true, "email":true}
}
假設(shè)有上面的資源數(shù)據(jù),下面將分別介紹基于該資源如何進(jìn)行不同的操作。
2.1 add添加操作
添加操作為對(duì)象添加新值。此外,我們還可以用它來(lái)更新現(xiàn)有成員,并在指定索引處向數(shù)組中插入一個(gè)新值。
給favorities數(shù)據(jù)添加新值,并且插入到第一個(gè)位置。
請(qǐng)求Body
{
"op": "add",
"path": "/favorites/0",
"value": "Bread"
}
結(jié)果
{
"id": "1",
"telephone": "001-555-1234",
"favorites": ["Bread","Milk","Eggs"],
"communicationPreferences": {"post":true, "email":true}
}
2.2 remove刪除操作
不僅可以刪除指定屬性的值,如果是數(shù)組還可以刪除指定索引位置的元素。
刪除communicationPreferences屬性值
請(qǐng)求Body
{
"op": "remove",
"path": "/communicationPreferences"
}
結(jié)果
{
"id": "1",
"telephone": "001-555-1234",
"favorites": ["Bread","Milk","Eggs"],
"communicationPreferences": null
}
2.3 replace替換操作
將目標(biāo)屬性值更新為一個(gè)新的值;
更新電話(huà)號(hào)碼;
請(qǐng)求Body
{
"op": "replace",
"path": "/telephone",
"value": "001-555-5678"
}
結(jié)果
{
"id": "1",
"telephone": "001-555-5678",
"favorites": ["Bread","Milk","Eggs"],
"communicationPreferences": null
}
2.4 move移動(dòng)操作
移動(dòng)操作會(huì)移除指定位置的值,并將其添加到目標(biāo)位置。
移動(dòng)favorities屬性第0號(hào)位置元素到最后一個(gè)位置。
請(qǐng)求Body
{
"op": "move",
"from": "/favorites/0",
"path": "/favorites/-"
}
結(jié)果
{
"id": "1",
"telephone": "001-555-5678",
"favorites": ["Milk","Eggs","Bread"],
"communicationPreferences": null
}
2.5 copy復(fù)制操作
復(fù)制操作將指定位置的值復(fù)制到目標(biāo)位置。
將favorites屬性中的Milk復(fù)制一份到該屬性的最后位置。
請(qǐng)求Body
{
"op": "copy",
"from": "/favorites/0",
"path": "/favorites/-"
}
結(jié)果
{
"id": "1",
"telephone": "001-555-5678",
"favorites": ["Milk","Eggs","Bread","Milk"],
"communicationPreferences": null
}
2.6 test測(cè)試操作
測(cè)試操作測(cè)試 "路徑 "上的值是否等于 "值"。
請(qǐng)求Body
{
"op": "test",
"path": "/telephone",
"value": "001-555-5678"
}
注意:JSON Patch請(qǐng)求的Content-Type類(lèi)型為:application/json-patch+json
接下來(lái)將實(shí)戰(zhàn)演示在Spring Boot中如何使用JSON Patch。
3. 實(shí)戰(zhàn)案例
3.1 引入依賴(lài)
<dependency>
<groupId>com.github.java-json-tools</groupId>
<artifactId>json-patch</artifactId>
<version>1.13</version>
</dependency>
該組件是RFC 6902(JSON Patch)和RFC 7386(JSON Merge Patch)的實(shí)現(xiàn),其核心使用Jackson(2.2.x)。該組件的特性:
- JSON Patch的序列化和JSON與Jackson Merge Patch實(shí)例
- 全面支持RFC 6902操作,包括測(cè)試
- JSON“差異”(僅RFC 6902)與運(yùn)算因子分解
接下來(lái)進(jìn)入實(shí)踐代碼的編寫(xiě)
3.2 定義實(shí)體類(lèi)
public class Customer {
/**編號(hào)*/
private Long id ;
/**電話(huà)*/
private String telephone ;
/**收藏集*/
private List<String> favorites ;
/**通信首選項(xiàng)*/
private Map<String, Boolean> communicationPreferences ;
public Customer(Long id, String telephone, List<String> favorites,
Map<String, Boolean> communicationPreferences) {
this.id = id ;
this.telephone = telephone ;
this.favorites = favorites ;
this.communicationPreferences = communicationPreferences ;
}
// getters, setters
}
定義異常類(lèi)
public static class CustomerNotFoundException extends RuntimeException {
}
當(dāng)沒(méi)有資源時(shí)拋出該異常類(lèi)
3.3 Service類(lèi)
@Service
public static class CustomerService {
// 模擬靜態(tài)數(shù)據(jù)
private static List<Customer> DATAS = List
.of(new Customer(
1L, "188",
List.of("Milk", "Eggs"),
Map.of("phone", true, "email", true)));
// 根據(jù)ID查詢(xún)操作
public Optional<Customer> findCustomer(Long id) {
return DATAS.stream().filter(customer -> customer.getId() == id).findFirst();
}
}
接下來(lái)就是關(guān)鍵的Controller接口的編寫(xiě)了
3.4 Controller接口
@PatchMapping(path = "/{id}", consumes = "application/json-patch+json")
public ResponseEntity<Customer> updateCustomer(@PathVariable Long id, @RequestBody JsonPatch patch) {
try {
// 查詢(xún)資源
Customer customer = customerService.findCustomer(id).orElseThrow(CustomerNotFoundException::new);
Customer customerPatched = applyPatchToCustomer(patch, customer);
return ResponseEntity.ok(customerPatched);
} catch (JsonPatchException | JsonProcessingException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
} catch (CustomerNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
}
// 將請(qǐng)求的操作轉(zhuǎn)換成真實(shí)的資源變更
private Customer applyPatchToCustomer(JsonPatch patch, Customer targetCustomer)
throws JsonPatchException, JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper() ;
JsonNode patched = patch.apply(objectMapper.convertValue(targetCustomer, JsonNode.class));
return objectMapper.treeToValue(patched, Customer.class);
}
在該接口中注意以下兩點(diǎn):
- consumes屬性設(shè)置為application/json-patch+json,也就是請(qǐng)求的Content-Type必須是該值。
- 請(qǐng)求body通過(guò)JsonPatch對(duì)象接收。
接下來(lái)進(jìn)行測(cè)試:
圖片
請(qǐng)求Body中定義了2個(gè)操作,replace與add。最后返回的結(jié)果表明操作成功,數(shù)據(jù)得到了變更。