简体   繁体   English

HTTP PATCH:处理数组,删除和嵌套密钥创建

[英]HTTP PATCH: Handling arrays, deletion, and nested key creation

I'm looking for a practical guide to implementing the PATCH verb for partial updates of a noun in a RESTful api using JSON. 我正在寻找一个实用指南来实现PATCH动词,以便使用JSON在RESTful api中对名词进行部分更新。 Understanding that PATCH is for partial updates, we lack still standardization around the syntax for deleting keys, creating or updating nested keys, and arrays. 了解PATCH是用于部分更新的,我们仍然缺乏关于删除键,创建或更新嵌套键和数组的语法的标准化。

Let's say I GET an object: 让我们说我GET一个对象:

// GET users/42
{
  id: 42,
  name: 'SimpleAsCouldBe',
  city: 'San Francisco',
  roles: ['viewer','editor'],
  posts: {
    '01': {},
    '02': {},
  }
}

...Then I want to update it: ...然后我想更新它:

// PATCH users/42
{
  name: 'SimpleGuy',                   // CLEAR:   update the key's value
  email: 'hey@google.com',             // CLEAR:   add the new key
  city: null                           // UNCLEAR: delete the key?
  roles: ['owner'],                    // UNCLEAR: replace the whole array?
  posts: {
    '02': { title:'how to pop lock' }, // CLEAR:  update nested key
    '03': { title:'how to salsa' }     // CLEAR:  create new nested key
  }
  notes: {
    '01': { title: 'a note title' }    // CLEAR (but disallowed?): create wrapping key
  }
}

The PATCH rfc says no to creating nested keys . PATCH rfc拒绝创建嵌套密钥 This is a spec bug, I think, because creating a nested key is non-ambiguous. 我认为这是一个规范错误,因为创建嵌套键是非模糊的。

I could send a full object diff, like this library generates, but this makes the clear case of adding or updating a key more verbose. 我可以发送一个完整的对象差异,就像这个库生成的那样,但是这使得添加或更新密钥的明显情况更加冗长。

How do I handle arrays, deletion, and nested keys in a lean way with HTTP PATCH? 如何使用HTTP PATCH以精益方式处理数组,删除和嵌套键?

The spec clearly details how to format the JSON body of a PATCH request. 规范清楚地详细说明了如何格式化PATCH请求的JSON主体。 You're using a totally different format. 你使用的是完全不同的格式。 Given that, I'm not surprised at all that there is ambiguity. 鉴于此,我并不感到惊讶。 The body should look something like: 身体应该看起来像:

   [
     { "op": "replace", "path": "/name", "value": "SimpleGuy" },
     { "op": "add", "path": "/email", "value": "hey@google.com" },
     { "op": "replace", "path": "/city", "value": null },
     { "op": "replace", "path": "/roles", "value": [ "owner" ] },
     { "op": "add", "path": "/posts/02/title", "value": "how to pop lock" },
     { "op": "add", "path": "/posts/", "value": "03" },
     { "op": "add", "path": "/posts/03/title", "value": "how to salsa" },
     { "op": "add", "path": "/notes", "value": { "title": "a note title" } }
   ]

Go back and read the spec. 回去阅读规范。 It even gives examples which address most of your questions. 它甚至提供了解决您大部分问题的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM