Home > Software design >  What is the proper approach on persisting a new object? Receiving a built json object with @RequestB
What is the proper approach on persisting a new object? Receiving a built json object with @RequestB

Time:10-28

In order to save a new object like i.e a User object:

class User {

private String name;
private String email;

}

Should I ask my client to submit a @RequestBody like this:

{
"name":"Josh",
"email":"[email protected]"
}

Or maybe should just ask for some @RequestParams like this:

/api/user?name=Josh&&email=josh@kmail.com

And create a method that builds the object from these params? I am dealing with some complex objects in my project if it has anything to do with my question.

Thanks your help.

CodePudding user response:

Spring MVC has 2 annotations to handle mapping to an object.

So actually both can automatically map to your User object.

@PostMapping
public User register(@RequestBody User user) {}

or

@PostMapping
public User register(@ModelAttribute User user) {}

The first will use the payload, the second will use the request parameters to create the User object. So both will work, but serve different use cases.

CodePudding user response:

Both your approaches would work - but the standard way is definitely using:

POST @RequestBody JSON of { user } to /users

GET would technically work - but using the HTTP method GET implies that the action is idempotent, meaning it will not change the underlying data (from the client's viewpoint) - and this is almost certainly not the case when creating a new User.

In addition, the current User object is simple enough to be represented by query string parameters - but that may change in the future, when a User could contain various contact information such as addresses.

CodePudding user response:

@RequestBody annotation automatically deserializes the JSON data encapsulated in the request body into a particular model object. example:

@PostMapping("/create")
@ResponseBody
public Product createProduct(@RequestBody Product product) {
// custom logic
return product;
}

unlike @RequestBody, the @RequestParam annotation supports only simple data types such as int and String.

  • Related