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

查看:29
本文介绍了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: Method not allowed 并发送回带有列表的 Allowed 响应标头允许的方法.

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: Not found 在我上面解释的情况下(将 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天全站免登陆