Java – create, update and get the same / different dto objects in the rest endpoint?
Consider using userdto class and usercontroller public endpoint to create, update and obtain users
Having the ID attribute in the userdto class has no meaning for creation and update If I use swagger or other automatically generated API documents, it will show that the ID can be passed in create end point But the system does not use it because the ID is generated internally
If I look at get, maybe I can get rid of the ID attribute, but it must be in the list user endpoint
I want to return the internal user domain object at the get / list endpoint This allows me to remove the ID attribute from the userdto class
Can I use a better choice for this?
public class UserDTO { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @RestController @RequestMapping(value = "/users",produces = MediaType.APPLICATION_JSON_VALUE) public class UserController { @RequestMapping(method = RequestMethod.POST) @ResponseBody public ResponseEntity<Void> create(@RequestBody UserDTO user) { } @RequestMapping(value = "{id}",method = RequestMethod.GET) @ResponseBody public ResponseEntity<UserDTO> get(@PathVariable("id") int id) { } @RequestMapping(value = "{id}",method = RequestMethod.PUT) @ResponseBody public ResponseEntity<Void> update(@PathVariable("id") int id,@RequestBody UserDTO user) { } }
Someone may have asked this question, but I can't find it Please forgive me for repeating the question
Solution
Data transfer object (dto) is a pattern created with a very clear purpose: to transfer data to a remote interface, just like a web service This pattern is very suitable for rest API. In the long run, dto will provide you with more flexibility
Once the rest resource representation does not need to have the same properties as the persistent object, I recommend using a custom class for the endpoint
To avoid boilerplate code, you can use a mapping framework such as mapstructure to map rest API DTOs to / from persistent objects
For more information on the benefits of using dto in the rest API, check the following answers:
> Why you should use DTOs in your REST API > Using tailored classes of request and response
To provide a better name for your dto, check the following answers:
> Giving meaningful names to your DTOs