Standard JSON API response format
Several models have been proposed, but none has emerged as clear standard (e.g. JSend, JSON API, OData JSON Protocol, HAL, HATEOAS, etc…). Some models are quite simple, while others tends to be complex and over-prescribing. Amongst them the JSend format is probably the simplest one, defining only four top level fields (i.e. status, code, message and data). The simplicity of this model and its focus on application-level messaging are important features to promote adoption and reuse.
Commonly, we prefer to use JSend Model
Example
{
"success": false, // Type : boolean
"message": "Invalid email or password", // Type : String | array
"code": 1400, // application level custom status code
"data": {} // Type : Object | String | array
}
Extending the JSend model
In addition to the fields defined by JSend, the model proposed here defines new mandatory fields that are particularly useful in modern distributed environments.
Every response should be a well-formatted JSON, always including the following fields:
app
: Application name - helps to identify that the response is coming from the right application;version
: Program version - in a distributed environment the response may come from a different version of the same program;release
: Program release number - useful for debugging purposes;datetime
: Human-readable UTC date and time of when the response has been dispatched;timestamp
: Machine-readable UTC timestamp in nanoseconds since EPOCH of when the response has been dispatched;status
: Status code (i.e. success, fail or error);code
: HTTP status code or a numeric code corresponding to the error in an error result;message
: A meaningful, end-user-readable (or at the least log-worthy) message, explaining the current status (e.g. what went wrong in an error result);data
: Data payload - a generic container for data returned for success, fail or error.
If the responses are stored as logs for auditing or debugging purposes, the new additional fields provide the required what and when information.
The API service should always return the above JSON object, even in case of error or panic. This allows to use a consistent parsing method.
Examples:
HTTP Response Code : HTTP.Success (200)
{
"app": "Executor",
"version": "v1",
"release": "0.1.0",
"datetime": "2022-09-06T19:58:29Z",
"timestamp": 1475783909566791977,
"status": "success",
"code": 200,
"message": "Users list",
"data": {
"users": [
{
"id": "000000001",
"first_name": "Prayas",
"description": "check this out"
},
{
"id": "000000002",
"first_name": "Aman",
"description": "check this out"
}
]
}
}
HTTP Response Code : HTTP.Success (200)
{
"app": "Executor",
"version": "v1",
"release": "0.1.0",
"datetime": "2022-09-06T19:58:29Z",
"timestamp": 1475783909566791977,
"status": "success",
"code": 200,
"message": "Users list",
"data": {
"duration": 33.263465257,
"message": "The service is healthy"
}
}
Comments ()