Is returning HTTP 409 appropriate for a validation check?

后端 未结 5 1166
-上瘾入骨i
-上瘾入骨i 2020-12-17 19:06

I have a service where some validation rules must be checked before a particular operation should be able to take place.

For instance, the client should not generate

5条回答
  •  生来不讨喜
    2020-12-17 19:52

    As is often the case it's hard to advise precisely without knowing exactly what you are doing, how, and why etc. For example:

    I have a service where some validation rules must be checked before a particular operation should be able to take place.

    Is this service serving local code? If so you should throw an exception to local code or return something normal.
    Is it tied to an API request? If so on face value I can't see why you'd validate on a separate REST call rather than doing it all in one request.

    However, an individual client may not have all of the required information (that user may only be able to access a subset of the data that is used to determine validation success), so a request must be sent to the server: basically "is a thing valid between start and finish".

    I'm making assumptions for example's sake, but eg you can just let them make the request which they would if they had all the necessary data etc, and validate at that point.

    The response will either be some sort of token that indicates VALID: FEEL FREE TO CONTINUE, or a list of validation failure reasons, that can be presented to the user.

    This is why I'm suggesting what I have, as your above reads like the requirement is:

    1. Send request to API, API performs Validation and returns a response;
    2. If response shows valid then user sends the next response to do the actual thing;
    3. If response shows invalid then user has to do something and retry until they get a valid response then they still have to do the actual thing;

    Alternative:

    1. Send request to API, perform validation, if valid do the thing, else return response indicating invalid state;
    2. User makes changes and again just has one request to send to do validation and the actual thing;

    Note: the action performed is not being performed on the server, so skipping this check, and just attempting the action, with a 403 in the case of the action being forbidden is not an option.

    If this isn't any kind pf remote/API request then I would suggest not using HTTP codes. Is this just all done within the same codebase? If so exceptions or bools etc from your validation to serve a message to the user.

提交回复
热议问题