简体   繁体   中英

Understanding where to put constraints validation for REST api service using Spring

I'm working on a REST api for a model having the following entities:

在此处输入图像描述

A Team cannot exists if it has no relationships with a Course and a Student . At the beginning, I created an endpoint for the teams ( API/teams ) for the CRUD operations. Now I ended up moving all the CRUD operations for the teams under the following URLs:

/API/courses/{courseId}/teams

The same has been done for Machine that cannot exists without any relationships with a Team and Student , so any CRUD operation should be done to the following:

/API/courses/{courseId}/teams/{teamId}/virtual-machines

This makes sense to me, since every time I need to perform an operation on a Machine I have to verify the constraint for which the Machine is owned by a Team related to a Course . For this reason, If I continued to perform any operation on URLs like /API/teams I should have requested the course and team ids to verify those contraints in the request body.

Having said this, my CourseController invokes a VirtualMachineService for all the operations on the Machine entity. What it seems odd to me is that each signature of every method in the VirtualMachineService need to have the course and the team id to verify the above constraints. This caused to have lots of duplicated code in every method.

  1. Are my design choices correct?

The CourseController only have to invoke the methods of VirtualMachineService and to validate the parameters coming from the requests body.

  1. Should those constraints validation be done inside the controller or inside the service?

Neither Configuration nor Model are entities. Entities are classes from the domain (real world representations related to project, if you will), not every class you use.

REST doesn't directly care about your entity model (meaning graph) but you should follow the guidelines for specifying REST endpoints which is

different endpoint for

/courses/... and /teams/... - don't mix these. Any constraints you would like to apply are applied at the backend and have nothing to do with endpoint definitions.

Validation guide https://www.baeldung.com/spring-mvc-custom-validator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM