904

Do standards or best practices exist for structuring JSON responses from an API? Obviously, every application's data is different, so that much I'm not concerned with, but rather the "response boilerplate", if you will. An example of what I mean:

Successful request:

{
  "success": true,
  "payload": {
    /* Application-specific data would go here. */
  }
}

Failed request:

{
  "success": false,
  "payload": {
    /* Application-specific data would go here. */
  },
  "error": {
    "code": 123,
    "message": "An error occurred!"
  }
}
Anish B.
  • 9,111
  • 3
  • 21
  • 41
FtDRbwLXw6
  • 27,774
  • 13
  • 70
  • 107
  • 25
    People probably have learnt from SOAP and won't build it again... – Denys Séguret Oct 09 '12 at 18:44
  • 27
    @dystroy: Care to explain your comment? – FtDRbwLXw6 Oct 09 '12 at 18:49
  • 4
    XML was, in my opinion, killed for programmers by an excess of normalization resulting in the bloating of API and applications, leading finally people to almost never, today, doing SOAP in the simple original few LOC way but with slow libraries, parameterization and even code building frameworks... I'm sure most designers today don't want to have the same nightmare occurring. But this is just an opinion and I don't want to soil your question with more rant-smelling comments. – Denys Séguret Oct 09 '12 at 18:52
  • 7
    I was really interested by this question as I had to design a JSON API recently and found myself wondering if they were any standards defining a response format. Yours actually looks quite nice, and looks worth using if you don't find a standard. It's a shame that the answers provided don't actually address the question. – Alex Oct 11 '12 at 21:05
  • 18
    @Alex unfortunately, that's because no matter where you go, there is *no* standard. Not only within JSON itself, but in terms of how to use it for RESTful applications, or anything else of the sort. Everybody does it differently. You can feel free to follow best-practices (HTTP-responses, meaningful package-structure, an eye towards structuring your data for consumption by your system), but ***everybody*** who is a major distributor is doing at least one thing different than the others... There is no standard, and there won't likely be one, so build something solid, and build it to fit you. – Norguard Oct 12 '12 at 02:41
  • 7
    @Norguard there are standards (see my answer). In fact [*The nice thing about standards is that you have so many to choose from.* - Andrew Tanenbaum](http://en.wikiquote.org/wiki/Andrew_S._Tanenbaum) – Adam Gent Jan 26 '13 at 16:16
  • @DenysSéguret: And yet, today, there's REST. – Michael Scheper Oct 26 '15 at 20:52
  • @MichaelScheper REST is absolutely unlike SOAP. And REST doesn't standardize JSON at all. – Denys Séguret Oct 27 '15 at 07:22
  • 1
    @DenysSéguret: Maybe I misunderstood your non-rant. The OP was asking about 'structuring JSON responses from an API'. JSON's largely replaced XML, and although I'm not sure REST standardises the responses themselves, it does standardise web APIs, in a much less nightmarish way than XML did. In projects involving many engineers, it's nice when there's a standard everyone can follow, and I wish there was one for responses. I try to write reusable client code, and while checking for HTTP 200 is easy enough, I'm often frustrated by inconsistent structures in error responses, which I'd like to log. – Michael Scheper Oct 28 '15 at 00:44
  • 6
    https://xkcd.com/927/ – prusswan Mar 14 '16 at 05:51
  • Very good question. We initially used dynamic objects in C# and quickly found it hard to know what the data was. Your presented idea actually looks like pretty good standard. – Andy Jan 11 '17 at 11:11
  • this should really move to software-engineer because this is more opinionated. – Archimedes Trajano Jan 05 '18 at 19:31
  • 1
    "Standards" mentioned in the checked answer are horrible (bloated, incomprehensible), The one that you have is the one I use as well. Maybe all of us using it should gather up and publish it as our own standard. – jayarjo Jul 01 '19 at 11:34
  • 3
    The "success" element seems a bit redundant these days. Much better to return the correct HTTP status code 2xx if success, 4xx if client request caused the error, 5xx if server caused the error. – bytedev Feb 10 '20 at 06:32
  • I think there should be a `status_code` field at the top level so the client can always look there regardless of what's happened and check for `200` for success. There should be an error *section*, I don't think error information should be packed at the top level, and the error section should probably be a *list* to allow multiple error descriptions. I think the success response data should always be in a `data` object, not packed at the top either, and there should be a `warning` section too, possibly populated for `200` responses. – NeilG Apr 26 '23 at 10:51
  • I don't see the need to define various verbage fields like `"status": "success"` when this just very poorly replicates the meaning of the `status_code` field. Client should be able to make a simple boolean assessment of success/failure from one field and `status_code == 200` is great for that and universally understood, and can still communicate a variety of nuances with all the other codes. – NeilG Apr 26 '23 at 10:54

18 Answers18

829

Yes there are a couple of standards (albeit some liberties on the definition of standard) that have emerged:

  1. JSON API - JSON API covers creating and updating resources as well, not just responses.
  2. JSend - Simple and probably what you are already doing.
  3. OData JSON Protocol - Very complicated.
  4. HAL - Like OData but aiming to be HATEOAS like.

There are also JSON API description formats:

xzilla
  • 1,142
  • 9
  • 19
Adam Gent
  • 47,843
  • 23
  • 153
  • 203
  • 27
    Thank you. JSend in particular is exactly what I was looking for. It's similar to what I was doing, but has some benefits that my method did not. In fairness to @trungly, JSend is very close to his own answer, as well. – FtDRbwLXw6 Jan 26 '13 at 20:29
  • 11
    For error responses specifically I also like the [Problem Details for HTTP APIs](http://datatracker.ietf.org/doc/draft-nottingham-http-problem/) RFC draft. – Pieter Ennes Feb 13 '14 at 12:36
  • 1
    Maybe you want to add https://code.google.com/p/json-service/ to the description format list? – emilesilvis Aug 15 '14 at 15:43
  • 1
    I think the "A recommended standard for Rails" label is a bit of an overstatement - this is just one programmer's solution. Not sure what makes it a "recommended standard" (specially if you look at the gem's popularity - doesn't look like that many people is using this at all)? I personally don't think most Rails programmers would recommend this solution because of using response body instead of HTTP headers for status – Iwo Dziechciarow Sep 04 '14 at 21:00
  • 3
    [Google JSON Style Guide](https://google.github.io/styleguide/jsoncstyleguide.xml) is also a good reference – MRodrigues Dec 16 '15 at 12:38
  • I use JSONAPI.org implementation on daily base, but I kinda like "Stormpath API" implementation more https://www.youtube.com/watch?v=hdSrT4yjS1g . – equivalent8 Mar 12 '16 at 20:19
  • I don't understand your second option (JSend). Data object has another object inside with variable (not constant) key. Does this mean I have to traverse the data, since I have no idea what the key is? It might be title, it might be username missing. Seems easier to just have data object tell the data straight, not have nested objects with variable keys. – jm18457 May 26 '18 at 04:29
298

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Steely Wing
  • 16,239
  • 8
  • 58
  • 54
  • 2
    Im not sure if you can handle this from a Server Side JSON API like PlayJson, either way it doesn't matter. @Steely your links are broken – Rhys Bradbury May 26 '16 at 10:26
  • 4
    What about errors that need to provide a list of failures (like validation problems)? – Xeoncross Dec 21 '17 at 02:08
  • 2
    @Xeoncross click the link on the word `error`, Google's page gives an example of this –  Dec 22 '17 at 19:00
  • 1
    @Xeoncross You can return a list of failures using error.errors[], defined as: "Container for any additional information regarding the error. If the service returns multiple errors, each element in the errors array represents a different error." Perhaps the top level error would mention "Request failed input validation" and the errors[] array would have one entry for each specific validation failure that occurred. – James Daily Jan 16 '19 at 20:48
  • @Steely Wing ->>> StatusCode: 304, ReasonPhrase: 'Not Modified', Version: 1.1, Content: ,Headers:{} <<<< is this a proper response of restApi ? – Arnold Brown Jul 10 '19 at 12:57
  • i wonder what's about other common field like `redirect` should be on `data` or `error`? – TomSawyer Jul 20 '19 at 14:41
  • I prefer to check the HTTP status code to check the error for the client side. – icaksama Aug 11 '22 at 07:50
187

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".

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
trungly
  • 2,041
  • 1
  • 11
  • 8
  • 4
    yes this is right way if you are using POJO for json parsing! when we are using POJOs we need static, non dynamic json format! – LOG_TAG Apr 10 '14 at 11:04
  • Simple and to the point. Better than jsend in my opinion because jsend distinguishes error from fail. – Josue Alexander Ibarra Apr 11 '14 at 22:11
  • 1
    I use this pattern too but with a field called `messages` which is an **array of messages** instead of a single string. – StockBreak May 29 '15 at 12:45
  • 5
    The answer is almost a copy of well documented [JSend](http://labs.omniti.com/labs/jsend) which is simple and very useful. They provided third status `fail` for typical validation problems, while `error` is used only with fatals like db errors. – s3m3n Jan 27 '16 at 13:44
  • 2
    for the success: if it has `200` in the headers why do you even need a `status` field? just return the data object straight. You know this can cause additional pain with typed FE languages like TypeScript. – Deniss M. Oct 08 '18 at 11:55
  • @DenissM. What's FE? – Charlie Flowers Dec 11 '18 at 19:00
  • @CharlieFlowers frontend. – Deniss M. Dec 11 '18 at 21:17
  • @JosueAlexanderIbarra I'm going with jsend. Success/Error/Fail is a much better fit with real life, where all non-successes can, and should, be categorised as "we have a problem" or "you have a problem". – bbsimonbb Jul 18 '19 at 10:07
  • @DenissM. Maybe the reason is that not all successful operations are necessary a `200` code. Like we can have a `201` when a new resource is created. – Onwuka Gideon Jul 05 '20 at 16:57
  • @OnwukaGideon how is that different? You're still getting the same 201 in headers. – Deniss M. Jul 06 '20 at 14:37
  • @DenissM. `201` is not the same as `200`, or is it? – Onwuka Gideon Jul 06 '20 at 19:38
  • @OnwukaGideon it isn't the same, but if the extent of your sophistication with reading HTTP status codes is `status === 200` then you are sort of missing the point of HTTP statuses. The browser-native `fetch` API responses include an `ok` boolean that indicates whether any non-success status was returned. You can always check for anything outside the `2XX` range using comparison operators. Swagger/OpenAPI recommends using status codes to report errors: https://swagger.io/blog/api-design/api-design-best-practices/#responses – Jon Hieb Dec 06 '20 at 01:23
110

Assuming you question is about REST webservices design and more precisely concerning success/error.

I think there are 3 different types of design.

  1. Use only HTTP Status code to indicate if there was an error and try to limit yourself to the standard ones (usually it should suffice).

    • Pros: It is a standard independent of your api.
    • Cons: Less information on what really happened.
  2. Use HTTP Status + json body (even if it is an error). Define a uniform structure for errors (ex: code, message, reason, type, etc) and use it for errors, if it is a success then just return the expected json response.

    • Pros: Still standard as you use the existing HTTP status codes and you return a json describing the error (you provide more information on what happened).
    • Cons: The output json will vary depending if it is a error or success.
  3. Forget the http status (ex: always status 200), always use json and add at the root of the response a boolean responseValid and a error object (code,message,etc) that will be populated if it is an error otherwise the other fields (success) are populated.

    • Pros: The client deals only with the body of the response that is a json string and ignores the status(?).

    • Cons: The less standard.

It's up to you to choose :)

Depending on the API I would choose 2 or 3 (I prefer 2 for json rest apis). Another thing I have experienced in designing REST Api is the importance of documentation for each resource (url): the parameters, the body, the response, the headers etc + examples.

I would also recommend you to use jersey (jax-rs implementation) + genson (java/json databinding library). You only have to drop genson + jersey in your classpath and json is automatically supported.

EDIT:

  • Solution 2 is the hardest to implement but the advantage is that you can nicely handle exceptions and not only business errors, initial effort is more important but you win on the long term.

  • Solution 3 is the easy to implement on both, server side and client but it's not so nice as you will have to encapsulate the objects you want to return in a response object containing also the responseValid + error.

eugen
  • 5,856
  • 2
  • 29
  • 26
  • 2
    You say that I should "Define a uniform structure for errors" and other similar suggestions, but this is precisely what I'm asking about. I guess the answer is turning out to be that "no, there is no standard or best practices with regards to this structure." – FtDRbwLXw6 Oct 09 '12 at 21:31
  • 8
    For the record: the HTTP status code is not a header. – pepkin88 Mar 25 '15 at 14:56
  • 3
    "the response will not be json but html." wrong! html has nothing to do with error handling. the response can be whatever content-type you support. – oligofren Oct 08 '15 at 10:47
  • @pepkin88, what is it then? – Incerteza Apr 14 '17 at 21:48
  • 2
    @アレックス HTTP status code is a 3-digit code in the status line of the header of an HTTP response. Following that line are header fields, colloquially also called headers. – pepkin88 Apr 15 '17 at 20:08
  • @pepkin88, what's the status line of the http header? which http header? – Incerteza Apr 16 '17 at 01:13
  • 1
    @アレックス The Wikipedia page on HTTP nicely answers your questions, you can check it there: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Response_message (link to the section Response message) – pepkin88 Apr 16 '17 at 17:37
37

The RFC 7807: Problem Details for HTTP APIs is at the moment the closest thing we have to an official standard.

Berislav Lopac
  • 16,656
  • 6
  • 71
  • 80
  • 1
    3 years later... seems to be the direction to go. See also:https://youtu.be/vcjj5pT0bSQ?t=611 (Visual Studio .Net core Support for 7807) – edelwater Apr 21 '19 at 21:49
28

Following is the json format instagram is using

{
    "meta": {
         "error_type": "OAuthException",
         "code": 400,
         "error_message": "..."
    }
    "data": {
         ...
    },
    "pagination": {
         "next_url": "...",
         "next_max_id": "13872296"
    }
}
Muhammad Amin
  • 1,173
  • 8
  • 11
24

I will not be as arrogant to claim that this is a standard so I will use the "I prefer" form.

I prefer terse response (when requesting a list of /articles I want a JSON array of articles).

In my designs I use HTTP for status report, a 200 returns just the payload.

400 returns a message of what was wrong with request:

{"message" : "Missing parameter: 'param'"}

Return 404 if the model/controler/URI doesn't exist

If there was error with processing on my side, I return 501 with a message:

{"message" : "Could not connect to data store."}

From what I've seen quite a few REST-ish frameworks tend to be along these lines.

Rationale:

JSON is supposed to be a payload format, it's not a session protocol. The whole idea of verbose session-ish payloads comes from the XML/SOAP world and various misguided choices that created those bloated designs. After we realized all of it was a massive headache, the whole point of REST/JSON was to KISS it, and adhere to HTTP. I don't think that there is anything remotely standard in either JSend and especially not with the more verbose among them. XHR will react to HTTP response, if you use jQuery for your AJAX (like most do) you can use try/catch and done()/fail() callbacks to capture errors. I can't see how encapsulating status reports in JSON is any more useful than that.

Bojan Markovic
  • 510
  • 7
  • 22
  • 3
    "JSON is a payload format...". No, JSON is a data serialization format. You can use it to transmit anything you want, including session protocols or just simple payloads. Your KISS comments are on target though and independent of JSON. Better to keep the JSON focused on what it is (success data or failure reason data as you describe) than pollute it with some mishmash of both that constantly has to be composed and later stripped out. Then you can go all the way and store your JSON data as is in Couchbase and return it as is to the application. – Dirk Bester Apr 16 '14 at 00:32
  • 1
    Perhaps I should have formulated it as "supposed to be a payload format", but apart from that, I stand by my comment. You could put session/error data as attributes of *body* tag in HTML document, but that does not make it the right or sensible way to do it. – Bojan Markovic Apr 16 '14 at 05:40
20

For what it's worth I do this differently. A successful call just has the JSON objects. I don't need a higher level JSON object that contains a success field indicating true and a payload field that has the JSON object. I just return the appropriate JSON object with a 200 or whatever is appropriate in the 200 range for the HTTP status in the header.

However, if there is an error (something in the 400 family) I return a well-formed JSON error object. For example, if the client is POSTing a User with an email address and phone number and one of these is malformed (i.e. I cannot insert it into my underlying database) I will return something like this:

{
  "description" : "Validation Failed"
  "errors" : [ {
    "field" : "phoneNumber",
    "message" : "Invalid phone number."
  } ],
}

Important bits here are that the "field" property must match the JSON field exactly that could not be validated. This allows clients to know exactly what went wrong with their request. Also, "message" is in the locale of the request. If both the "emailAddress" and "phoneNumber" were invalid then the "errors" array would contain entries for both. A 409 (Conflict) JSON response body might look like this:

{
  "description" : "Already Exists"
  "errors" : [ {
    "field" : "phoneNumber",
    "message" : "Phone number already exists for another user."
  } ],
}

With the HTTP status code and this JSON the client has all they need to respond to errors in a deterministic way and it does not create a new error standard that tries to complete replace HTTP status codes. Note, these only happen for the range of 400 errors. For anything in the 200 range I can just return whatever is appropriate. For me it is often a HAL-like JSON object but that doesn't really matter here.

The one thing I thought about adding was a numeric error code either in the the "errors" array entries or the root of the JSON object itself. But so far we haven't needed it.

robert_difalco
  • 4,821
  • 4
  • 36
  • 58
19

Their is no agreement on the rest api response formats of big software giants - Google, Facebook, Twitter, Amazon and others, though many links have been provided in the answers above, where some people have tried to standardize the response format.

As needs of the API's can differ it is very difficult to get everyone on board and agree to some format. If you have millions of users using your API, why would you change your response format?

Following is my take on the response format inspired by Google, Twitter, Amazon and some posts on internet:

https://github.com/adnan-kamili/rest-api-response-format

Swagger file:

https://github.com/adnan-kamili/swagger-sample-template

adnan kamili
  • 8,967
  • 7
  • 65
  • 125
9

The point of JSON is that it is completely dynamic and flexible. Bend it to whatever whim you would like, because it's just a set of serialized JavaScript objects and arrays, rooted in a single node.

What the type of the rootnode is is up to you, what it contains is up to you, whether you send metadata along with the response is up to you, whether you set the mime-type to application/json or leave it as text/plain is up to you (as long as you know how to handle the edge cases).

Build a lightweight schema that you like.
Personally, I've found that analytics-tracking and mp3/ogg serving and image-gallery serving and text-messaging and network-packets for online gaming, and blog-posts and blog-comments all have very different requirements in terms of what is sent and what is received and how they should be consumed.

So the last thing I'd want, when doing all of that, is to try to make each one conform to the same boilerplate standard, which is based on XML2.0 or somesuch.

That said, there's a lot to be said for using schemas which make sense to you and are well thought out.
Just read some API responses, note what you like, criticize what you don't, write those criticisms down and understand why they rub you the wrong way, and then think about how to apply what you learned to what you need.

Norguard
  • 26,167
  • 5
  • 41
  • 49
  • 2
    Thank you for the response, but again, I'm not worried about the payloads themselves. While your examples all have very different requirements in terms of what is sent/received within the _payloads_ and how those _payloads_ are consumed, they all have to solve the same problems with respect to the _response itself_. Namely, they all need to determine if the request was successful. If it was, proceed with processing. If it wasn't, what went wrong. It's this boilerplate that is common to _all_ API responses that I'm referring to in my question. – FtDRbwLXw6 Oct 09 '12 at 19:36
  • 1
    Either return a status of 200 for everything, and define yourself a specific error payload, or return a status commensurate with the error, with and/or without more details in the body of the payload (if supported). Like I said, the schema is up to you - including any meta/status information. It's a 100% blank slate to do with what you please based on your preferred style of architecture. – Norguard Oct 09 '12 at 22:10
  • 2
    I realize that it's a blank slate to do with as I please. The purpose of my question is to ask if there were any emerging standards as far as the structure goes. I was not asking "what is JSON and how do I use it", but rather, "I know how to use JSON to return/structure anything I want, but I'd like to know if there are any standard structures being used or becoming popular." I'm sorry if I misworded by question. Thanks for your response, anyway. – FtDRbwLXw6 Oct 11 '12 at 19:08
8

JSON-RPC 2.0 defines a standard request and response format, and is a breath of fresh air after working with REST APIs.

dnault
  • 8,340
  • 1
  • 34
  • 53
  • The only thing JSON-RPC_2.0 offers for exceptions is an error code? A numeric error code can not represent with any fidelity the problem that occurred. – AgilePro May 02 '19 at 18:58
  • @AgilePro Agreed, a numeric error code is not very nice, and I wish the authors of the spec had allowed the `code` field to be a String. Fortunately the spec allows us to stuff whatever information we want into the error's `data` field. In my JSON-RPC projects I typically use a single numeric code to for all application-layer errors (as opposed to one of the standard protocol errors). Then I put the detailed error information (including a string code indicating the real error type) in the `data` field. – dnault May 02 '19 at 19:36
4

The basic framework suggested looks fine, but the error object as defined is too limited. One often cannot use a single value to express the problem, and instead a chain of problems and causes is needed.

I did a little research and found that the most common format for returning error (exceptions) is a structure of this form:

{
   "success": false,
   "error": {
      "code": "400",
      "message": "main error message here",
      "target": "approx what the error came from",
      "details": [
         {
            "code": "23-098a",
            "message": "Disk drive has frozen up again.  It needs to be replaced",
            "target": "not sure what the target is"
         }
      ],
      "innererror": {
         "trace": [ ... ],
         "context": [ ... ]
      }
   }
}

This is the format proposed by the OASIS data standard OASIS OData and seems to be the most standard option out there, however there does not seem to be high adoption rates of any standard at this point. This format is consistent with the JSON-RPC specification.

You can find the complete open source library that implements this at: Mendocino JSON Utilities. This library supports the JSON Objects as well as the exceptions.

The details are discussed in my blog post on Error Handling in JSON REST API

AgilePro
  • 5,588
  • 4
  • 33
  • 56
4

For those coming later, in addition to the accepted answer that includes HAL, JSend, and JSON API, I would add a few other specifications worth looking into:

  • JSON-LD, which is a W3C Recommendation and specifies how to build interoperable Web Services in JSON
  • Ion Hypermedia Type for REST, which claims itself as a "a simple and intuitive JSON-based hypermedia type for REST"
CodeBiker
  • 2,985
  • 2
  • 33
  • 36
A. Barakat
  • 41
  • 4
1

There is no lawbreaking or outlaw standard other than common sense. If we abstract this like two people talking, the standard is the best way they can accurately understand each other in minimum words in minimum time. In our case, 'minimum words' is optimizing bandwidth for transport efficiency and 'accurately understand' is the structure for parser efficiency; which ultimately ends up with the less the data, and the common the structure; so that it can go through a pin hole and can be parsed through a common scope (at least initially).

Almost in every cases suggested, I see separate responses for 'Success' and 'Error' scenario, which is kind of ambiguity to me. If responses are different in these two cases, then why do we really need to put a 'Success' flag there? Is it not obvious that the absence of 'Error' is a 'Success'? Is it possible to have a response where 'Success' is TRUE with an 'Error' set? Or the way, 'Success' is FALSE with no 'Error' set? Just one flag is not enough? I would prefer to have the 'Error' flag only, because I believe there will be less 'Error' than 'Success'.

Also, should we really make the 'Error' a flag? What about if I want to respond with multiple validation errors? So, I find it more efficient to have an 'Error' node with each error as child to that node; where an empty (counts to zero) 'Error' node would denote a 'Success'.

Broken Arrow
  • 576
  • 3
  • 12
1

I used to follow this standard, was pretty good, easy, and clean on the client layer.

Normally, the HTTP status 200, so that's a standard check which I use at the top. and I normally use the following JSON

I also use a template for the API's

dynamic response;

try {
   // query and what not.
   response.payload = new {
      data = new {
          pagination = new Pagination(),
          customer = new Customer(),
          notifications = 5
      }
   }

   // again something here if we get here success has to be true
   // I follow an exit first strategy, instead of building a pyramid 
   // of doom.
   response.success = true;
}
catch(Exception exception){
   response.success = false;
   response.message = exception.GetStackTrace();
   _logger.Fatal(exception, this.GetFacadeName())
}

return response;

{ 
  "success": boolean,
  "message": "some message",
  "payload": { 
     "data" : []
     "message": ""
     ... // put whatever you want to here.
  } 
}

on the client layer I would use the following:

if(response.code != 200) { 
  // woops something went wrong.
  return;
}

if(!response.success){
  console.debug ( response.message ); 
  return;
}

// if we are here then success has to be true.
if(response.payload) {
  ....
}

notice how I break early avoiding the pyramid of doom.

1

I use this structure for REST APIs:

{
  "success": false,
  "response": {
    "data": [],
    "pagination": {}
  },
  "errors": [
    {
      "code": 500,
      "message": "server 500 Error"
    }
  ]
}
1

A bit late but here is my take on HTTP error responses, I send the code, (via status), the generic message, and details (if I want to provide details for a specific endpoint, some are self explanatory so no need for details but it can be custom message or even a full stack trace depending on use case). For success it's a similar format, code, message and any data in the data property.

ExpressJS response examples:

// Error

    res
      .status(422)
      .json({
        error: {
          message: 'missing parameters',
          details: `missing ${missingParam}`,
        }
      });
        
    // or
        
    res
      .status(422)
      .json({
        error: {
          message: 'missing parameters',
          details: 'expected: {prop1, prop2, prop3',
        }
      });

 // Success

    res
      .status(200)
      .json({
         message: 'password updated',
         data: {member: { username }}, // [] ...
      });
Ed Barahona
  • 721
  • 5
  • 7
-4

Best Response for web apis that can easily understand by mobile developers.

This is for "Success" Response

{  
   "code":"1",
   "msg":"Successfull Transaction",
   "value":"",
   "data":{  
      "EmployeeName":"Admin",
      "EmployeeID":1
   }
}

This is for "Error" Response

{
    "code": "4",
    "msg": "Invalid Username and Password",
    "value": "",
    "data": {}
}
Manish Vadher
  • 1,524
  • 15
  • 14