-1

tl;dr Which is the best server response for an endpoint to get a user's age?

30 or {"age":30} or {"metadata":{"time":1561919615,"status":200},"age":30} or something else?


I am writing a server using Firebase Functions. I am trying to determine the best way to send my responses. My server-side experience is minimal.

Sometimes the data I need to send is an object, where JSON makes perfect sense.

getUser: {"name":"John","age":30,"car":null}

Sometimes it is a number, where JSON seems like overkill.

getAge: {"age":30} or 30

Is it preferable to always send fully-formatted JSON? Performance is not a major concern in my case.

On the other side, should I make a predefined type that I always respond with?

{"age":30} or {"metadata":{"time":1561919615,"status":200},"age":30}

To summarize, what does a proper response from a server look like? For my particular case, its a mobile app where pricing is dictated primarily by number of responses, not size of response. As far as I understand, JSON is the standard, and I believe just sending 30 would be bad practice. (But I don't know for sure.)

Should I use one of the 3 versions above, or is there a better approach I should take?

closed as primarily opinion-based by Jörg W Mittag, Doc Brown, Philip Kendall, BobDalgleish, gnat Jul 3 at 21:15

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

2

Having a basic JSON wrapper such as {"age":30} enables you to extend the response structure in the future without breaking the interface. You don't need to include the additional metadata if you don't need it right now, but you have the option of adding it later.

A JSON structure also provides a basic schema for clients to validate against. If the server fails and dumps a raw error message, you don't want clients to try and interpret this as a valid response.

  • Age = 401 could be misinterpreted... – James McLeod Jul 1 at 1:59
  • @JamesMcLeod: Which is why you would never return it. – Robert Harvey Jul 1 at 2:46
  • Yes, absolutely. I am agreeing with this answer. – James McLeod Jul 1 at 2:48
1

I would use JSON responses for everything which is back end related. Even for error responses if possible. It's always more meaningful for the front end because of the key/value format and standardization.

  • Agreed in general, although 30 is a valid JSON response, too (it just means the number 30, not an object with key:value associations.) So for readability and extensibility I'd use {} objects or [{}] lists of objects. – Hans-Martin Mosner Jul 2 at 10:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.