Routing is often described as the process of mapping URLs to their corresponding endpoints. However, this description often fails to capture the true underlying complexity of this process. In this article, we will discuss how the Spring Routing framework can be used to implement an API that supports various routes to different endpoints.

REST is the most widely used architecture for building HTTP APIs. It is lightweight and simple, but not necessarily flexible or scalable (of course, some of the other benefits of REST also apply here). WebFlux is a lightweight and flexible alternative that, although still not as fast as the other frameworks, is still very easy to use.

REST is a popular architectural style used to describe APIs and other web-based services. Spring WebFlux is a framework that makes developing RESTful web applications a breeze. If you’re looking to develop a simple RESTful API using the WebFlux framework, read this tutorial to learn how to build a simple JSON API using Spring WebFlux.

This tutorial is the fifth in a series of lessons on reactive programming in Java and the Spring Framework. In this tutorial, we will develop a simple REST API with Spring Web flow. To fully understand this tutorial, you must have studied the previous tutorial and know how to develop a REST controller in blocking mode (unresponsive) with Spring Framework.

Web Reactive Battery

The following figure, taken from the Spring Webflux documentation, shows how the Spring Web Reactive stack differs from and resembles the Spring MVC stack. word-image-1589

Practice code

The REST API we are going to create is a simple CRUD API that will be responsible for interacting with the books stored in MongoDB. We will use Maven as a dependency management tool. The structure of the project is shown below: word-image-1590 Here is the pom.xml file I used for the project: 4.0.0 org.springframework.boot spring-boot-starter-parent 2.5.0 com.sergey reactive_api 0.0.1 reactive_api demo project for spring boot 1.8 org.projectlombok lombok 1.18.20 org.springframework.boot spring-boot-starter-data-mongodb-reactive org.springframework.boot spring-boot-starter-webflux the.flapdoodle.embed the.flapdoodle.embed.mongo org.springframework.boot spring-boot-maven-plugin To limit the number of configurations, we will use MongoDB in memory. It is provided by the flapdoodle project library.


The book entity will be the only entity in the model. Let’s assume for the sake of convenience that every book has an author. @Document @Data @NoArgsConstructor public class Book { @Id private String id; private String name; private String author ; public Book(String name, String author) { = name; = author; } } The Lombok project was used to reduce the number of code models.


I’m a big fan of SOLID principles, so let’s make them abstractions. There will be an interface for the service and the implementation of the service.


public interface BookService { Mono getBookById(String id) ; The getAllBooks() thread; Mono DeleteBookToId(String id) ; Mono deleteAllBooks() ; Mono createBook(Book) ; Mono updateBook(Book book); }


@Service public class BookServiceImple implements BookService { private final BookRepository bookRepository ; public BookServiceImpl(BookRepository bookRepository) { this.bookRepository = bookRepository ; } private Book formatBook(Book Book) { book.setName(book.getName().toLowerCase()); book.setAuthor(book.getAuthor().toUpperCase()); return book; } @Override public Mono getBookById(String id) { return bookRepository.findById(id) .map(this::formatBook); } @Override public Flux getAllBooks() { return bookRepository.findAll().map(this::formatBook); } @Override public Mono deleteBookById(String id) { return bookRepository.deleteById(id); } @Override public Mono deleteAllBooks() { return bookRepository.deleteAll(); } @Override public Mono createBook(Book book book) { if (book.getId() != null) { return Mono.error(new IllegalArgumentException(Id of new book must be null)); } return; } @Overridepublic Mono updateBook(Book book) {return bookRepository.existsById(book.getId()).flatMap(isExisting ->{if (isExisting) {return;} else {return Mono.error(new IllegalArgumentException(The book id must exist for the update to take place));}});} The implementation class can be extended with additional logic if necessary.

Recovery controller

When using Spring Webflux, there are two ways to create a controller:

1) Use annotations as in Spring MVC.

This is the easiest method for those familiar with Spring MVC. Here is the controller class with all the CRUD methods: @RestController @RequestMapping(/v1/annotated/books) public class AnnotationController { private final BookService bookService ; public AnnotationController(BookService bookService) { this.bookService = bookService; } @GetMapping public Flux getAllBooks() { return bookService.getAllBooks(); } @GetMapping(/{id}) public Mono getBookById(@PathVariable String id) { return bookService.getBookById(id); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public Mono createBook(@RequestBody Book book) { return bookService.createBook(book); } @PutMapping public Mono updateBook(@RequestBody Book book book) { return bookService.updateBook(book); } @DeleteMapping(/{id}) public Mono deleteBookById(@PathVariable String id) { return bookService.deleteBookById(id); } @DeleteMapping public Mono deleteAllBooks() { return bookService.deleteAllBooks(); } }

2) Use of functional criteria

These endpoints are created in a functional programming style. This means he uses lambda expressions a lot. This method is simpler than the annotation method because it uses the same Reactive Core Foundation. It uses a functional programming model in which functions are used to route and process requests. @Configuration @EnableWebFlux public class FunctionalController { private static String BASE_URL = /v1/functional/books; private final BookService bookService ; public FunctionalController(BookService bookService) { this.bookService = bookService; } @Bean public RouterFunction getAllBooks() { return RouterFunctions.route() .GET(BASE_URL, request -> ServerResponse.ok().body(bookService.getAllBooks(), Book.class).build(); } @Bean public RouterFunction getBookById() { return RouterFunctions.route() .GET(BASE_URL.concat(/{id}), request -> { String id = request.pathVariable(id); return ServerResponse.ok().body(bookService.getBookById(id), Book.class); }).build(); } @Bean public RouterFunction createBook() { return RouterFunctions.route() .POST(BASE_URL, request -> request.bodyToMono(Book.class) .flatMap(bookService::createBook) .flatMap(book -> ServerResponse.status(HttpStatus.CREATED) .body(book, Book.class)) .build(); } @Bean public RouterFunction updateBook() { return RouterFunctions.route() .PUT(BASE_URL, request -> request.bodyToMono(Book.class) .flatMap(bookService::updateBook) .flatMap(book -> ServerResponse.ok() .body(book, Book.class)) .build(); } @Bean public RouterFunction deleteBookById() { return RouterFunctions.route() .DELETE(BASE_URL.concat(/{id}), request -> { String id = request.pathVariable(id); return ServerResponse.ok().body(bookService.deleteBookById(id), Void.class); }).build(); } @Bean public RouterFunction deleteAllBooks() { return RouterFunctions.route() .DELETE(BASE_URL, request -> ServerResponse.ok() .body(bookService.deleteAllBooks(), Void.class)).build(); } } The class RouterFunction represents the main entry point of the query when we use a functional style. It accepts the request and returns a response, wrapped in a class ServerResponse. It can be considered the equivalent of query mappings and associated methods when using the annotated style. The RouterFunctions class is a class used to build RouterFunctions according to the Builder model. We use it to specify the structure of the request and how the request is used to form the response. You can read in detail how this works in the RouterFunctions section of the Webflux documentation. You can test the application by adding a bootstrap class that loads some data into the database, then use POSTMAN or a similar tool to test different endpoints. @Component @Slf4j public class Bootstrap implements CommandLineRunner { private final BookRepository bookRepository ; public Bootstrap(BookRepository bookRepository) { this.bookRepository = bookRepository; } @Override public void run(String… args) throws Exception { Book book1 = new Book(Docker In Action, Florian Lowe); Book book2 = new Book(Java Best Practices, Sergey); Book book3 = new Book(Reactive Programming in C#, Satoshi Nakamoto) ; bookRepository.saveAll(Arrays.asList(book1, book2, book3)).subscribe(book -> books with name : {}, book.getName());} This is the end of this manual. You can now use Spring Webflux to work on different projects. I hope this was helpful. Until the next lesson.Have you ever had the experience of writing a RESTful API for your application or business? Most business applications or applications in general tend to have a primary data layer and a secondary data layer. The data layer may contain data that you are trying to access from a client application. The primary data layer is the data that the business application is trying to access. A RESTful API is a technology that you can use to interact with this data layer. The primary data layer can be distributed across several servers, and the RESTful API allows clients to access this data across the network.. Read more about spring webflux crud example and let us know what you think.

Frequently Asked Questions

What type of API is spring WebFlux?

WebFlux is an API-first framework that makes it easier to build REST APIs using Spring Boot. WebFlux provides a lightweight, minimalist API layer so that you can focus on the business logic (the logic that you need to write in your code to make a request to a web service, and all the logic necessary to create and return a response to the client). Most of the time, when you see a bunch of APIs, you immediately think of a REST API. This is a built-in API that allows you to interact with different types of data with a HTTP GET request. However, there are other types of APIs, like event-based APIs (also known as reactive APIs), which are based on your data and feed your app’s UI based on changes to that data.

How do I create a spring REST API?

REST APIs are a popular choice for creating web services because it is a standard way to develop a web application. However, REST APIs have their limitations. For example, if you have a RESTful API that is used by multiple applications, how do you ensure that they remain consistent and do not conflict with each other? Furthermore, how do you share state across requests? Spring WebFlux is a lightweight and efficient alternative to REST and SOAP architecture, which is good news if you’re unfamiliar with the concepts. This guide to using Spring WebFlux will have you up and running with a RESTful API quickly.

How do I use WebFlux in spring boot?

WebFlux is a new Spring framework designed to be a faster alternative to Spring MVC. It was introduced in the Spring 2016 and is said to be the fastest way to develop a REST API. So in this blog, I would like to share how I use WebFlux in spring boot so that you can get started faster with any REST API you want to build using spring boot. Recently, while working on my Geospatial Application, I had to define a new REST service to interact with some legacy systems I was working with. I decided to use the WebFlux API since I was familiar with the framework. I started to write the code to interact with the system and found that I had a few issues with my code, namely it was very long and looked very ugly. Due to my grumpy mood, I decided to fix my code and create a simple REST API. I created a simple Spring Boot project with a simple REST service that retrieves a list of locations.

spring-webflux-example githubspring webflux crud examplespring-boot-starter-webfluxspring webflux vs spring mvcspring-webflux mavenbuild reactive restful apis using spring boot/webflux,People also search for,Feedback,Privacy settings,How Search works,Hands‑On Reactive Programm…,Reactive Programm… With Java…,Reactive Spring,Cloud Native Java: Designing…,Learning Spring Boot 2.0: Simpli…,Hands‑On Spring Security 5…,See more,build reactive restful apis using spring boot/webflux,build reactive restful apis using spring boot/webflux free download,spring-webflux-example github,spring webflux crud example,spring-boot-starter-webflux,spring-boot-starter-webflux vs spring-boot-starter-web,spring webflux vs spring mvc,spring-webflux maven