سؤال

When constructing an API response, which method is better for (manually) returning the status code to indicate the validity of the request:

1 - Embed a response code within the JSON response

{
  'status_code' => 200,
  'status_message' => 'OK',
  'data' => { ... }
}

2 - Or is it better to modify the HTTP Headers Status field?

Request URL:http://somesite.com
Request Method:GET
Status Code: 200 (EDITING THIS ONE)

I would think that the HTTP Statuses should only be regarding connection errors and file retrieval errors that occur at the server level rather than altering this to address application level errors.

Any good articles and resources to read would be very appreciated as well.

هل كانت مفيدة؟

المحلول

I have found the best way to present errors in a REST Request is to change the HTTP Status Code to the proper error, and embed the error in the response.

If you are using JSON, it might look like this, with the status code set to 500 for this example:

{"error" : "An error has occurred while trying to read from the database."}

This is the same method that Microsoft CRM uses to report errors, and it has proved to be a good method; RESTFul applications will not fail to parse the response if they are expecting JSON (or XML, if you are using that).

نصائح أخرى

This question addresses the same issue (perhaps from a slightly different perspective).

I think that, in general, if a request to a resource in your application results in an error condition, that fact should be reflected in the HTTP headers. You can use the application response to provide more detailed information.

Update: Here is an interesting mapping of application errors to status codes (used by Azure).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top