Friday, May 19, 2023

Top 5 Spring MVC Annotations for RESTful Web Services in Java

Hello guys, Spring framework is one of the most popular Java framework and Spring MVC is probably the most common way to develop web applications in Java, but things just doesn't end there. In the past a couple of years, Spring has become the best way to develop RESTful Web services in Java. Despite numerous RESTful Web Service frameworks in Java world e.g. Restlet, Jersey, RESTEasy, and Apache CFX, Spring MVC has maintained its position as the leading framework for creating RESTful APIs in Java, and there are multiple reason why Spring is the best framework for Java developers for creating RESTful solutions and we will look one of them in this article. 

One of the most important reason of that success is state of the art support for developing both RESTful client and servers in Spring Framework. 

Spring MVC always had some of the ingredients required for exposing REST resources but some of the recent enhancements from Spring 3.0 and Spring 4.0 has made it even more suitable for creating REST resources and most important them are annotations. 

Spring MVC provides some really good annotations to work with RESTful web services e.g. you have annotation to create controller to handle request for REST resources, annotations to override HTTP status codes, which is key for conveying information to REST client, annotations for extracting data from URLs, which is another important feature to work with RESTful URLs and several HTTP message converters to convert objects into representations client wants. 

In this article, I am going to share some of the essential Spring MVC annotations you can use to develop RESTful Web Services. If you have been using Spring MVC then you may be already familiar with these Spring MVC annotations but for beginners, a good knowledge of these annotations goes a long way in creating RESTful web services in Spring. 




5 Essential Spring MVC Annotations for RESTful Web Service Development

Without wasting anymore of your time, here is a list of most essential Spring MVC annotations for developing RESTful client and Server in Java using Spring Framework.  You need to include Spring MVC library in your classpath to get access of these annotations. 

You can do that using Maven by declaring dependency in pom.xml file or you can download Spring framework JAR from Maven central and add them into your application classpath. By the way, using Maven or Gradle for dependency management is better and recommend in Java application. 


1. @ResponseBody

One of the key difference between a normal Spring web application and a RESTful web service is the response returned by controller method. In case of normal web application, controller generally return name of the view and then the view resolvers are responsible for sending the correct representation to the client (see how how dispatcher servlet works). 

In case of RESTful web services, you don't really need a view because all client is interested in the representation of Resource (a Java object) in the format he wants e.g. JSON or XML and @ResponseBody annotation just does that. 

It tells Spring that you want to send the returned object as a resource to the client, converted into some representational form that the client can accept. 

You can completely by pass the view resolution process by using the @ResposneBody annotation. When you use @ResponseBody annotation at the handler method level it instruct Spring MVC that the HTTPMessageConvert should be used to create appropriate representation of the Java objects returned by handler method instead of using a view resolver. 

For example, MapppingJackson2HttpMessageConvert can be used to read and write JSONs to and from typed objects or untyped HashMap. It's also automatically registered if the Jackson 2 JSON library is present in the classpath. 

Btw, it doesn't meant that you cannot use the ViewResolver while developing RESTful web services with Spring, the ContentViewNegotiaonViewResolver is a special view resolver for RESTful response. 

It can look at the extension of HTTP request path or Accept header to figure out the correct representation for client. For example, if client wants JSON then it may request resource with .json or send "application/json" the Accept header. 

Top 5 Spring MVC Annotations for Developing RESTful Web Services




2. @RequestBody

As the name suggest this is a close cousin of @ResponseBody annotation but on the request side. Just as @ResponseBody tells Spring to use a message converter while sending response to the client, the @Requestbody annotation tells Spring to find a suitable message converter to convert a resource representation coming from a client into a Java object, controller can work. 

This is particularly useful while creating resources using POST method or updating them using PUT method. If you are not sure about POST and PUT, I suggest to read when to use PUT and POST method in REST.

Here is how your handler method to create a resource e.g. a Tutorial will look like:

@RequestMapping(method = RequestMethod.POST consumes="application/json")
public @ResponseBody Tutorial create(@RequestBody Tutorial tutorial){
  return tutorialRepository.create(tutorial);
}

If client send a Tutorial object in JSON format then the @RequestBody annotation will automatically convert that into a Tutorial Java object, of course by using HttpMessageConverts. See REST with Spring course by Baeldung to learn more about HttpMessageConverts and effective use of @ResposneBody and @RequestBody annotation. 




3. @RestControler 

The @ResponseBody annotation is a nice way to instruct Spring that employ message conversion for returned object from controller handler method but it get repetitive if your controller has many methods and all of them does message conversion. Spring acknowledge this problem and it introduced @RestController annotation in Spring 4.0. 

So instead of annotating all handler methods with @ResponseBody annotation, you can just annotated your controller class with @RestController and still have same effect i.e. all objects returned from these handler methods will still go through message conversion before sending them to client. 

It also improves readability by clearly indicating that a particular controller is dealing with requests for REST API. You can read more about it on my post difference between @Controller and @RestController in Spring

RestController Example in Java and Spring



4. @ResponseStatus

A REST API is much more than just the payload, both status code and headers are important part of any REST architecture. They convey some of the important meta data for REST client which helps them to understand the both the resource and response better. The @ResponseStatus annotation allows you to specify a status code for the response. You can even override default status code to provide more information. 

For example in the above method to create a resource (Tutorial) by default a status code of 200 OK will be returned to client, which is not a bad idea but you can make it even better by returning a more appropriate code 201 Created. 

This will clearly communicate to the client that not just its request was handled successfully but also a resource is created as part of its request. You can do this by using @ResponseStatus annotation, which allows you to override the default status code as shown below:

@RequestMapping(method = RequestMethod.POST consumes="application/json")
@ResponseStatus(HttpStatus.CREATED)
public @ResponseBody Tutorial create(@RequestBody Tutorial tutorial){
   return tutorialRepository.create(tutorial);
}

You can further clean the code by removing @ResponseBody annotation and using @RestController at the class level. If you are also interested in learning more about effective handling of HTTP status code on RESTful web service, then I suggest you to join REST with Spring Masterclass by Eugen Paraschiv.




5. @PathVariable

One of the key difference between a REST URL and a normal URL is that REST uses part of URI to indicate the resource identifier instead of a query parameter. For example, in a REST API where you can create, read, update, or delete Tutorials, you can specify a tutorial like https://tutorials.com/tutorials/4321, here 4321 is resource identifier. 

If you want to write a controller handler method to find and return this resource then you need to extract the tutorialId=4321 and @PathVariable can do that for you. It can extract data from a Parameterized URL as shown below:

@RequestMapping(value="/{tutoriaId}" method=RequestMethod.GET)
public @ResponseBody Tutorial get(@PathVaraible long tutorialId){
   return tutorialRepository.find(tutorialId);
}

Here we have omitted the value attribute for @PathVariable because it same as value attribute in @RequestMapping annotation. This way you can retrieve part of URI inside handler method. You can learn about @PathVaraible on my post difference between @RequestParam and @PathVariable in Spring

That's all about some of the essential Spring MVC annotations for developing RESTful Web services using Spring framework. A good knowledge of these annotations goes a long way in writing better RESTful applications in quick time. If you want to learn these annotations in depth with some real world examples, The REST With Spring Masterclass is a good place to start with. 

Other Spring and REST resources and articles you may like

Thanks for reading this article so far. If you like these Spring MVC annotations and my explanation then please share with your friends and colleagues. If you have any questions or feedback then please drop a note. 

No comments:

Post a Comment