Вопрос

I have an api endpoint that returns a Voucher object.

The voucher is retrieved from a third party.

There are some conditions, for example an expired date, that we check for / validate on.
So, if a client application requests /voucher/1234 voucher with id 1234 is retrieved from the third party.

If the expired date is < now, we need to return an error.

I want to return standard HTTP errors.

Which would be the most suitable?
I initially thought a 412 would be, but now I'm not sure.

Это было полезно?

Решение

HTTP 412 is used when the server doesn't meet one of the preconditions(If-Match, If-Modified-Since, etc) supplied in the request header.

The very generic way would be to return HTTP 400 + specific error message on invalid fields.

However more and more populer APIs are starting to use HTTP extensions to be more granular with the error feedback to the client. Twitter and GitHub use HTTP 422 Unprocessable Entity as defined in the WebDAV HTTP extension. HTTP 422 says that :

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.

Your server understands what the user wants to do and understands what the data contains, it just won't let you do that. So, Http 422 looks good for you.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top