Quick revision
The short answer
We declare a @Bean of type RouterFunction<ServerResponse> built with RouterFunctions.route().GET("/persons/{id}", h::get).POST("/persons", h::create).build(), and put the request handling in a PersonHandler whose methods take a ServerRequest and return Mono<ServerResponse>. Compared with @RestController, the functional style makes routing explicit, plain code that is easy to compose and test, while the annotated style is more familiar and declarative; in the functional style validation and exception handling must be wired by hand. Spring MVC offers the same model as WebMvc.fn.
What to remember
In this answer, we wrote a functional WebFlux endpoint: a RouterFunction bean built with RouterFunctions.route() that maps GET /persons/{id} and POST /persons to a handler, whose methods read the path variable or body from ServerRequest and build responses with ServerResponse, using switchIfEmpty for 404. Compared with an annotated controller, the functional style is explicit, composable and easy to test with WebTestClient.bindToRouterFunction, while the annotated style is familiar and declarative. Validation and exception handling must be wired by hand in the functional style, and Spring MVC offers the same model as WebMvc.fn.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We declare a @Bean of type RouterFunction<ServerResponse> built with RouterFunctions.route().GET("/persons/{id}", h::get).POST("/persons", h::create).build(), and put the request handling in a PersonHandler whose methods take a ServerRequest and return Mono<ServerResponse>. Compared with @RestController, the functional style makes routing explicit, plain code that is easy to compose and test, while the annotated style is more familiar and declarative; in the functional style validation and exception handling must be wired by hand. Spring MVC offers the same model as WebMvc.fn.
Why this question is asked
Spring gives us two ways to write web endpoints, and many teams only know one of them. Functional endpoints appear in gateways, small services and code that builds routes dynamically, and they are a good test of whether we understand what the annotations normally do for us. Interviewers ask for this code because it shows we can read and write the request and response API directly, and because the comparison reveals what we lose and gain. In this answer, we will write the router and the handler, look at each line, compare the same endpoints as an annotated controller, add the validation and error handling the functional style needs, test it, and see the Spring MVC version.
1A Quick Recap of the Functional Model
In the functional model, also called WebFlux.fn, a request is handled by a HandlerFunction: a function that takes a ServerRequest and returns a Mono<ServerResponse>. A RouterFunction maps requests to handler functions, by method and path, and returns the handler for a matching request. We register the router as a bean, and Spring's DispatcherHandler consults it alongside any annotated controllers.
There is no reflection over annotations and no argument resolution. The handler reads the path variable, the query parameters or the body from the ServerRequest itself, and builds the response with ServerResponse's builder.
2Writing the Router and the Handler
The router declares the two routes and points them at methods of the handler. The handler does the work.
8 messages in order. Play them, or step through them one at a time.
Notice how get handles the missing case. findById returns an empty Mono when there is no person, so flatMap never runs, and switchIfEmpty substitutes a 404 response. That is the functional equivalent of returning ResponseEntity.notFound() from a controller.
In create, bodyToMono reads and decodes the JSON body without blocking, save returns the stored person with its id, and created sets the 201 status and the Location header in one call.
3The Same Endpoints as an Annotated Controller
Here is the annotated version for comparison.
The annotated style is declarative: the routes live next to the methods, and Spring converts the path variable and the body for us. It is what most Spring developers already know, and documentation tools understand it without help. Notice the @Valid: with annotations, validation is one word, and @ControllerAdvice handlers catch exceptions for every controller.
The functional style is explicit: all routes are visible in one place, they are ordinary values we can combine with and(), nest under a common path with nest() or path(), filter, and build conditionally, and handlers are plain methods with no framework magic, easy to unit test. The cost is that the conveniences the annotations provide must be wired by hand.
4Wiring Validation and Error Handling by Hand
In a functional handler, nothing validates the body unless we call a validator, and @ControllerAdvice does not apply to router functions. So we inject a Validator and handle errors in the router.
Notice that the error mapping is part of the router, so it is visible and local. For a service with many routers we would put the mapping in a shared filter or a global error handler instead of repeating it.
5Testing and the Spring MVC Version
Router functions are easy to test without starting a server, because WebTestClient can bind directly to them.
The MVC version lives in the org.springframework.web.servlet.function package and its handlers return ServerResponse directly instead of a Mono. So the choice between functional and annotated style is independent of the choice between MVC and WebFlux.
6Follow-up questions
Can annotated controllers and router functions live in the same application?
Yes. DispatcherHandler looks up handlers from both, and router functions are consulted first by default. Mixing them in one service is possible but makes cross-cutting concerns such as error handling and documentation harder to keep consistent, so most teams pick one style per service.
Why use switchIfEmpty rather than defaultIfEmpty in the handler?
defaultIfEmpty takes a plain value, while switchIfEmpty takes another publisher. ServerResponse.notFound().build() returns a Mono<ServerResponse>, so switchIfEmpty is the matching operator. In the annotated version, ResponseEntity.notFound().build() is a plain value, so defaultIfEmpty fits there.
How do I document router functions with OpenAPI?
springdoc-openapi cannot infer request and response types from a router, so we add @RouterOperation annotations, grouped with @RouterOperations, on the router bean, pointing at the handler class and method, or use springdoc's functional builder. Annotated controllers are documented automatically.
7Conclusion
In this answer, we wrote a functional WebFlux endpoint: a RouterFunction bean built with RouterFunctions.route() that maps GET /persons/{id} and POST /persons to a handler, whose methods read the path variable or body from ServerRequest and build responses with ServerResponse, using switchIfEmpty for 404. Compared with an annotated controller, the functional style is explicit, composable and easy to test with WebTestClient.bindToRouterFunction, while the annotated style is familiar and declarative. Validation and exception handling must be wired by hand in the functional style, and Spring MVC offers the same model as WebMvc.fn.
Open with
I'd define a configuration class with a bean of type RouterFunction of ServerResponse that takes the handler as a parameter and returns RouterFunctions.route(), then GET slash persons slash id mapped to handler get, POST slash persons mapped to handler create, then build.
Then, if they want more
The handler is a component with the reactive repository injected. get takes a ServerRequest, calls repo.findById with request.pathVariable id, flatMaps the person into ServerResponse.ok().bodyValue, and uses switchIfEmpty with ServerResponse.notFound().build() so a missing person becomes a 404. create does request.bodyToMono of Person, flatMaps into repo.save, and then returns ServerResponse.created with the location URI and the saved body, so a 201 with a Location header.
Compared with an annotated controller, the functional style makes routing explicit code: all routes in one place, composable with nest, filters and conditions, and handlers are plain methods that are easy to test, for example with WebTestClient.bindToRouterFunction.
The annotated style is more familiar and declarative, Spring resolves path variables and bodies for you, @Valid validates the body and @ControllerAdvice handles exceptions. In the functional style I have to call a Validator myself and map exceptions in the router with onError or a filter, and for OpenAPI I need @RouterOperation annotations.
And it's not tied to WebFlux: Spring MVC has the same model, WebMvc.fn, where handlers return a ServerResponse directly.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Spring WebFlux, Project Reactor reference guide
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a WebFlux functional endpoint that routes GET /persons/{id} and POST /persons to a...": https://scrivio-interview-library.netlify.app/spring-boot/webflux/012e557949/