返回REST API中错误的HTTP方法的代码? [英] Return code for wrong HTTP method in REST API?

查看:529
本文介绍了返回REST API中错误的HTTP方法的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的API用户可以通过向根API地址发送 GET 请求来获取 root 文档(集合列表)。如果他发送 POST ,我们应该返回一些东西。同样的问题适用于其他资源路径,例如在查询路径上发送 PATCH 等。并非所有方法在某些路径上都有意义。

Our API user can get the root document (collection list) by sending GET request to root API address. If he sends POST, we should return something. The same question applies for other resource paths, like e.g. sending PATCH on query path etc. Not all methods have meaning on some paths.

正如我从HTTP RFC看到的那样是我们应该返回代码 405 方法不允许并发回允许的回复带有允许方法列表的标题。

As I see from HTTP RFCs is that we should return code 405: Method not allowed and sending back the Allowed response header with list of allowed methods.

我看到了例如GitHub API在我上面解释的情况下返回 404 未找到(发送 POST 到root)。

I see that e.g. GitHub API returns 404: Not found in the case I explained above (sending POST to root).

什么是正确的答案? 404 405 ?我看到 405 更适合开发人员,所以有什么理由不使用它吗?

What would be the proper response? 404 or 405? I see 405 more developer-friendly, so is there any reason not to use it?

推荐答案

在这种情况下,根据HTTP规范和REST准则,预期的行为是返回 405 Method Not Allowed 资源就在那里,因为GET有效,所以 404 Not Found 会让人感到困惑。

The expected behavior in this case, as per the HTTP spec and by REST guidelines, would be to return 405 Method Not Allowed. The resource is there, since a GET works, so a 404 Not Found would be confusing.

我不熟悉 GitHub API 但在某些情况下我看到 403 Forbidden 它还返回 404 Not Found

I'm not familiar with the GitHub API but in some cases I see that for 403 Forbidden it also returns 404 Not Found:


在某些地方,要求身份验证的请求将返回404 Not Found,而不是403 Forbidden。这是为了防止私有存储库意外泄露给未经授权的用户。

Requests that require authentication will return 404 Not Found, instead of 403 Forbidden, in some places. This is to prevent the accidental leakage of private repositories to unauthorized users.

根源地址上的行为可能是更大机制的一部分一般来说,处理此类案件,谁知道。 也许你可以问一下

Maybe the behavior on the root address is part of a bigger mechanism that handles such cases generally, who knows. Maybe you could ask?

这篇关于返回REST API中错误的HTTP方法的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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