简体   繁体   中英

REST API error return, include HTTP status code or not

I'm working on an restful API back end, and we only use json as content type. And There are two ways of performing error response as I know:

  1. HTTP status code is always 200, and the returning json should contain error code and error message.
  2. Treat HTTP status code as part of our API, we may pick HTTP error code(4XX) to corresponding error condition. And we can include a json document in the payload to includes a sub-code and a descriptive comment.

I want to know which one is more idiom for a restful service?

You need to use both.

  1. HTTP Status : Use this to process the status of the request. For example, if you query a DB and you find no entries, you'll still return 200. If the user is not authorized, 403, if number of SQL connections exceed, 500, and so on.

  2. API Status : If the DB request succeed and you find no entries, include a custom field in your json {status: NO_ENTRIES } or { status: DEPRECATED_API } . In these cases, the response code will still be 200.

Generally speaking, I would not advocate for always returning a 200. There are failure scenarios that match commonly accepted status codes. Above, someone mentioned 403, which you deliver when access is denied. And 500 is typically issued by the web/app server when things really go south. And 404 if either a record is not found for a resource.

So, I do advocate for:

  1. Going with at least 200, 403, 404, 500
  2. Providing as verbose error details as possible in your JSON error response
  3. Documenting every error code your API might deliver - HTTP status codes and every sub-condition error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM