Is there any standard for JSON API response format?
Yes there are a couple of standards (albeit some liberties on the definition of standard) that have emerged:
- JSON API - JSON API covers creating and updating resources as well, not just responses.
- JSend - Simple and probably what you are already doing.
- OData JSON Protocol - Very complicated.
- HAL - Like OData but aiming to be HATEOAS like.
There are also JSON API description formats:
- Swagger
- JSON Schema (used by swagger but you could use it stand alone)
- WADL in JSON
- RAML
- HAL because HATEOAS in theory is self describing.
I guess a defacto standard has not really emerged (and may never). But regardless, here is my take:
Successful request:
{
"status": "success",
"data": {
/* Application-specific data would go here. */
},
"message": null /* Or optional success message */
}
Failed request:
{
"status": "error",
"data": null, /* or optional error payload */
"message": "Error xyz has occurred"
}
Advantage: Same top-level elements in both success and error cases
Disadvantage: No error code, but if you want, you can either change the status to be a (success or failure) code, -or- you can add another top-level item named "code".
Google JSON guide
Success response return data
{
"data": {
"id": 1001,
"name": "Wing"
}
}
Error response return error
{
"error": {
"code": 404,
"message": "ID not found"
}
}
and if your client is JS, you can use if ("error" in response) {}
to check if there is an error.