1

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?

1
  • place your code, which technique or library are you using for server communivation?.t Commented Jul 10, 2015 at 5:30

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

And what about always return HTTP status of 200, but use API status to represent corresponding error? I see many company do that.
I gave you an example for that. If your server encounters a sever error, say out of memory, or the above, you should throw 500, Ann in the json reply, you can still add an error message, telling the client something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.