{"id":95,"date":"2021-04-28T17:37:32","date_gmt":"2021-04-28T17:37:32","guid":{"rendered":"https:\/\/tejasgarde.dev\/?p=95"},"modified":"2021-04-28T17:37:32","modified_gmt":"2021-04-28T17:37:32","slug":"spring-webflux-rest-controller-part-2","status":"publish","type":"post","link":"https:\/\/tejasgarde.dev\/index.php\/2021\/04\/28\/spring-webflux-rest-controller-part-2\/","title":{"rendered":"Spring WebFlux REST Controller &#8211; Part-2"},"content":{"rendered":"\n<p>In order to understand  Spring WebFlux more deeply we will implement a simple REST end-point  for User. This User end-point as of now will have following REST action.<\/p>\n\n\n\n<div class=\"wp-container-1 wp-block-group\"><div class=\"wp-block-group__inner-container\">\n<figure class=\"wp-block-table is-style-stripes\"><table><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\">HTTP Method<\/td><td>URI<\/td><td>Response<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">GET<\/td><td>\/v1\/users<\/td><td>UserResposne<\/td><\/tr><\/tbody><\/table><figcaption>GET Method<\/figcaption><\/figure>\n<\/div><\/div>\n\n\n\n<h2>Creating Spring Boot WebFlux Application<\/h2>\n\n\n\n<p>So first we will have to create Spring WebFlux application. Its simple to stat with , just go <a rel=\"noreferrer noopener\" href=\"https:\/\/start.spring.io\/\" target=\"_blank\">here<\/a> and fill up Project metadata and in dependencies  use <strong>Spring Reactive Web<\/strong>. This will generate a folder with requires pom.xml and other Spring WebFlux dependencies . Once you download it , extract and import it in your favourite IDE . Make sure the pom.xml file has following dependency .<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-webflux&lt;\/artifactId&gt;<br>&lt;\/dependency&gt;<\/pre>\n\n\n\n<h2>Creating REST Controller<\/h2>\n\n\n\n<p>All is set up for us to create Controller . But before writing controller code directly , let&#8217;s just first <em>take a moment and understand what are the information we are going to need<\/em> <em>to implement the controller <\/em>. So we already know few things , and these are <\/p>\n\n\n\n<ul><li>We need REST End Point for Users<\/li><li>We have to use HTTP GET Method <\/li><li>We Know Path\/URI for this HTTP GET Method<\/li><li>We Know what to send in Response.<\/li><\/ul>\n\n\n\n<p>Now we need to implement above functionality in Spring WebFlux application, Spring provides annotation for all of the above requirement , we just have to implement it in correct way.  So here are those annotation in Spring Reactive Web Provides  <\/p>\n\n\n\n<ul><li><strong>@RestController<\/strong> for REST End Point for Users    <\/li><li><strong>@GetMapping <\/strong>for HTTP GET Method<\/li><li><strong>@RequestMapping<\/strong> for  Path\/URI for this HTTP GET Method<\/li><li><strong>@ResponseBody<\/strong> to send in Response.<\/li><\/ul>\n\n\n\n<p>Lest understand what each of this annotation do.<\/p>\n\n\n\n<h2><strong>@RestController<\/strong><\/h2>\n\n\n\n<p>@RestController is composed annotation. It is composed of @Controller and @ResponseBody annotations.   @Controller defines bean as controller whereas @ResponseBody indicates that every method this bean writes directly to the response body . The @RestController annotation is applied at the top of the class . <\/p>\n\n\n\n<h2><strong>@GetMapping<\/strong><\/h2>\n\n\n\n<p> @GetMapping annotation is type of request mapping annotation that gets invoked when GET HTTP method is called . We can also use @RequestMapping annotation here like this <\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>@RequestMapping<\/strong>(method = RequestMethod.<em>GET<\/em>)<\/pre>\n\n\n\n<h2><strong>@RequestMapping<\/strong><\/h2>\n\n\n\n<p>@RequestMapping annotation maps the incoming request for the given URI to the particular endpoint . In our case we need to point all the request (irrespective of HTTP Method) to our controller , so we will declare this annotation at top of the Controller class mentioning the URI.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>@RequestMapping<\/strong>(<em>USER_API_V1<\/em>+<em>SLASH<\/em>+<em>USERS<\/em>)<\/pre>\n\n\n\n<p>where values in parenthesis is the URI in our case it is &#8220;\/v1\/users&#8221; indicating its version-1 of the API with endpoint &#8220;users&#8221;. The same @RequestMapping annotation can also be used along with HTTP method above functions to define the routing as mentioned above.<\/p>\n\n\n\n<h2><strong>@ResposneBody<\/strong><\/h2>\n\n\n\n<p>@ResposneBody annotation adds the return type of the method where it is declared to the repose body of the request. It is defined at the top of controller methods. In Simple word if the method is returning String , then response of that endpoint will be String. <\/p>\n\n\n\n<p>With above annotations knowledge lets create a controller with String as @ResposneBody.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>@RestController<br><\/strong><strong>@RequestMapping<\/strong>(<em>USER_API_V1<\/em>+<em>SLASH<\/em>+<em>USERS<\/em>)<br>public class UserController {<br>  <strong>@GetMapping<br><\/strong><strong>  <\/strong>public String getValue(){<br>    return <strong>\"Hello World\"<\/strong>;<br>  }<br>}<\/pre>\n\n\n\n<p>If you run the Spring application with above controller we will get response in browser for GET HTTP call on http:\/\/localhost:8080\/v1\/users as <strong>&#8220;Hello World&#8221;<\/strong> .  <\/p>\n\n\n\n<p>Till now its exactly similar to how we do it in Spring MVC\/Boot  and we have not yet used any of the WebFlux feature, in order to use it , lets enhance the application and add Service layer for User and return UserResponse object. <\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>@Service<br><\/strong>public class UserServiceImpl implements UserService {<br>  <strong>@Override<br><\/strong><strong>  <\/strong>public Flux&lt;UserResponse&gt; getAllUsers() {<br>    return Flux.<em>fromIterable<\/em>(generateUsers());<br>  }<br><br>  private List&lt;UserResponse&gt; generateUsers() {<br>    return Arrays.<em>asList<\/em>(UserResponse.<em>builder<\/em>()<br>            .userId(1)<br>            .userName(<strong>\"User-1\"<\/strong>)<br>            .build(),<br>        UserResponse.<em>builder<\/em>()<br>            .userId(2)<br>            .userName(<strong>\"User-3\"<\/strong>)<br>            .build(),<br>        UserResponse.<em>builder<\/em>()<br>            .userId(3)<br>            .userName(<strong>\"User-3\"<\/strong>)<br>            .build(),<br>        UserResponse.<em>builder<\/em>()<br>            .userId(4)<br>            .userName(<strong>\"User-4\"<\/strong>)<br>            .build());<br>  }<br>}<\/pre>\n\n\n\n<h2><strong>Flux and Mono in Reactive Spring<\/strong><\/h2>\n\n\n\n<p>As you can see we have <strong>UserServiceImpl<\/strong> class which has getAllUsers() method that Returns <strong>Flux&lt;UserResposne&gt;<\/strong>. Since we are returning the more than 1 entity in response we will have to use the <strong>Flux<\/strong> of that entity. <\/p>\n\n\n\n<p>There are 2 Types of Publisher in Spring , <strong>Mono and Flux<\/strong>. Mono is a Publisher that produces 0 to 1 value . Flux is publisher that produces 0 to N values. As of now just keep in mind that we want to return more than 1 UserResposne entity we are using Flux. When we will use endpoint to get single entity of UserResposne that time we will use Mono. More on Flux and Mono in upcoming post.<\/p>\n\n\n\n<h2><strong>Final Controller Code <\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>@RestController<br><\/strong><strong>@RequestMapping<\/strong>(<em>USER_API_V1<\/em>+<em>SLASH<\/em>+<em>USERS<\/em>)<br>public class UserController {<br>  <strong>@Autowired<br><\/strong><strong>  <\/strong>private UserService userService;<br><br>  <strong>@GetMapping<br><\/strong><strong>  <\/strong>public Flux&lt;UserResponse&gt; getValue(){<br>    return userService.getAllUsers();<br>  }<br>}<\/pre>\n\n\n\n<p>When you run this application using postman with url <strong>http:\/\/localhost:8080\/v1\/users<\/strong> the you should see the following response<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"664\" height=\"639\" src=\"https:\/\/tejasgarde.dev\/wp-content\/uploads\/2021\/04\/Spring-GET.png\" alt=\"\" class=\"wp-image-87\" srcset=\"https:\/\/tejasgarde.dev\/wp-content\/uploads\/2021\/04\/Spring-GET.png 664w, https:\/\/tejasgarde.dev\/wp-content\/uploads\/2021\/04\/Spring-GET-300x289.png 300w\" sizes=\"(max-width: 664px) 100vw, 664px\" \/><figcaption>GET Request Response<\/figcaption><\/figure>\n\n\n\n<p>Now we are done with first part of Spring WebFlux tutorial. There are lot more things to learn and things are getting super exited, we have just started. <br><\/p>\n\n\n\n<p>The Code for above you can find it here at <a href=\"https:\/\/github.com\/tejasgrd\/spring-webflux-examples\" target=\"_blank\" rel=\"noopener\">GitHub<\/a>.  <\/p>\n\n\n\n<p>Thank You \ud83d\ude4f <\/p>\n","protected":false},"excerpt":{"rendered":"<p>In order to understand Spring WebFlux more deeply we will implement a simple REST end-point for User. This User end-point as of now will have following REST action. HTTP Method URI Response GET \/v1\/users UserResposne GET Method Creating Spring Boot WebFlux Application So first we will have to create Spring WebFlux application. Its simple to &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/tejasgarde.dev\/index.php\/2021\/04\/28\/spring-webflux-rest-controller-part-2\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Spring WebFlux REST Controller &#8211; Part-2&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[],"_links":{"self":[{"href":"https:\/\/tejasgarde.dev\/index.php\/wp-json\/wp\/v2\/posts\/95"}],"collection":[{"href":"https:\/\/tejasgarde.dev\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tejasgarde.dev\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tejasgarde.dev\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tejasgarde.dev\/index.php\/wp-json\/wp\/v2\/comments?post=95"}],"version-history":[{"count":2,"href":"https:\/\/tejasgarde.dev\/index.php\/wp-json\/wp\/v2\/posts\/95\/revisions"}],"predecessor-version":[{"id":97,"href":"https:\/\/tejasgarde.dev\/index.php\/wp-json\/wp\/v2\/posts\/95\/revisions\/97"}],"wp:attachment":[{"href":"https:\/\/tejasgarde.dev\/index.php\/wp-json\/wp\/v2\/media?parent=95"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tejasgarde.dev\/index.php\/wp-json\/wp\/v2\/categories?post=95"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tejasgarde.dev\/index.php\/wp-json\/wp\/v2\/tags?post=95"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}