Should I add a key to the items of my REST API response?

  softwareengineering

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?

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

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT