ChatGPT解决这个技术问题 Extra ChatGPT

What HTTP status response code should I use if the request is missing a required parameter?

I am thinking 412 (Precondition Failed) but there may be a better standard?

412 is definitely wrong

D
David Ongaro

Status 422 seems most appropiate based on the spec.

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.

They state that malformed xml is an example of bad syntax (calling for a 400). A malformed query string seems analogous to this, so 400 doesn't seem appropriate for a well-formed query-string which is missing a param.

Note: Since the above RFC is about WebDAV there can be a misunderstanding that 422 and some others are only to be used in the context of WebDAV and using them outside of it is "nonstandard". But this only means these status codes were introduced in the context of this RFC. Indeed the wording of these definitions is carefully chosen not to be specific to WebDAV.


IMO I would use this for when the value in the query string was incorrect, not when there was an extra value or a missing value. ie. Expecting an e-mail and its value is '123123'
I tend to think of a GET and POST parameters as the method signature of the URL path, so 404 makes sense to me. In a RESTful API meant for public consumption it is prudent to return the missing/extra parameters. In the context of a URL the query string parameters are usually important for identifying a resource and extra or missing parameters represent a resource that does not exist, without any assumptions. Of course, there are trade offs with robustness by being explicit, and optional parameters make a resource potentially just as vulnerable to silent error. Then there's usability...
The spec referenced is for WebDAV, and is not the HTTP standard spec.
@DavidV You're correct that it's for WebDAV, but there doesn't seem to be a better option for core HTTP. This blog mentions popular APIs using 422.
This is worth a read: bennadel.com/blog/… I would not use 422 for missing param either. I think 400 is more appropriate.
C
Community

I'm not sure there's a set standard, but I would have used 400 Bad Request, which the latest HTTP spec (from 2014) documents as follows:

6.5.1. 400 Bad Request 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 Bad Request is meant to indicate protocol-level problems, not semantic errors. If we're going to hijack HTTP status codes to indicate application-level (rather than protocol-level) errors, why not go all the way and just use 412?
Google's OAuth 1.0 implementation agrees with this answer. A 400 response is given when POST parameters are missing or unsupported: code.google.com/apis/accounts/docs/OAuth_ref.html
@matt-zukowski: "412: The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server." from RFC2616 - If it's a POST, the parameters are in the request body and not the request-header-fields. Technically, the GET method sends it's parameters in the request-headers but I'd rather have some consistency instead ?
@MattZukowski 400 is an application level status code. If you look at the rewording in the draft version of RFC 7231 you will see that. Unfortunately, the wording in the latest version is not so clear because the author of the latest changes also invented 422.
@DarrelMiller is right (direct link): "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)." Depending on semantics and extensibility expectations (will it one day be possible to issue a request without the parameter?) then only 400 and 404 seem appropriate in standard HTTP. Else, invent a new code for your API, but don't overload semantics.
C
Community

The WCF API in .NET handles missing parameters by returning an HTTP 404 "Endpoint Not Found" error, when using the webHttpBinding.

The 404 Not Found can make sense if you consider your web service method name together with its parameter signature. That is, if you expose a web service method LoginUser(string, string) and you request LoginUser(string), the latter is not found.

Basically this would mean that the web service method you are calling, together with the parameter signature you specified, cannot be found.

10.4.5 404 Not Found The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent.

The 400 Bad Request, as Gert suggested, remains a valid response code, but I think it is normally used to indicate lower-level problems. It could easily be interpreted as a malformed HTTP request, maybe missing or invalid HTTP headers, or similar.

10.4.1 400 Bad Request The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.


This is what CherryPy does by default.
What about when handling a post request where you're accepting a model and part of the model is missing? In that case you don't get a 404. Instead you get a model that's not valid if I'm not mistaken and you have to decide what to do now.
This interpretation seems like a stretch, and expresses an RPC rather than a REST pov. The URI is the identifier, and it exists and has been found. What is sent in the body is not part of the resource identifier. 422 is more appropriate.
404 is the right answer, just go edit some urls on the web to find the consensus!
B
BoltClock

You can send a 400 Bad Request code. It's one of the more general-purpose 4xx status codes, so you can use it to mean what you intend: the client is sending a request that's missing information/parameters that your application requires in order to process it correctly.


E
Elad Meidar

I Usually go for 422 (Unprocessable entity) if something in the required parameters didn't match what the API endpoint required (like a too short password) but for a missing parameter i would go for 406 (Unacceptable).


Well, 406 Unacceptable is used with Accept header (if server can't send response the client will understand). "The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request." . I'm stuck with 422 as there is no "right" choice with current specification :-/
Using 406 for this is wrong. A 406 code doesn't mean that the request was not acceptable; it means that you can't satisfy the request because the responses you're able to serve are ones that the client would find unacceptable, based on the Accept headers it sent in the request. (For instance, the request included Accept-Language: de, indicating it will only accept responses in German, but the only versions of the requested document that your server has available are in English or French.) Using it to indicate a missing parameter in the request is incorrect, per the definition in spec.
g
gabrielem

In one of our API project we decide to set a 409 Status to some request, when we can't full fill it at 100% because of missing parameter.

HTTP Status Code "409 Conflict" was for us a good try because it's definition require to include enough information for the user to recognize the source of the conflict.

Reference: w3.org/Protocols/

So among other response like 400 or 404 we chose 409 to enforce the need for looking over some notes in the request helpful to set up a new and right request.

Any way our case it was particular because we need to send out some data eve if the request was not completely correct, and we need to enforce the client to look at the message and understand what was wrong in the request.

In general if we have only some missing parameter we go for a 400 and an array of missing parameter. But when we need to send some more information, like a particular case message and we want to be more sure the client will take care of it we send a 409


This is plain wrong. 409 is for concurrency issues as @MaximeGélinas points out OR situations where a resource is already present and duplicates are not allowed.
Per spec, "The 409 (Conflict) status code indicates that the request could not be completed due to a conflict with the current state of the target resource.". Using it for a missing parameter is just wrong; that's a totally different sort of error.
N
Neromancer

For those interested, Spring MVC (3.x at least) returns a 400 in this case, which seems wrong to me.

I tested several Google URLs (accounts.google.com) and removed required parameters, and they generally return a 404 in this case.

I would copy Google.


Because Google does it does not automatically mean Google does it right!
I agree, not necessarily 'right' but sometimes what's right and what's sensible are two different things. Anyhow.. up to the reader :)
Some Google APIs return a 400, e.g. github.com/google/google-api-nodejs-client/issues/404
which is wrong (and why spring mvc is not jax-rs compliant)
L
Luca

It could be argued that a 404 Not Found should be used since the resource specified could not be found.


This is the default behavior of Java JAX-RS when a query parameter cannot be converted to the proper datatype. I don't agree with it though. The resource WAS found: query parameters are for filtering the resource and one of the filters was supplied with an unacceptable value. I think this matches 422 Unprocessable Entity closest, and 400 Bad Request second closest.
its the default behaviour of jax-rs because its the right behaviour!
Using a 404 is reasonable when the query string parameter is meant to identify a resource, a value was given, but that value doesn't correspond to a resource that exists - for instance, if you're requesting example.com/show-user-profile?user_id=123 and user 123 doesn't exist. But that's not what this question asked about; it was about the scenario where a required parameter is omitted entirely. I don't see how that corresponds to a specified resource not being found.
C
Community

I often use a 403 Forbidden error. The reasoning is that the request was understood, but I'm not going to do as asked (because things are wrong). The response entity explains what is wrong, so if the response is an HTML page, the error messages are in the page. If it's a JSON or XML response, the error information is in there.

From rfc2616:

10.4.4 403 Forbidden The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.


Sounds good initially, although I'd naturally associate this with authentication or permission based errors. Also, the spec hints towards this where it says "if the server does not wish to make this information available to the client". Also that 404 might be a better option. I'd head towards a 404 or 400 than a 403.
This is a terrible idea, even if technically sound. 403 is universally used for auth failure responses, and you will confuse the hell out of your clients if you try to use this to indicate parameter errors. For example Twitter does this — 403 is used both when you provide invalid OAuth credentials, and when there is something semantically wrong with your request — and it is a constant source of confusion for API clients.
@MattZukowski well that's just wrong. The spec says Authorization will not help, so Twitter should not send this for invalid OAuth credentials.
@torvin Twitter should be sending a 401 Unauthorized instead. However, you can understand why they don't if you look at the MDN docs' descriptions of these two codes, which are very similar.
You should describe the reason of failure in your response. If you prefer not to do it, just use 404.