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

时间:2014-04-02 18:44:41

标签: json api http rest architecture

我正在寻找实用指南来实现PATCH动词,以便使用JSON在RESTful api中对名词进行部分更新。理解PATCH用于部分更新,我们仍然缺乏关于删除键,创建或更新嵌套键和数组的语法的标准化。

让我说GET一个对象:

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

...然后我想更新它:

// 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
  }
}

PATCH rfc说no to creating nested keys。我认为这是一个规范错误,因为创建嵌套密钥是不明确的。

我可以发送一个完整的对象差异,就像this library生成一样,但是这使得添加或更新密钥的明显情况更加冗长。

如何使用HTTP PATCH以精益方式处理数组,删除和嵌套键?

1 个答案:

答案 0 :(得分:21)

spec清楚地详细说明了如何格式化PATCH请求的JSON主体。你使用的是完全不同的格式。鉴于此,我并不感到惊讶。身体应该看起来像:

   [
     { "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" } }
   ]

返回并阅读规范。它甚至提供了解决大部分问题的例子。