Http response exceptions format - json

Does anyone know what is the best format to return an HTTP response error to the client when facing an exception? A format to handle the error in a dynamic way and the easiest way to catch the exception between server and client
i suggested the following, but i need to get the best format for the error response:
{
"FLAG": "ERROR",
"TEXTEN": "SERVER ERROR – BAD REQUEST"
}

One good solution would be to send back the error code in the answer's headers, using the standardized HTTP codes from the HTTP protocol.
You can also add you own error code and a corresponding human readable message in the JSON body to provide more informations on the encountered error.
For example, for a Bad Request error, the corresponding HTTP code is 400. So you should send back the HTTP code 400 in the response header and the corresponding HTTP message (Bad Request). But some programming languages does not offer out of the box features to read the message. To be sure that the user can read it properly, you can also put it in the JSON body if you want.

Related

API POST response returning 400 response code in Jmeter

I am trying to create a test plan using jmeter.its for an API Post request, I have a header manager, bodydata, checked for spellings and the syntax seems to be correct. However, Im getting 400 response code with the following error shown in the attached image. Anyone with an idea how I can resolve this? Thank you. the error
Here is the request the request
The user doesn't have to be logged in, i have added a header manager, I have also noticed there header has a cookie value thats hard coded but it appears to be the same in every request. In the UI the API request returns 200 and thats what im expecting with the Jmeter script.
In its current form the question cannot be answered comprehensively.
HTTP Status Code 400 means that
The 400 (Bad Request) status code indicates that the server cannot or
will not process the request due to something that is perceived to be
a client error (e.g., malformed request syntax, invalid request
message framing, or deceptive request routing).
Check that your ${site} and ${csVersion} variables have their respective values using Debug Sampler and View Results Tree listener combination
Cross check headers sent by JMeter and by the "UI", the most important is Content-Type
Use a sniffer tool like Wireshark of Fiddler and capture the requests which are being sent by JMeter and the "UI", the requests must be exactly the same apart from dynamic parameters which need to be correlated
The issues was being caused by an anti-forgery cookie which was hard coded in the request.I used a regex to extract the value from a previous request and used a variable value from the regex to make sure the same value is being passed on to the request that was failing.

API endpoint returns text before and after the JSON content, causing parsing error

I'm using postman to test calling a rest service endpoint.
I'm trying to parse the JSON return content but it throws an error because the response body has more than just JSON.
This is how I parse it in my postman test script:
var jsonData = JSON.parse(responseBody);
Here is the response body:
--13398550-b6ea-4731-a8ee-4b2ad24c3cfe
Content-Type: application/json; charset=utf-8
//this is the actual content I want to parse --->
{"id":"123456","value":"the_value"}
--13398550-b6ea-4731-a8ee-4b2ad24c3cfe--
When I try to parse it, I get the following error (in postman)
There was an error in evaluating the test script: SyntaxError:
Unexpected number in JSON at position 3
Obviously because the content being parsed is not just JSON
Is this something special that the api is doing? Or am I just parsing it incorrectly?
NOTE: I'm not including details of the rest service function. If the cause of this issue is something that is being done by the service itself, then that is enough of an answer for me to perhaps ask another question or do some further investigation. The purpose of this question is to ask whether this is something special being done in HTTP, or if it's the service.
Edit:
I managed to see the server side code and it is indeed manually building the response with boundaries identified by a GUID. I'll have to manually parse the response
The server is not emitting straight up application/json, it's packed in a multipart mime envelope.
Whether or not it's doing that correctly depends on the response headers. If you didn't expect a multipart response, but a simple JSON response, then I'd say yes: it's something you need to fix server-side.

How to distinguish a deliberate, controller-generated 404 from an actual error in a REST API?

In a JSON-REST service architecture (following these patterns for methods and response codes) we often need to generate a deliberate 404 response - for example, if GET /users/123 is routed to a controller, which is then unable to find a User entity with ID 123, we return a 404 response, which in many cases will include a JSON payload with an error message/code/etc.
Now, when we provide a client for a specific API, we want the client to behave differently under different conditions. For example, if we point the client to the wrong host, we might get a 404 not found from that host - as opposed to the 404 we might get for an invalid User ID if we do reach the service.
In this case, a "404 User ID not found" is not an error, as far as the client is concerned - as opposed to any other "404 Not Found", which should cause the client to throw an exception.
My question is, how do you distinguish between these 404 errors?
Solely based on the response?
By adding a header to indicate a valid response?
Or some other way?
It is OK to return 404 in both cases. As 4xx codes are client relevant codes, it is also OK to return content even if there was an error.
Now, deciding what kind of 404 it was can be decided based on the body of the response. Remember, that the response should carry a mime-type that is compatible with the Accept header the client supplied. So if the client "knows" your specific error-describing format, your server can answer with a more detailed description.
This way both the server can decide whether the client would understand a detailed response with the 404, and the client also understands when it just got a regular 404, or one with a message it can process.
This would be both semantically correct, and compatible with HTTP.

Suggested JSON structure for Exceptions?

Out of curiosity, are there any popular standards for returning server side exceptions (and corresponding details) in an API that returns JSON? The exceptions could be anything from uncaught exceptions in the code or thrown exceptions put in place by the developer.
Currently I'm setting the HTTP Status Code according to their Wiki definitions'
My JSON response would look something like this:
HTTP Code: 401
{'error': 'Authentication required.', 'message': 'You must be authenticated to perform that action.'}
You can take a look at JSON-RPC (http://en.wikipedia.org/wiki/JSON-RPC).
In case of success, the response is like this:
{
"result": ...(returned data)...
...
}
and in case of error, the response is like that:
{
"error": ...(error details)...
...
}
When the error occured, "error" property must be present and "result" property must not be returned. In case there was no error, "error" property must not be set. This way you can distinguish errors from successful responses based solely on the content of the response, without the need to check the headers (like response codes).
The standard structure of native ECMAScript error objects is:
{
name: ...,
message: ...
}
where "name" is the type of the error (the name of the corresponding constructor, like "Error", "SyntaxError", etc.). In your example, you could use the name "AuthentificationError", for instance.
Yes you can do the same.
As we know that Web servers allow us to create custom error pages for HTTP errors, in those custom error pages you have to serve the JSON reply
Example:
Add the following to your WEB-INF/web.xml:
<error-page>
<error-code>401</error-code>
<location>/autherror.jsp</location>
</error-page>
In the autherror.jsp file code the required logic to accomplish your needed JSON reply.
Try being a bit more verbose regarding the error you are sending. This structure has been suggested in some places to give sufficient information both for users and developer using your API
"error":{
"code":"410",
"long":"410001",
"message":"cannot connect to DB",
"developer":"Connection to the DB was unsuccessful due to ...",
"documentation": "mysite.com/help/errors/..."
}
Return the correct HTTP code for error. It is bad practice to return code 200 with error.
Extend the code with your own error IDs
Provide short message that roughly outlines the cause of the error. Consider adding more detailed message for the developers. Have in mind that API error messages are 99.9% of the time read by developers so make them happy by providing technical details (within reason) so that they can resolve ASAP.
In case you keep public documentation about your api and error codes, simply add the url.

How to handle REST Exceptions?

We are in the middle of a ongoing discussion about how to handle REST exceptions.
Response Content type : JSON
Two solutions we have:
Throw all the unchecked exceptions as a JSON response.
Send Request Invalid Response code.
Arguments:
When its a error, why return JSON? Just send a invalid response code.
Counter Argument:
Response code are too technical to handle for normal developers.
Whats your say??
For a JSON API I recently developed I do both. I always respond with valid JSON (well, assuming I respond at all). If I detect an invalid request, I use status 400. If I detect a server error (which I don't believe is caused by an invalid request), I use a 5xx status. The JSON object contains a special key that is only set for errors, with a string value.
I think this is a good solution that respects REST principles, and can be used in multiple ways. The same solution is used by some other JSON APIs, such as Yahoo Search. Try http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&output=json .
Use error codes like for HTTP. So 50* for any exception cause by some internal problem. And 40* for bad arguments. Avoid using your own defined codes as far as its possible. The idea is to have a "uniform" interface.
In general.
204 for success without sending any content
200 for success with a json representation of the resource
And if its not a successful operation return appropriate response code. You can choose to optionally return a json. To simplify things you can have a common format (json) for all error responses.
http://en.wikipedia.org/wiki/REST is a must read before you freeze on your api specs.