4

I have an REST API endpoint which the JSON response looks like:

{
 "products": [
 {"id": 1040, "price": 2.95, ...}
 {"id": 4545, "price": 3.95, ...}
 ]
}

One of my colleagues suggested that I should add a key for each item in the list. He said it would make easier to browse the browse the API. The example above would become:

{
 "products": {
 "1040": {"id": 1040, "price": 2.95, ...}
 "4545": {"id": 4545, "price": 3.95, ...}
 }
}

Making it will not be harmful for my API's performance and I can understand how it should improve the browsability. Should I do that? Is there any example of public API that does something similar?

asked Jul 25, 2014 at 18:10

1 Answer 1

4

It depends.

Is the response an answer to a query that's more like GetListOfProducts() or GetProductIndex()? Is the result intended to be iterated over or used as a single-product lookup by id? Is the sort-order significant?

If it's more like GetListOfProducts() with sort-order implications and/or the intention of iteration, like displaying the records in a table, stick with what you have. It's probably trivial for your API consumers to search or index the items.

If it's more like GetProductIndex() and is intended to be used like an index, and if sort order doesn't matter, consider sending it in the 2nd form. But even in this case, remember that it's probably trivial to index (or search() or filter()) the array client-side. So, I'd be a little hesitant: Consider whether it's more difficult for the client/consumer to index and search a list or for the server to inject a sort order (and the client to respect that order) if needed on a property set that has no inherent ordering.

answered Jul 25, 2014 at 19:01
1
  • 1
    Thanks for the answer. I didn't think about the sort order issues. In my case the order doesn't matters, but there should be other places where it does. My API could become inconsistent if I return a map in some endpoints and a list elsewhere. Commented Jul 25, 2014 at 21:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.