Home

Awesome

JSend

So how does it work?

A basic JSend-compliant response is as simple as this:

{
    status : "success",
    data : {
        "post" : { "id" : 1, "title" : "A blog post", "body" : "Some useful content" }
     }
}

When setting up a JSON API, you'll have all kinds of different types of calls and responses. JSend separates responses into some basic types, and defines required and optional keys for each type:

<table> <tr><th>Type</td><th>Description</th><th>Required Keys</th><th>Optional Keys</td></tr> <tr><td>success</td><td>All went well, and (usually) some data was returned.</td><td>status, data</td><td></td></tr> <tr><td>fail</td><td>There was a problem with the data submitted, or some pre-condition of the API call wasn't satisfied</td><td>status, data</td><td></td></tr> <tr><td>error</td><td>An error occurred in processing the request, i.e. an exception was thrown</td><td>status, message</td><td>code, data</td></tr> </table>

Example response types

Success

When an API call is successful, the JSend object is used as a simple envelope for the results, using the data key, as in the following:

GET /posts.json:

{
    status : "success",
    data : {
        "posts" : [
            { "id" : 1, "title" : "A blog post", "body" : "Some useful content" },
            { "id" : 2, "title" : "Another blog post", "body" : "More content" },
        ]
     }
}

GET /posts/2.json:

{
    status : "success",
    data : { "post" : { "id" : 2, "title" : "Another blog post", "body" : "More content" }}
}

DELETE /posts/2.json:

{
    status : "success",
    data : null
}

Required keys:

Fail

When an API call is rejected due to invalid data or call conditions, the JSend object's data key contains an object explaining what went wrong, typically a hash of validation errors. For example:

POST /posts.json (with data body: "Trying to creating a blog post"):

{
    "status" : "fail",
    "data" : { "title" : "A title is required" }
}

Required keys:

Error

When an API call fails due to an error on the server. For example:

GET /posts.json:

{
    "status" : "error",
    "message" : "Unable to communicate with database"
}

Required keys:

Optional keys:

Whither HTTP?

But wait, you ask, doesn't HTTP already provide a way to communicate response statuses? Why yes, astute reader, it does. So how does the notion of indicating response status in the message body fit within the context of HTTP? Two things:

So where does that leave us? Accounting for deficiencies in the status quo does not negate the usefulness of HTTP compliance. Therefore it is advised that server-side developers use both: provide a JSend response body, and whatever HTTP header(s) are most appropriate to the corresponding body.

License

The JSend specification (this page) is covered under a modified BSD License