5

I got called "unprofessional" today because I didn't nest my JSON response in a parent object.

GET /users/{id} responds with this:

{
    "username":"atr217",
    "age":35,
    ...
}

They expected this:

{
    "user":{
        "username":"atr217",
        "age":35,
        ...
    }
}

Or maybe this:

{
    "status":200,
    "message":"OK"
    "data":{
        "username":"atr217",
        "age":35,
        ...
    }
}

I've seen it done both ways. Is the best practice to wrap the data in a parent? If so, why? And what else goes in the parent?

I'm using SwaggerHub and OpenAPI 3, if that matters.

3
  • 1
    Possible duplicate of Root Nodes in JSON
    – Helen
    Commented Oct 24, 2018 at 8:06
  • 2
    status and "message":"OK"/or any other are totally redundant since we can get that from the HTTP response. In general all info that can be gotten from the HTTP response is redundant in the response data, all the rest is a matter of following conventions (team, best practice everybody agreed to use, etc.) but arguable at the end of the day. Commented Oct 24, 2018 at 15:04
  • consider using jsonapi.org
    – Tylor Hess
    Commented Oct 25, 2018 at 15:24

1 Answer 1

7

I found the correct Google search term: "envelope"

RESTful API Design Tips from Experience

“I do not like enveloping data. It just introduces another key to navigate a potentially dense tree of data. Meta information should go in headers.”

“One argument for nesting data is to provide two distinct root keys to indicate the success of the response, data and error . However, I delegate this distinction to the HTTP status codes in cases of errors.”

“Originally, I held the stance that enveloping data is not necessary, and that HTTP provided an adequate “envelope” in itself for delivering a response. However… I now recommend enveloping.”

When in my REST API should I use an envelope? If I use it in one place, should I always use it?

“HTTP is your envelope… Having said that, there is nothing wrong with having a descriptive body on a response”

Best Practices for Designing a Pragmatic RESTful API

“Don’t use an envelope by default, but make it possible when needed”

“We can future proof the API by staying envelope free by default and enveloping only in exceptional cases.”

“There are 2 situations where an envelope is really needed - if the API needs to support cross domain requests over JSONP or if the client is incapable of working with HTTP headers.”

“Envelope loving APIs typically include pagination data in the envelope itself. And I don’t blame them - until recently, there weren’t many better options. The right way to include pagination details today is using the Link header introduced by RFC 5988.”

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