Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return code for wrong HTTP method in REST API?

Tags:

rest

http

api

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?

like image 240
igr Avatar asked Jan 22 '15 10:01

igr


People also ask

How do I send HTTP error messages in REST API?

The most basic way of returning an error message from a REST API is to use the @ResponseStatus annotation. We can add the error message in the annotation's reason field. Although we can only return a generic error message, we can specify exception-specific error messages.

What is a 201 response code?

The HTTP 201 Created success status response code indicates that the request has succeeded and has led to the creation of a resource.

How do I find HTTP return code?

Just use Chrome browser. Hit F12 to get developer tools and look at the network tab. Shows you all status codes, whether page was from cache etc.

What does return code 200 mean?

An HTTP status code 200 means success. The client has requested documents from the server. The server has replied to the client and given the client the documents. All is well.


1 Answers

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?

like image 161
Bogdan Avatar answered Oct 02 '22 16:10

Bogdan