Return code for wrong HTTP method in REST API?

2019-04-18 08:24发布

问题:

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.

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.

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

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

回答1:

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.

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

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?



标签: api rest http