Reputation: 679
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.
Upvotes: 5
Views: 2089
Reputation: 679
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.”
Upvotes: 7