апите код состояния для запроса поста, который не смог


April 2019


21 раз


У меня есть апи вызов пост, который в настоящее время создает встречу в моей системе бронирования.

Если вызов апи отправляет запрос на назначение и апите может успешно создать appoinment API-интерфейс возвращает 201, созданный код статуса.

В настоящее время, если запрос на назначение не не создается (из-за различные вещи, такие как время, больше не доступно или в комнате в настоящее время используется) API-интерфейс возвращает код статуса 400 Неверного запроса.

«400 Bad Request ответ код состояния указывает на то, что сервер не может или не обработать запрос из-за чего-то, что воспринимается как ошибка клиента»

Данные, посылаемые не недопустимый синтаксис и потенциально может быть повторно и быть успешным.

Есть ли более соответствующий код состояния для этой неудачи, чтобы создать ресурс. будет 422 Unprocessable Entity быть правильным ответом в данном случае?

3 ответы


[... ]if the appointment request is not created (due to various things such as the time is no longer available or the room is now being used) [...]

The 409 status code could be used for this purpose:

6.5.8. 409 Conflict

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. This code is used in situations where the user might be able to resolve the conflict and resubmit the request. The server SHOULD generate a payload that includes enough information for a user to recognize the source of the conflict. [...]

You could use both: In general, use 400 to indicate syntax errors in the payload or invalid parameters in the URL. And use 422 to indicate semantic problems in the payload.

See how each status code is defined:

6.5.1. 400 Bad Request

The 400 (Bad Request) status code indicates that the server cannot 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).

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.

Also consider the status codes returned by the well-known GitHub API v3 API:

There are three possible types of client errors on API calls that receive request bodies:

  1. Sending invalid JSON will result in a 400 Bad Request response. [...]

  2. Sending the wrong type of JSON values will result in a 400 Bad Request response. [...]

  3. Sending invalid fields will result in a 422 Unprocessable Entity response. [...]

Michael Kropat put together a set of diagrams that's pretty insightful when it comes to picking the most suitable status code. See the following diagram for 4xx status codes:

Picking the right 4xx status code


If you are looking for retry ability, then the 4xx range is typically permanent and should not be retried. The 5xx range also doesn't seem appropriate. 503 almost works but that indicates the request will work in the future, which it might not.

However, 409 could suit this use-case(and my personal preference): "The request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request." Typically used in PUT but could work in this scenario. For example, they could change the proposed time in the request. Or they could retry later if the room becomes available.

422 could also work to indicate a field level error.

Either way, an important thing is to accompany it with a good error message indicating the issue. From rfc7231:

the server SHOULD send a representation 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.


If the error is due to something going wrong on the server and to no fault of the client you can use the 5xx range (Server Error). 4xx errors are reserved for errors caused by the client. Most often 500 Internal Server Error is used in this case.


  • Clients fault --> 4xx

  • Servers fault --> 5xx