Let's say I've got route /posts. It only implements GET HTTP method.
If someone tries to access it with different, existing method (POST, PUT, etc.) I return 405.
What should I return in case someone tries using some unsupported, nonexistent method like MYCUSTOMMETHOD or SFASFS? 405 method not allowed or rather 501 not implemented or maybe even 400 bad request (seems to be default behaviour in node express) , as such methods are not in HTTP specs?
Related
In my case there is no parameters required. In other words, the application does not expect any data via post, get or put. However, in the implementation a stored list of items in session variable should be defined first i.e. something like shopping cart items, the user collect items, and then go to the action below, otherwise, it should throw an HTTP error. Checkout the example below:
public function actionCreate(){
if(count(Yii::$app->session->get('versesList',[])) > 0){
// Do the logic
}
else{
throw new \yii\web\BadRequestHttpException(Yii::t('app', 'You must collect some verses first!'));
}
}
I don't know exactly, if the 400 bad request is the proper error code or not. I have tried reading List of HTTP status codes on the Wikipedia but I have gotten confused among some of the other HTTP errors such as: 406 Not Acceptable, 412 Precondition Failed,422 Unprocessable Entity
HTTP 400, since you are requesting an operation the server doesn't know how to handle (so it's a bad request).
RFC2731 states the following:
The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
400 is definitely fine for this case, but if you want to get more specific:
it sounds like the user needs to do some other HTTP request for this HTTP request to be valid. It's common to use 409 Conflict for these cases.
I wrote a bit more about this with additional examples on my blog, if it's interesting: https://evertpot.com/http/409-confict
Example:
We provide a URL http://.../foo/download.csv
web client (MS office) opens above URL and tries to access (for reasons I really don't know) http://.../foo/ with an http OPTIONS request.
Up to now or app returns 404 since the above URL does not exist (even for GET requests).
I think All OPTIONS requests should get a 405. It should not matter if the URL would be accessible via GET or POST.
Does this match the http spec?
Here is my explanation why I think 405 fits better: If there is an OPTIONS request, I don't want to look at the path. I don't care what the path looks like, there should always be the same answer: Not allowed.
Up to now it depends: if there is a GET-view registered, then we return 405. Otherwise a 404 gets returned.
Update: 404 vs 405
HTTP-Spec 405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.
Source: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6
It's not really clear why you want it to return a 405, to be honest. It'll never get as far as checking the method, because the 404 handler will be invoked first - there's no view logic for it to get, that's what the 404 is. This is the default, and correct, behaviour.
I suspect, if you don't want to write custom middleware for it, and you insist on implementing it, that overriding the 404 handler would be the way forward - if a 404 Handler is invoked, check the method and return that accordingly - this is messy though, and the custom middleware would be more pythonic.
def handler404(request):
if request.method == 'OPTION':
#return your custom 405 response
else:
#go on and do your regular 404.
I am developing a RESTful web service. The web service receives XML from clients, it should reject some bad requests containing some error related to our business logic(say, the payment value below a minimum value). If rejecting request, a customised error code and error message will be written in a response XML(inside http response body). I also want to return a HTTP code in the status line, so client can recognize rejection right away without looking into the response boday. Some people suggest using HTTP code 412, however by looking at the definition of HTTP 412:
412 Precondition Failed
The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server. This response code allows the client to place preconditions on the current resource metainformation (header field data) and thus prevent the requested method from being applied to a resource other than the one intended.
I don't quite understand what it represents for. Could someone explain the appropriate usage of 412 please? or in this case are there any better choices?
It's for use with conditional requests: http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p4-conditional-25.html.
You may want to look at 422 or 409 instead.
I am implementing a simple rest service with the 4 http methods get,post, put and delete using sitebricks. trying to send a delete request to the defined service with a WebClient I get a 405 response. Does anyone knows why would I get such response ?
10:22:24.840 [5907955#qtp-6711891-2 - /r/clients/123] DEBUG org.mortbay.log - RESPONSE /r/clients/123 405
This is how I use web client
WebClient client = web().clientOf(delete(123)).transports(String.class).over(Json.class);
client.delete();
here is my delete method
#Delete
#At("/:id")
public Reply delete(#Named("id") String id) {
clientsRepository.delete(id);
return Reply.saying().ok();
}
I am using Jetty Server.
Response code 405 means that something is configured to not allow the use of the http DELETE method.
I can't speak for sitebricks itself, but servlet spec allows you to disable specific methods.
The web.xml of your webapp or the ${jetty.home}/etc/webdefault.xml, as either could be configured to disallow the use of specific HTTP methods (like TRACE, PUT, DELETE).
Check those files for <security-constraints> that might have <http-method> declarations for DELETE.
Also note that any code can trigger the 405 response itself.
Since you are seeing this in Sitebricks, possibly a <filter> in your web.xml is preventing it.
Are you constructing the request URI properly? Sitebricks returns 405 if there is no handler method. This test case verifies that #Delete does indeed work properly:
https://github.com/dhanji/sitebricks/blob/master/sitebricks-acceptance-tests/src/main/java/com/google/sitebricks/example/RestfulWebServiceWithSubpaths2.java
Also as joakime says, do check if any other filters or handlers are firing outside Sitebricks.
I have several pages designed to be called with AJAX - I have them return an abnormal status code if they can't be displayed, and my javascript will show an error box accordingly.
For example, if the user is not authenticated or their session has timed out and they try to call one of the AJAX pages, it will return 401 Unathorized.
I also have some return 500 Internal Server Error if something really odd happens server-side.
What status code should I return if one of these pages was called without required parameters? (and therefore can't return any content).
I had a look at the wikipedia article on HTTP status codes, but the closest one I could find to the code I'm looking for was this:
422 Unprocessable Entity
The request was well-formed but was unable to be followed due to semantic errors.
Edit: The above code is WebDAV specific and therefore unlikely to be appropriate in this case
Can anyone think of an appropriate code to return?
What status code should I return if one of these pages was called without required parameters? (and therefore can't return any content).
You could pick 404 Not Found:
The server has not found anything matching the Request-URI [assuming your required parameters are part of the URI, i.e. $_GET]. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.
(highlight by me)
404 Not Found is a subset of 400 Bad Request which could be taken as well because it's very clear about what this is:
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
This is normally more common with missing/wrong-named post fields, less with get requests.
As Luca Fagioli comments, strictly speaking 404, etc. are not a subset of the 400 code, and correctly speaking is that they fall into the 4xx class that denotes the server things this is a client error.
In that 4xx class, a server should signal whether the error situation is permanent or temporary, which includes to not signal any of it when this makes sense, e.g. it can't be said or would not be of benefit to share. 404 is useful in that case, 400 is useful to signal the client to not repeat the request unchanged. In the 400 case, it is important then for any request method but a HEAD request, to communicate back all the information so that a consumer can verify the request message was received complete by the server and the specifics of "bad" in the request are visible from the response message body (to reduce guesswork).
I can't actually suggest that you pick a WEBDAV response code that does not exist for HTTP clients using hypertext, but you could, it's totally valid, you're the server coder, you can actually take any HTTP response status code you see fit for your HTTP client of which you are the designer as well:
11.2. 422 Unprocessable Entity
The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a
415(Unsupported Media Type) status code is inappropriate), and the
syntax of the request entity is correct (thus a 400 (Bad Request)
status code is inappropriate) but was unable to process the contained
instructions. For example, this error condition may occur if an XML
request body contains well-formed (i.e., syntactically correct), but
semantically erroneous, XML instructions.
IIRC request entity is the request body. So if you're operating with request bodies, it might be appropriate as Julian wrote.
You commented:
IMHO, the text for 400 speaks of malformed syntax. I would assume the syntax here relates to the syntax of HTTP string that the client sends across to the server.
That could be, but it can be anything syntactically expressed, the whole request, only some request headers, or a specific request header, the request URI etc.. 400 Is not specifically about "HTTP string syntax", it's infact the general answer to a client error:
The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents SHOULD display any included entity to the user.
The important part is here that you must tell the client what went wrong. The status code is just telling that something went wrong (in the 4xx class), but HTTP has not been specifically designed to make a missing query-info part parameter noteable as error condition. By fact, URI only knows that there is a query-info part and not what it means.
If you think 400 is too broad I suggest you pick 404 if the problem is URI related, e.g. $_GET variables.
I don't know about the RFC writers' intentions, but the status code I have seen used in the wild for that case is 400 Bad Request.
422 is a regular HTTP status code; and it is used outside WebDAV. Contrary to what others say, there's no problem with that; HTTP has a status code registry for a reason.
See http://www.iana.org/assignments/http-status-codes
Read this carefully:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
422 is a WebDAV-specific thing, and I haven't seen it used for anything else.
400, even though not intended for this particular purpose, seems to be a common choice.
404 is also a viable choice if your API is RESTful or similar (using the path part of the URI to indicate search parameters)
Description as quoted against 400
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
(Emphasis mine)
That speaks of malformed syntax, which is not the case when the browser sends a request to the server. Its just the case of missing parameters (while there's no malformed syntax).
I would suggest stick with 404 :)
(Experts correct me if I am wrong anywhere :) )
I need to answer this old question because the most upvoted and accepted answer is plain wrong.
From RFC 9110 - HTTP Semantics:
The 400 (Bad Request) status code indicates that the server cannot or
will not process the request due to something that is perceived to be
a client error (e.g., malformed request syntax, invalid request
message framing, or deceptive request routing).
So 400 is what you have to use.
Do not use 404, because you will completely mislead the API consumer. 404 means that the resource was not found on the server:
The 404 (Not Found) status code indicates that the origin server did
not find a current representation for the target resource or is not
willing to disclose that one exists.