简体   繁体   English

当属性不存在时,在REST JSON API上POST / PUT

[英]POST/PUT on REST JSON API when property doesn't exist

We are building public RESTful JSON API and trying to figure out what is the best practice for POST/PUT requests when specified property doesn't exist. 我们正在构建公共RESTful JSON API,并试图找出当指定属性不存在时POST / PUT请求的最佳实践。 Should we throw an HTTP error and which one or just skip it and apply all other properties? 我们应该抛出HTTP错误,哪一个或只是跳过它并应用所有其他属性?

{
    "name" : "Test",
    "property_doesnt_exist" : "that's sad"
}

HTTP 422: Unprocessable Entity HTTP 422:不可处理的实体

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. 422(不可处理实体)状态代码表示服务器理解请求实体的内容类型(因此415(不支持的媒体类型)状态代码是不合适的),并且请求实体的语法是正确的(因此是400(错误请求) )状态代码不合适)但无法处理包含的指令。 For example, this error condition may occur if an XML request body contains well-formed (ie, syntactically correct), but semantically erroneous, XML instructions. 例如,如果XML请求主体包含格式正确(即语法正确)但语义错误的XML指令,则可能发生此错误情况。 RFC4918 RFC4918

A common practice is NOT to add valid message properties if the message also contains invalid properties. 如果消息还包含无效属性,则通常的做法是不添加有效的消息属性。

A common rule for a server is to be generous in what you accept and strict in what you produce. 服务器的一个常见规则是慷慨接受你所接受的内容并严格遵守你所生产的内容。

I'd prefer to accept such an input and get as much as possible out of it. 我更愿意接受这样的输入并尽可能多地获取它。 Any unknown property of the input would be ignored. 输入的任何未知属性都将被忽略。

When answering that question you have to consider versioning too. 在回答这个问题时,你也必须考虑版本控制。 Do you support old clients that send fewer arguments than expected - that could work with suitable defaults. 您是否支持发送的参数少于预期的旧客户端 - 可以使用合适的默认值。 Or do you have more than one server implementation such that newer clients would be sending too many arguments for an older server implementation? 或者,您是否有多个服务器实现,以便较新的客户端为较旧的服务器实现发送过多的参数? If the answer is yes to one of these then you have to be careful about rejecting inputs. 如果其中一个答案是肯定的,那么你必须小心拒绝输入。

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

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