Having built a RESTful API (using Laravel) for a project at work, I followed what seemed (from lots of reading) to be a the majority in terms of my approach to nested resources - by defining them in the path:
https://myapi.com/clients/{clientId}/tasks
rather than:
https://myapi.com/tasks?client={clientId}
Filtering results further than this, plus ordering etc was done using query parameters:
https://myapi.com/clients/{clientId}/tasks?orderby=title
Whilst initially this seemed like a good approach, it did become more difficult to maintain in terms of the controllers and routes. For example, for the above, I created a ClientsController, a TasksController AND a ClientsTasksController.
TasksController
public function store() {}
public function updated() {}
public function destroy() {}
TasksClientsController
public function index($client_id) {}
And the routes:
Route::resource('tasks', 'TasksController', ['except' => [
'edit', 'index'
]]);
Route::resource('clients.tasks', 'ClientsTasksController', ['only' => [
'index'
]]);
This application did not need many more nested resources such as this, it was relatively straightforward. However, I am now looking to create an API for existing application which has many more complex relationships. It is a league management app, EER diagram below:
Where I'm concerned is that I am going to need to query resources by a lot of different data - for example:
- teams by a specific division, season and round
- statistics by both team id and season id, and possibly round id also
- matches by season, round and division
and combinations of the above.
It therefore seems to me to make more sense to have a controller and route for each final resource, but to use query parameters rather than path variables.
For example:
https://myapi.com/matches?team_id={teamId}&season_id={seasonId}&roundId={roundId}
rather than:
https://myapi.com/seasons/{seasonId}/teams/{teamId}/matches
and the various extra controllers this would create.
However I feel this may be going against the grain in terms of what most people seem to suggest - see here for example. The second URL also seems neater to me.
Any help / recommendations would be very much appreciated.