gpt4 book ai didi

java - PUT 方法中路径变量为空时的 HTTP 响应

转载 作者:太空宇宙 更新时间:2023-11-04 09:04:24 25 4
gpt4 key购买 nike

我正在尝试找到最佳实践,了解当使用 PUT 方法时 REST 服务中的路径参数为空或 null 时,应该发送哪种类型的响应。

例如,假设我们有以下资源:

PUT report/{report-id}/client/{client-id}

我应该验证参数report-id和client-id不为空或空白吗?

如果它们为空或为空,我可以想到两种类型的消息:

  • 返回 400 响应,其中包含一条消息,表明强制执行缺少参数。
  • 返回 404 响应,表示我们无法创建或更新资源,因为该资源不存在?

我认为没有这样做的标准惯例。有没有?不过,我想听听关于在这种情况下使用的最佳实践的意见。

最佳答案

REST 规范在这里可能很有洞察力:

The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service (e.g. "today's weather in Los Angeles"), a collection of other resources, a non-virtual object (e.g. a person), and so on. In other words, any concept that might be the target of an author's hypertext reference must fit within the definition of a resource. A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time.

由于缺少资源在逻辑上无法命名,因此它永远不会存在于 REST 中。因此,我认为您会发现大多数公共(public) API 都会返回 404。以从 GitHub 获取用户信息为例。该文档指出可以在 https://api.github.com/users/{username} 找到用户。 https://api.github.com/users/ (注意结尾的斜杠)返回404。无论 HTTP 规范如何规定(尽管遵循它总是一个好主意),如果您遵守 principle of least surprise返回 404 是您最好的选择。

顺便说一句,在命名资源时,约定集合应该是复数。因此,对于您的示例,您实际上希望资源看起来更像:/reports/{report-id}/clients/{client-id}。特别是在处理“空”参数时,它会让请求的具体用途变得更加清晰。

关于java - PUT 方法中路径变量为空时的 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60403477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com