What is the appropriate HTTP status code response

2019-01-10 10:20发布

I'm creating a RESTful API that will process a number of user interactions, including placing orders using stored credit cards.

In the case of a successful order, I'm returning a 200 OK, and in the case where the order request is malformed or invalid I'm returning a 400 Bad Request. But what should I return if there is a problem during the actual processing of the order?

  1. Client POSTS order to server for a user resource. If user does not exist, 404 Not Found is returned.
  2. Order format and information is validated. If not valid, 400 Bad Request is returned.
  3. Order is processed. If the order is successful, a 201 Created is returned for the order. If an unexpected error is encountered, a 500 Server Error is returned.

The last step is the problem - what do I return if the order doesn't complete for any other reason? Possible scenarios could include:

  • Product is sold out
  • User maximum order limit reached
  • Credit card transaction failure (insufficient funds, etc.)

This doesn't seem like it would be appropriate for either a 400 or 500. If anything I could see it as a 400 if there's no better code - the request was invalid according to the business rules. It just doesn't seem accurate.

Edit: Also found this existing discussion of the same topic. All of the answers there seem to point to using status codes for this type of violation, with some discussion between using 400, 409, or the 422 extension.

7条回答
不美不萌又怎样
2楼-- · 2019-01-10 11:05

You should use 4xx for a client error if the client can modify the request to get around the error. Use a 5xx for a server error that the client can't really work around.

Product sold out would be a server error. The client can't modify the request in some fashion to get around the error. You could switch to another product but wouldn't that be a new request?

User maximum order limit reached is also a server error. Nothing the client can do to work around that error.

Credit card transaction failure would be a client error. The client could resubmit the request with a different payment method or credit card number to work around the error.

查看更多
登录 后发表回答