Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

api - What is the standard format for returning lists in REST JSON responses?

When returning a list of objects in a JSON response, say a GET request to a /movies endpoint, is it more common to return a JSON array or an object that wraps a JSON array? I've seen both formats in APIs and I was wondering if the standard. If there isn't, which way is preferable?

i.e.

[
  {
    "name": "Harry Potter",
    "year": 2000
  }
]

vs.

{
  "movies": [
    {
      "name": "Harry Potter",
      "year": 2000
    }
  ]
}
question from:https://stackoverflow.com/questions/65903612/what-is-the-standard-format-for-returning-lists-in-rest-json-responses

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In general if you have a service that only return a list, the first option is perfect fine:

[
  {
    "name": "Harry Potter",
    "year": 2000
  }
]

But if you are thinking in a general way to do it will be better add more context data, as total items counter, pagination variables or status values. So in spite of the first one is perfectly fine, I always preffer second one, but without the name of the collection/array/table name and with more context info, as for example:

{
  "items": [
    {
      "name": "Harry Potter",
      "year": 2000
    }
  ],
  "total": 1,
  "page": 1,
  "pages": 1
  "status": 1,
  "timestamp: 121344
}

Set the array nested on movies value is a bit redundant. But for my it's only a practical approach that for my experience is more readable and used in all projects which I am related.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...