HTTP PATCH:处理数组,删除和嵌套密钥创建 [英] HTTP PATCH: Handling arrays, deletion, and nested key creation

查看:509
本文介绍了HTTP PATCH:处理数组,删除和嵌套密钥创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for a practical guide to implementing the PATCH verb for partial updates of a noun in a RESTful api using JSON. Understanding that PATCH is for partial updates, we lack still standardization around the syntax for deleting keys, creating or updating nested keys, and arrays.

假设我 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
  }
}

PATCH rfc说不创建嵌套键。我认为这是一个规范错误,因为创建嵌套键是不明确的。

The PATCH rfc says no to creating nested keys. 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.

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

How do I handle arrays, deletion, and nested keys in a lean way with HTTP PATCH?

推荐答案

规范清楚地详细说明了如何格式化PATCH请求的JSON主体。你使用的是完全不同的格式。鉴于此,我并不感到惊讶。正文应该类似于:

The spec clearly details how to format the JSON body of a PATCH request. 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.

这篇关于HTTP PATCH:处理数组,删除和嵌套密钥创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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