views:

192

answers:

3

I'm implementing a Web service that returns a JSON-encoded payload. If the service call fails -- say, due to invalid parameters -- a JSON-encoded error is returned. I'm unsure, however, what HTTP status code should be returned in that situation.

On one hand, it seems like HTTP status codes are for HTTP: even though an application error is being returned, the HTTP transfer itself was successful, suggesting a 200 OK response.

On the other hand, a RESTful approach would seem to suggest that if the caller is attempting to post to a resource, and the JSON parameters of the request are invalid somehow, that a 400 Bad Request is appropriate.

I'm using Prototype on the client side, which has a nice mechanism for automatically dispatching to different callbacks based on HTTP status code (onSuccess and onFailure), so I'm tempted to use status codes to indicate service success or failure, but I'd be interested to hear if anyone has opinions or experience with common practice in this matter.

Thanks!

+2  A: 

You should definitely use the proper status codes since they are exactly for this purpose, not to indicate the status of the HTTP request itself. By this way you can redirect the response to the appropriate function/branch before parsing it which will lead to a much tidier code in the client side.

BYK
+4  A: 

http status code are just for indicating the status of the application response. and as you said, if json parameters as somehow invalid, a 400 status code is an appropriate answer.

so yes, it is a really good idea to use http status code. de plus, status code are then easy to understand as they don't change from an application (web services) to another

mathroc
A: 

Although HTTP itself is on the application layer in the traditional network-stack sense, I would consider a JSON payload a level above HTTP conceptually. I think it's best to keep your error methods local to the source of the error itself. So, if a request comes in with an issue in the JSON, return a 200 OK response, containing an error message in the JSON payload.

This method will be easier for others to maintain. If I saw a 400 Bad Request in the header, my first instinct would be to check for problems in the HTTP layer - probably not what you want if you are using these codes to indicate JSON-level errors.

Additionally, you don't really have too much expressiveness with HTTP code errors - you would likely need to create a fairly descriptive error structure in the JSON itself anyway. There's little to be gained by having HTTP-level errors indicate problems with HTTP itself or your JSON application-level errors (or even both).

tehblanx