gpt4 book ai didi

rest - 应该从 REST API 返回哪个 HTTP 代码?

转载 作者:可可西里 更新时间:2023-11-01 15:26:35 25 4
gpt4 key购买 nike

我目前正在一个网站上工作,该网站在后端有 Spring,在前端有 Angularjs,我们讨论了后端响应以处理前端的消息对话框,我有一个问题要问:

假设我有一个 API:

GET : /getstatistics
Request params : fromTime,toTime ( in timestamp format)

如果客户端发出带有无效参数(如字符串)的请求,服务器应返回哪个响应代码?带有消息“fromTime 和 toTime 应该采用时间戳格式”的 HTTP 400 错误请求和响应正文或带有相同消息的 HTTP 200?

我看到了一些 Google 的 API,例如 Oauth,它们为具有无效 access_token 的请求返回代码 200 但是,在我们的项目中我认为它应该是 HTTP 400 因为 Javascript 有成功和错误回调,它更好吗因为它只是弹出一个红色对话框,里面有消息而不是 HTTP 200 代码,那么还需要检查消息的内容吗?

欢迎任何建议和意见。

谢谢!

最佳答案

对于错误的请求,您应该返回 400 错误。查看this引用。

The server cannot or will not process the request due to somethingthat is perceived to be a client error (e.g., malformed requestsyntax, invalid request message framing, or deceptive requestrouting).

请看RFC7231#section-6

A client MUST understand the class of any status code, as indicated bythe first digit

和,

4xx (Client Error): The request contains bad syntax or cannot befulfilled

错误的语法可能就像您在问题中提到的那样(使用无效参数发出请求,例如字符串)。

每当我设计 RESTful API 时,我都会将这两个引用资料放在手边,可能对您也有帮助:

  1. https://httpstatuses.com/
  2. http://www.restapitutorial.com/httpstatuscodes.html

关于rest - 应该从 REST API 返回哪个 HTTP 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40320032/

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