kitkong
kitkong

Reputation: 51

How to use Objects as parameters in REST webservices

I am writing a rest service looking something like this:

@POST
@Consumes("application/json")
public void save(@QueryParam("firstName") String firstName, @QueryParam("lastName") String lastName, @QueryParam("email") String email) {
    User user = new User(firstName, lastName, email);
    db.createUser(user);
}

I would like to be able to have something like an object parameter:

@POST
@Consumes("application/json")
public void save(@ObjectParam User user) {
    db.createUser(user);
}

It would be nice not having to specify what parameters i am expecting or writing my own object parser.

Upvotes: 0

Views: 75

Answers (2)

morsor
morsor

Reputation: 1323

In Spring REST, one may do the following:

@RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseEntity<Car> update(@RequestBody Car car) {
    ...
}

Upvotes: 0

Weston Jones
Weston Jones

Reputation: 161

This should be sufficient

@POST
@Consumes("application/json")
public void save(User user) {
    db.createUser(user);
}

It should map the object to JSON as long as you include a JSON object in your POST that matches.

Upvotes: 1

Related Questions