One Web API controller per resource, or fewer controllers with more custom actions?

I want to expose most of my business layers to web API techniques to enable wider consumption.

One idea is to have one web API controller per resource.

Another idea is to have one controller for each logical business part and use attribute routing to display relative methods.

I like the second approach, which results in fewer controllers.

What are the disadvantages of NOT having one controller per resource?

Additional Information:

This API will live on the intranet and will serve support applications that need data from our 2-3 core applications (ERP, Payroll, Barcode etc)

The resource for this APi will be the business objects that are defined in our business layer assembly. They will be simple objects and complex ones. Examples:

  • Inventory items
  • Clients
  • Items per customer
  • Pickslips currently loading
  • Existing production data

etc

Example:

I want to expose methods like GetCustomerListByArea

or GetItemsListPerCategory

.

What then? Should I create another controller or use custom controller actions and attribute routing and put it in existing controllers?

Link with more information:

REST vs. RPC in ASP.NET web frontend? Who cares; he does both.

Very nice, pretty old article explaining my question. But it doesn't go deeper into telling you how to operate the controllers. Areas? Or just folders?

+3


source to share


1 answer


It boils down to a simple design principle of Separation of Concerns (SoC), you should think about what functionality of your business layer you want to expose and build controllers from.

In the above example, you can create ProductController

and CustomerController

that can display the following endpoints:



GET /api/customer/1234        # gets customer by id
POST /api/customer/create     # creates a new customer
GET /api/customer/1234/items  # gets all items for a customer
GET /api/product/9876         # gets a product by id
POST /api/product/create      # creates a new product

      

Hope it helps ...

+1


source







All Articles