So far we have seen how methods accept HTTP requests and how they pass data from those requests to method parameters. However, occasionally, the requests received will need to be more complex. For example, instead of receiving the first name as a string parameter from an HTTP request, perhaps we may need to receive an entire form object. How do we go about passing a custom object into a method via an HTTP request? Also, how does the server understand how to properly translate that request? You guessed it; there’s an annotation for that!
We can use the @RequestBody
annotation on the parameters of a method. When used, this annotation allows Spring to automatically deserialize the HTTP request body into a Java object which can be bound to the method and further processed. The objects can be created by matching attributes with values in JSON.
For example, we can rewrite the previous book example with @RequestBody
if we define a Book
object:
class Book { public int authorCount; public int publishedYear; }
The new controller will have a single Book
parameter instead of separate authorCount
and publishedYear
parameters:
@GetMapping("/book") public Book isBookAvailable(@RequestBody Book book) { return book.find(book.authorCount, book.publishedYear); }
Finally, the request would need to have authorCount
and publishedYear
in its body (rather than the previous URL query parameters ?author_count=2&published_year=1995
):
curl -X POST --data '{\"authorCount\": \"2\", \"publishedYear\": \"1995\"}' "https://localhost:8080/.../book"
Instructions
Previously, our createNewSuperHero
method accepted 3 path variables that matched the properties in the SuperHero
class:
String firstName
String lastName
String superPower
Update the method so that it accepts one argument of type SuperHero
:
- import the
RequestBody
annotation - Replace the three existing parameters with a single, new parameter
- Label it with the
@RequestBody
annotation - Update the method body accordingly
Using curl
, make a POST request to the endpoint /addNew
with a request body containing a new superhero.