Ronnie
Ronnie

Reputation: 302

WebFlux Swagger (Open API) integraton - Post Request sample

I have integrated Swagger (OpenAPI) with Spring Webflux as mentioned here: https://springdoc.org/#spring-weblfuxwebmvcfn-with-functional-endpoints using RouterOperation. The integration works fine and is accessible at /swagger-ui.html

However, for POST APIs, I am not seeing the "Request" sample when I click on "Try it out" button. My Post API accepts a Json as Request Body.

How do I configure this ? Can that be done via Annotations along with RouterOperation or something else ?

Edit: Below is my Router class code:

@Configuration
public class  MyRouter {

    @RouterOperations({
            @RouterOperation(path = "/data", beanClass = MyHandler.class, beanMethod = "getData"),
            @RouterOperation(path = "/allData", beanClass = MyHandler.class, beanMethod = "getAllData") })

    @Bean
    public RouterFunction<ServerResponse> route(MyHandler MyHandler) {

        return RouterFunctions
                .route(RequestPredicates.POST("/data").and(RequestPredicates.accept(MediaType.APPLICATION_JSON)), MyHandler::getData)
                .andRoute(RequestPredicates.GET("/allData").and(RequestPredicates.accept(MediaType.APPLICATION_JSON)), MyHandler::getAllData);
    }
}

Upon adding RouterOperations annotation I can see the swagger-ui showing both the GET and POST APIs correctly but not the request schema sample.

I also came across yaml / json file to describe this. But I am not getting where to put this file in my application so that swagger-ui uses it.

Upvotes: 2

Views: 3357

Answers (1)

Ronnie
Ronnie

Reputation: 302

Finally found it

Using @Operation and @Schema, can define the class that is required as input in request body. This will be shown as sample json structure in Swagger-ui. No other configuration required.

@RouterOperations({
            @RouterOperation(
                    path = "/data", beanClass = MyHandler.class,  beanMethod = "getData",
                    operation = @Operation(
                            operationId = "opGetData",
                            requestBody = @RequestBody(required = true, description = "Enter Request body as Json Object",
                                                content = @Content(
                                                        schema = @Schema(implementation = ApiRequestBody.class))))),
            @RouterOperation(path = "/allData", beanClass = MyHandler.class, beanMethod = "getAllData")})

@Bean
    public RouterFunction<ServerResponse> route(MyHandler myHandler) {

        return RouterFunctions
                .route(RequestPredicates.POST("/data").and(RequestPredicates.accept(MediaType.APPLICATION_JSON)), myHandler::getData)
                .andRoute(RequestPredicates.GET("/allData").and(RequestPredicates.accept(MediaType.APPLICATION_JSON)), myHandler::getAllData);
    }

Upvotes: 8

Related Questions