I have an action method returning all books of a library by specifying libraryId. Should the action method be placed into LibraryController or into BookController?
There are many action methods in the controllers and the controllers are named according to entities: BookController, LibraryController, OrderController, LoginController.
There can be two rules for that.
1. Endpoints organized by url (the url is the same, the entity type differs)
The endpoint with url /library/{libraryId}/books returning list of books should be placed in LibraryController, but the endpoint with url /book/{bookId} returning one book should be placed in the BookController.
/library/{libraryId}/books => LibraryController
/book/{bookId} => BookController
Example:
[ApiController]
[Route("/library")]
public class LibraryController
{
[HttpGet]
[Route("{libraryId}/books")]
public async Task<ActionResult<IList<Book>> GetBooks([FromRoute] Guid libraryId)
{
return await bookService.GetBooks(libraryId);
}
}
[ApiController]
[Route("/book")]
public class BookController
{
[HttpGet]
[Route("{bookId}")]
public async Task<ActionResult<Book>> GetBook([FromRoute] Guid bookId)
{
return await bookService.GetBook(bookId);
}
}
2. Endpoints organized by returned entity (the url differs, the entity type is the same)
The endpoint with url /library/{libraryId}/books returning list of books and the endpoint with url /book/{bookId} returning one book should both be placed into BookController since they return Book entity and list of Book entities.
/library/{libraryId}/books => BookController
/book/{bookId} => BookController
Example:
[ApiController]
public class BookController
{
[HttpGet]
[Route("/book/{bookId}")]
public async Task<ActionResult<Book>> GetBook([FromRoute] Guid bookId)
{
return await bookService.GetBook(bookId);
}
[HttpGet]
[Route("/library/{libraryId}/books")]
public async Task<ActionResult<IList<Book>> GetBooks([FromRoute] Guid libraryId)
{
return await bookService.GetBooks(libraryId);
}
}
Which rule do you use and why?
Note: I added examples