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?

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.

  • 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. – Renan Ivo Jul 25 '14 at 21:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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