Search code examples
spring-bootrestswaggeropenapi

How can I override the Requestbody ExampleValue and Schema in my Swagger OpenApi Doc?


I wrote a REST- Api in Springboot (3.2.2) and I am trying to create a fully customized Swagger OpenApi(3.0). Due to some api-requirements the RequestBody in my controller method can not be the dto-class to which the incoming json is mapped later on in the code. I still want the dto-class to be the "ExampleValue" and "Schema" in my Swagger Documentation.

My Controller:

public ResponseEntity<Object> createSaveObjects(@RequestBody String json) {...}

To customize my documentation I use a SpringdocConfig - Class:

    @OpenAPIDefinition
    @Configuration

public class SpringdocConfig {

    @Bean
OpenAPI baseOpenAPI() {

    OpenAPI openAPI = new OpenAPI();

    // Info
    Info info = new Info()
            .title("Documentation")
            .description("blubb")
            .version("1.0.0");
    openAPI.setInfo(info);


    // Paths
    Paths paths = new Paths();
    paths.addPathItem("/object", new PathItem()
            .post(new Operation()
                    .summary("saves objects")
                    .description("saves objects")
                    .requestBody(new RequestBody()
                            .description("blibb")
                            .required(true)
                            .content(new Content()
                                    .addMediaType("application/json", new io.swagger.v3.oas.models.media.MediaType()
                                            .schema(new Schema()
                                                    .type("object")
                                                    .addProperty("Name", new Schema().type("string").example("string"))
                                                    .addProperty("Origin", new Schema().type("int").example(4))
                                                    
                                            )...

What I want:

    Request body

application/json
blibb

Example Value
{
  "Name": "string",
  "Origin": 4
}

What I get:

  Request body

application/json
blibb

Example Value
"string"

Solution

  • I solved it myself: I just added the @Hidden annotation to the POST-Method in the Controller so Swagger fully ignors it for the Documentation

    @Hidden
    @PostMapping
    public ResponseEntity<Object> createSaveObjects(@RequestBody String json) {...}