Giter VIP home page Giter VIP logo

jsend's Introduction

JSend

  • What? - Put simply, JSend is a specification that lays down some rules for how JSON responses from web servers should be formatted. JSend focuses on application-level (as opposed to protocol- or transport-level) messaging which makes it ideal for use in REST-style applications and APIs.
  • Why? - There are lots of web services out there providing JSON data, and each has its own way of formatting responses. Also, developers writing for JavaScript? front-ends continually re-invent the wheel on communicating data from their servers. While there are many common patterns for structuring this data, there is no consistency in things like naming or types of responses. Also, this helps promote happiness and unity between backend developers and frontend designers, as everyone can come to expect a common approach to interacting with one another.
  • Hold on now, aren't there already specs for this kind of thing? - Well... no. While there are a few handy specifications for dealing with JSON data, most notably Douglas Crockford's JSONRequest proposal, there's nothing to address the problems of general application-level messaging. More on this later.
  • (Why) Should I care? - If you're a library or framework developer, this gives you a consistent format which your users are more likely to already be familiar with, which means they'll already know how to consume and interact with your code. If you're a web app developer, you won't have to think about how to structure the JSON data in your application, and you'll have existing reference implementations to get you up and running quickly.

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:

TypeDescriptionRequired KeysOptional Keys
successAll went well, and (usually) some data was returned.status, data
failThere was a problem with the data submitted, or some pre-condition of the API call wasn't satisfiedstatus, data
errorAn error occurred in processing the request, i.e. an exception was thrownstatus, messagecode, data

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:

  • status: Should always be set to "success".
  • data: Acts as the wrapper for any data returned by the API call. If the call returns no data (as in the last example), data should be set to null.

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:

  • status: Should always be set to "fail".
  • data: Again, provides the wrapper for the details of why the request failed. If the reasons for failure correspond to POST values, the response object's keys SHOULD correspond to those POST values.

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:

  • status: Should always be set to "error".
  • message: A meaningful, end-user-readable (or at the least log-worthy) message, explaining what went wrong.

Optional keys:

  • code: A numeric code corresponding to the error, if applicable
  • data: A generic container for any other information about the error, i.e. the conditions that caused the error, stack traces, etc.

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:

  • The official HTTP spec has 41+ status codes, and there are many interpretations on how to use each one. JSend, on the other hand, defines a more constrained set of status codes, specifically related to handling JSON traffic in the context of a dynamic web UI.
  • The spec is meant to be as small, constrained, and generally-applicable as possible. As such, it has to be somewhat self-contained. A common pattern for implementing JSON services is to load a JavaScript file which passes a JSON block into a user-specified callback. JSON-over-XHR handling in many JavaScript frameworks follows similar patterns. As such, the end-user (developer) never has a chance to access the HTTP response itself.

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

jsend's People

Contributors

xzilla avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsend's Issues

Does the standard define 'data' as a JSON object?

One thing that is not immediately clear from the specification is whether the 'data' key of the response should always be either a JSON object or a null, or whether it can be any valid JSON value. Indeed, the examples only show these two options, but other possibilities are not explicitly ruled out.
An example of a different format:

{
    "status": "success",
    "data": "Some string value"
}

If an endpoint specifically returns a single value of a primitive type, I am wondering if packaging that in an additional JSON object would be a bit superfluous?

important

https://www.quora.com/What-are-the-things-which-are-banned-in-other-countries-except-in-India

Media will never inform you??
Nestle company accepts that they add juice extracted from Beef in chocolate Kitkat.


Media never informed you ???
That in a case in Chennai high court Fair & Lovely company accepted that the cream contains the oil from Pig fats !!


media never informed us that Vicks is banned in how many countries of Europe ! There it has been declared as slow poison ! But in our country we see it's advertising on TV whole day !!


media never informed us that Life bouy is neither bath soap nor toilet soap ! But it's
a Cabolic soap used for bathing animals !
Europe uses Life bouy for Dogs ! And in our country millions of humans use it !!


media never informed us ! ???????????
That Coke, Pepsi is in reality toilet cleaner ! it has been proved that it contains 21 types of different poisons ! And it's sale is banned in the canteen of indian parliament ! But it is sold in whole country !!


media never informed us ????
That foreign companies selling health tonics like Boost
Complan
Horlics
Maltova
Protin-ex., were tested in Delhi at All India Institute (which houses biggest laboratory in india) and it was found that it is made from the waste left after oil is extracted from Groundnut ! Which is food for animals ! From this waste they make health tonic !!


media never informed us ??????
When Amitabh Bachhan was operated in hospital for 10 long hours !
Doctor had to cut and remove large intestine !! and doctor had told him that it has rotten due to drinking of soft drinks like Coke, Pepsi ! And then he stopped advertising coke
pepsi !


Media is faithful to the advertisers.

Lots of people enjoy Pizzas today.
Let's have a look over pizza companies
"Pizza Hut
Dominos
KFC
McDonalds
Pizza Corner
Papa John’s Pizza
California Pizza Kitchen
Sal’s Pizza"
These are all american companies,
Note:- to make Pizza tasty...
E-631 flavor Enhancer is added which is made from Pork or Pig meat.
● Attention friends if following codes are mentioned on food packs then you should know what you are unknowingly consuming.
E 322 - Beef
E 422 - Alcohol
E 442 - Alcohol & Chemical
E 471 - Beef & Alcohol
E 476 - Alcohol
E 481 - mixture of Beef and Pork
E 627 - Dangerous Chemical
E 472 - mixture of Beef, meat & Pork
E 631 - Oil extracted from Pig fats.
● Note - you will find these codes mostly in products of foreign companies like :- Chips , Biscuits , Chewing Gums, Toffees, Kurkure and Maggi !
● Don't ignore pay your kind attention atleast for the well being of your kids, if in doubt then search by yourself through your sources if not internet. (Google)
● Look at ingredient on Maggi pack, you will find flavor (E-635 ).
● Also look for following codes on Google :-
E100, E110, E120, E140, E141, E153, E210, E213, E214, E216, E234, E252, E270, E280, E325, E326, E327, E334, E335, E336, E337, E422, E430, E431, E432, E433, E434, E435, E436, E440, E470, E471, E472, E473, E474, E475, E476, E477, E478, E481, E482, E483, E491, E492, E493, E494, E495, E542, E570, E572, E631, E635, E904.

Is HTTP 404 (not found) fail or error?

We are finding it difficult to agree on the correct jsend status for an HTTP 404 response. Could the spec clarify this somewhat special case?

Two schools of thought here.

  • It's the client's fault, so it's fail, with data set to something like {"message": "Route not found"}.
  • The client can't change the request params and try again.

I've taken a look at some implementations, and there seems to be some consensus for HTTP 404 being error. However, my reading of the spec is that it should be fail.

Reusing the data is a problem for typing

I love this, and will use it 'til retirement. I would like to propose a little mod to play better with typing. I would like to replace data with sData and fData, such that I can strongly type the payloads, both sending and receiving.

How do you handle multilanguage apps?

For example, I have this fail response, but the frontend is a multilanguage app.

{
    "status" : "fail",
    "data" : { "username" : "Username already exists" }
}

Should I specify the language on a header and handle it on the backend? I thought that maybe could be a good idea to add a code in a nested object like this

{
    "status" : "fail",
    "data" : {
		"username" : {
			"message": "Username already exists",
			"code": "usernameExists"
    	}
	 }
}

And the frontend should have a dictionary with "userAlreadyExists" to manage multilanguage error messages.

Feature Request: log

Thankyou for this helpful spec. I would like to request an addition to the spec - an optional key "log" which would be a list of log data generated during any given transaction.

For example:

{
    status : "success",
    data : {
        "posts" : [
            { "id" : 1, "title" : "A blog post", "body" : "Some useful content" }
        ]
     },
    log: [
        "New post created",
        "Editor notified"
    ]
}

I don't think it is needed to specify what the type of itmes in the log key are. For example they could be dictionaries.

{
    status : "success",
    log: [
        {"level": "DEBUG", "message": "Workflow state changed to published"}
    ]
}

Motivation: Particularly in admin interfaces it is helpful to have more detail on actions taken. For example an application could detect that a user is a system admin and generate more information in the return objects.

Using message with "fail"

I think that message attribute could also be a part of fail just as it is with error.

As you describe it, FAIL is:

There was a problem with the data submitted, or some pre-condition of the API call wasn't satisfied

So in case of the former, the "problem with the data submitted" current structure makes perfect sense.
However for "some pre-condition of the API call wasn't satisfied" it does not quite work, and a "message" describing the problem seems to be much more logical. Because this pre-condition may not depend on what data user submitted, but on other conditions outside of it. For example maybe this request only works on certain days of the week?

It also allows to handle both fail and error responses in the same way, by showing an error or warning and message response from the server.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.