Sahil Sharma
Sahil Sharma

Reputation: 4247

REST API: How to fetch objects and popular objects, should it be same API or separate API?

We have several API endpoints like:

/api/cities/ => Fetches all cities in our database. Its an oversimplified example, actually we have around 1k cities.

{
         "name": "Chicago",
         "name": "Los Angeles",
         "name": "New York",
         "name": "Phoenix"
}

Currently these API returns city list in alphabetic order.

We have new requirement where we need to fetch popular cities at the top, this followed by list in alphabetic order.

JSON Output would look like:

{
   "popular"
   {
     "name": "New York",
     "name": "Los Angeles"
   },
   "all"
   {
      "name": "Chicago",
      "name": "Los Angeles",
      "name": "New York",
      "name": "Phoenix"
   }
}

How should current APIs be modified to fulfil this:

  1. Should we create new API like /api/popularcities/ which would fetch list of popular cities? This way client would call /api/popularcities/ first and then /api/cities/ API.
  2. Should we add query string parameter in existing API /api/cities/?fetch=popularall to fetch both popular and all cities.

Or any other thing, this doesn't look like filter attribute as this is actually adding result at the top and not filtering it out.

We do need to repeat popular cities in all city list as this would be binded directly to UI dropdown and requirement is to keep alphabetic ordering intact.

Suggestions?

Upvotes: 0

Views: 237

Answers (2)

kien bui
kien bui

Reputation: 1820

you can use both endpoint, a endpoint like as shortcut of api fetch all with order by popular.

  1. /cities?sort=popular
  2. /popular_cities

Upvotes: 0

Ioan
Ioan

Reputation: 5187

popular cities are a way of sorting for the same entities.

It shouldn't be a new resource, but a way of querying the same resource sorted differently to get the needed entries.

I would use a query for that: ?sort=popular.

Upvotes: 1

Related Questions