I have a custom implementation of a RESTful API for a PHP application that returns json data, and in order to communicate the status of the operation, ie whether there were failures in the request, I'm setting a custom HTTP Header with a (very tiny) json object as a string. This works well since I can send responses and easily retrieve them client side without messing with the actual data sent.
The question is, are there any drawbacks I may not have realized of using this method? It doesn't seem to be very common for applications to set custom http headers, so I'm wondering whether it is a bad practice or bad "taste" somehow.
This is an interesting question. There shouldn't be any reason for it to be a problem, but you should take a few things into account:
X-MyApplication-Foo: Bar
. Not doing this might cause conflicts in future.Is there are reason you can't use the standard HTTP error codes? I understand that you might want to provide stack traces or other useful debugging information, but in the case of an error, wouldn't you just return a JSON blob that contains the error information, rather than the normal "result" JSON data? You could easily detect the difference based on the HTTP error code and handle the two cases differently.
The reason I'm concerned by your suggested approach is that headers are used to alter or cause browser behaviour - they're not intended to be a data storage mechanism.
Pseudo-code example:
switch(httpResponseCode)
{
case 200:
parseResult(json);
break;
case 403:
parseForbidden(json);
break;
case 500:
parseServerError(json);
break;
default:
// bad response code, handle appropriately
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With