Arian
Arian

Reputation: 7729

Should I have separate rest controller for a dependent entity

There are two entities in my spring boot app: Dealer, Car

A Car cannot live without being owned by a Dealer.

Right now, I have two sets of endpoints (i.e. two controller classes): DealerController, CarController

DealerController handles CRUD operations for Dealer entities. CarController handles UPDATE, DELETE, READ operations for Car entities.

My question is regarding the CREATE operation for Car. The endpoint takes in the id for the Dealer and the POST request body would be the Car information.

Should I put it under DealerController or CarController ?

Upvotes: 2

Views: 1414

Answers (2)

Avi
Avi

Reputation: 1100

Both controllers should be present as they will be used for specific operations.

The DealerController will be responsible for,

  • Adding new dealers /dealers - POST
  • Updating dealer details /dealers/2 - PUT
  • Getting list of dealers - /dealers - GET
  • Getting details of a particular dealer /dealers/2 - GET
  • Deleting a dealer - /dealers/2 - DELETE
  • etc.

The CarController will be responsible for,

  • Adding new cars /cars - POST
  • Updating car details - /cars/1 - PUT
  • Getting list of all cars /cars - GET
  • Getting list of all cars by dealer /cars?dealerId=2 /GET
  • Getting details of a particular car /cars/1 - GET
  • Deleting a car - /cars/1 - DELETE
  • etc.

Your end point for CarController should not have the dealerId in it if you strictly want to go by RESTful conventions. When adding a new car, the request body should contain the JSON representation of the car attributes and the dealerId since every car can have only one dealerId

e.g.

{
    "dealerId": 2,
    "manufacturer": "bmw",
    "color": "white",
    "model": "320d"
}

Accordingly the model class for car should have the dealerId or the dealer object as its attribute, depending on how much detail you want.

Upvotes: 1

alirabiee
alirabiee

Reputation: 1306

As the operation is about creating a Car, it concerns the Car entity mainly. Hence, following the guidelines of separation of concerns and high coupling in OOP, it needs to be placed inside the CarController.

Upvotes: 1

Related Questions