Sub topic 8
Functional endpoints with RouterFunction
This chapter shows how to define HTTP endpoints as plain functions instead of annotated methods. The earlier chapter covered annotated controllers. Here you build the same kind of API with RouterFunction and HandlerFunction.
What this chapter assumes
- You can write a
Mono/Fluxpipeline withmap,flatMap, andswitchIfEmpty. - You have built an annotated controller in WebFlux.
- You have a
Bookclass with agetId()method. You also have aBookRepositorythat extendsReactiveCrudRepository<Book, String>. Both come from the earlier examples.
Two functions instead of one annotation
An annotated controller mixes routing (@GetMapping("/{id}")) and logic (the method body) in one place. The functional model splits them into two parts.
- A
HandlerFunction<ServerResponse>takes aServerRequestand returns aMono<ServerResponse>. It holds the logic. - A
RouterFunction<ServerResponse>takes aServerRequestand returns aMono<HandlerFunction>. It decides which handler applies, if any.
Both are ordinary functional interfaces. You can build, combine, and test them without reflection or annotation scanning. The router is a value you declare as a Spring bean. The runtime picks up every RouterFunction bean and uses it to dispatch requests.
A first endpoint
The routes and the handler go in separate classes.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
@Configuration
public class BookRoutes {
@Bean
RouterFunction<ServerResponse> bookRoutes(BookHandler handler) {
return RouterFunctions.route()
.GET("/fbooks/{id}", handler::get)
.build();
}
}
@Component
class BookHandler {
private final BookRepository repository;
BookHandler(BookRepository repository) {
this.repository = repository;
}
Mono<ServerResponse> get(ServerRequest request) {
return repository.findById(request.pathVariable("id"))
.flatMap(book -> ServerResponse.ok().bodyValue(book))
.switchIfEmpty(ServerResponse.notFound().build());
}
}The handler method has the shape ServerRequest -> Mono<ServerResponse>, so handler::get is a valid HandlerFunction.
The get pipeline reads in three steps:
findByIdyields aMono<Book>.flatMapturns a found book into aMono<ServerResponse>. It usesflatMapbecause building a response returns aMono, not a plain value.switchIfEmptyruns only when the repository found nothing, and it supplies the 404.
How a request reaches your handler
The router tests its routes in the order you declared them. The first route whose predicate matches wins. If none match, the result is empty and WebFlux answers 404.
Predicates
A route is a RequestPredicate plus a handler. GET("/fbooks/{id}", ...) combines a method check and a path check. You can add more conditions with the static methods on RequestPredicates.
| Predicate | Matches when |
|---|---|
| `GET(pattern)`, `POST(pattern)`, and so on | The HTTP method and path pattern match |
| `accept(mediaType)` | The `Accept` header allows the media type |
| `contentType(mediaType)` | The `Content-Type` header equals the media type |
| `queryParam(name, predicate)` | A query parameter exists and satisfies the check |
| `headers(predicate)` | A custom check on the headers passes |
You can combine predicates with and, or, and negate. The builder methods also take a predicate in front of the handler.
Grouping routes and ordering them
Repeating /fbooks on every route gets tedious. The path method nests routes under a shared prefix. The routes below also show predicates and the other HTTP methods.
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RequestPredicates.contentType;
import org.springframework.http.MediaType;
@Bean
RouterFunction<ServerResponse> bookRoutes(BookHandler handler) {
return RouterFunctions.route()
.path("/fbooks", builder -> builder
.GET("/{id}", handler::get)
.GET(accept(MediaType.APPLICATION_JSON), handler::list)
.POST(contentType(MediaType.APPLICATION_JSON), handler::create))
.build();
}Because the first match wins, put specific routes before general ones. Suppose you add GET("/{id}") before GET("/search"). Then /search is captured by the {id} route with id set to search.
Reading requests and building responses
ServerRequest gives access to the parts of a request.
request.pathVariable("id")returns the path variable as aString.request.queryParam("title")returns anOptional<String>.request.bodyToMono(Book.class)andrequest.bodyToFlux(Book.class)decode the body.request.headers()exposes the headers.
ServerResponse uses a builder. You choose the status, add headers, and then call a body method.
bodyValue(object)sends one value you already have.body(publisher, Class)sends aMonoorFluxand keeps it non-blocking.
Here are the two handlers that go with the routes above:
Mono<ServerResponse> list(ServerRequest request) {
return ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(repository.findAll(), Book.class);
}
Mono<ServerResponse> create(ServerRequest request) {
return request.bodyToMono(Book.class)
.flatMap(repository::save)
.flatMap(saved -> ServerResponse
.created(java.net.URI.create("/fbooks/" + saved.getId()))
.bodyValue(saved));
}The body(publisher, Class) call needs the element class so the encoder can pick the right serializer despite type erasure. create reads the request body, saves it, and answers 201 Created with a Location header. Nothing runs until the framework subscribes to the returned Mono<ServerResponse>.
Filters and error handling
The builder can attach cross-cutting behavior to a group of routes. This is similar to what @ControllerAdvice and servlet filters do for annotated code.
@Bean
RouterFunction<ServerResponse> bookRoutes(BookHandler handler) {
return RouterFunctions.route()
.path("/fbooks", builder -> builder
.GET("/{id}", handler::get)
.POST(contentType(MediaType.APPLICATION_JSON), handler::create))
.filter((request, next) -> {
System.out.println(request.method() + " " + request.path());
return next.handle(request);
})
.onError(IllegalArgumentException.class, (ex, request) ->
ServerResponse.badRequest().bodyValue(ex.getMessage()))
.build();
}filterwraps every route declared before it on that builder. Callnext.handle(request)to continue, or return a response directly to stop the request, for example when authentication fails.onErrormaps an exception type to a response. It handles errors signaled in theMonoand exceptions thrown while the handler runs.
Prefer onError for failures that have a clear HTTP meaning. Without a mapping, an unhandled exception becomes a 500.
Annotated or functional?
Both models run on the same runtime and use the same Mono and Flux types. Pick based on how you want to structure code.
| Question | Annotated controllers | Functional endpoints |
|---|---|---|
| Where is routing declared? | On each method, by annotations | In one place, as code |
| Argument binding and validation | Automatic (`@RequestBody`, `@Valid`) | Manual, through `ServerRequest` |
| Return values | `Mono<Book>`, `Flux<Book>` | Always `Mono<ServerResponse>` |
| Dynamic routes | Hard | Easy, since routes are values |
| Familiarity for Spring MVC teams | High | Lower |
You can mix both styles in one application. Their paths must not collide.
Common errors
- Forgetting that nothing runs without a subscriber. A handler that builds a pipeline but returns a different
Monodrops the work silently. Return the pipeline you built. - Using
mapwhereflatMapis needed.map(book -> ServerResponse.ok().bodyValue(book))produces aMono<Mono<ServerResponse>>, which does not compile as a handler result. UseflatMap. - Blocking inside a handler. Calling
.block()or a blocking client there stalls an event-loop thread. Move blocking work to a scheduler, as covered in the threading chapter. - Route order. A broad pattern placed first hides narrower ones that follow it.
- A missing
Content-Type. If aPOSTroute requirescontentType(APPLICATION_JSON)and the client omits the header, the predicate fails and the request gets 404 or 415 instead of reaching your handler. - Passing a plain value to
body(...).bodyexpects aPublisher. UsebodyValuefor a single object.
Exercise
A router declares GET("/fbooks/{id}", handler::get) first and GET("/fbooks/featured", handler::featured) second. A client calls /fbooks/featured. Which handler runs, and how do you fix the order?
Show answer
The get handler runs, with id set to "featured", because the first matching route wins. Put the /fbooks/featured route before /fbooks/{id} so the specific route is tested first.
Exercise
Why does this handler fail to compile, and what is the fix? return repository.findById(id).map(book -> ServerResponse.ok().bodyValue(book));
Show answer
bodyValue returns a Mono<ServerResponse>, so map produces a Mono<Mono<ServerResponse>>. A handler must return Mono<ServerResponse>. Replace map with flatMap.