11

Have the following method of Controller:

    @ApiResponses(value = {@ApiResponse(responseCode = "200")})
    @GetMapping(value = API_URI_PREFIX + PRODUCTS_URI, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public Flux<Product> getProducts(@Valid @NotNull PagingAndSorting pagingAndSorting) {
   }

I need to find a way how to show in Swagger example of PagingAndSorting object.

I am using springdoc-api v1.4.3.

user471011
  • 7,104
  • 17
  • 69
  • 97

4 Answers4

14

You can use @ExampleObject annotation.

Note that you can also in the examples use the ref @ExampleObject(ref="..."), if you want to reference an sample existing object. Or ideally, fetch the examples from external configuration file and add them using OpenApiCustomiser, like it's done in this test:

Here is sample code using @ExampleObject:

@PostMapping("/test/{id}")
public void testme(@PathVariable("id") String id, @RequestBody(content = @Content(examples = {
        @ExampleObject(
                name = "Person sample",
                summary = "person example",
                value =
                        "{\"email\": test@gmail.Com,"
                                + "\"firstName\": \"josh\","
                                + "\"lastName\": \"spring...\""
                                + "}")
})) PersonDTO personDTO) { }

If you are using the @RequestBody Spring annotation in the controller you need to differentiate the two, for example by using @io.swagger.v3.oas.annotations.parameters.RequestBody for the Swagger annotation. This prevents the null param problem mentioned in the comments below.

brianbro
  • 4,141
  • 2
  • 24
  • 37
  • What is "content" in @RequestBody(content = ....)? Doesn't compile. – catch22 Dec 19 '20 at 13:05
  • OK. I tried to use import io.swagger.v3.oas.annotations.parameters.RequestBody; Now it compiles, but RequestBody argument does not work. Value of param (variable) = null. – catch22 Dec 19 '20 at 13:32
  • @brianbro - do you have example on how to fetch external configuration file as ExampleObject's value?. Tried this but not working: test(@Valid @RequestBody(content = @Content(examples = {@ExampleObject(name = "Example Body", summary = "Example Body", ref = "exampleFile.json") where exampleFile.json is on my src/main/resource folder – Chris Landeza Mar 22 '22 at 08:00
  • If I use this - @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(examples = { @ExampleObject( name = "Person sample", summary = "person example", value = "{"email": test@gmail.Com," + ""firstName": "josh"," + ""lastName": "spring..."" + "}") })) I get below exception - no viable alternative at input ',@io.swagger.v3.oas.annotations.parameters.RequestBody(content=@Content(examples={@ExampleObject(name="Person sample",summary="person example",value="{\"email\": test@gmail.Com,"+"\"firstName\": \"josh\","+"\"lastName\": \"spring...\""+"}")})))': NoViableAltException – Rabin Mallilck Mar 30 '22 at 02:20
  • Is there any way to add the resources file content to the `@ExampleObject`? I am trying to add the `@ExampleObject` from the `resources file` using `ref` but its not working for some reason. I have posted my question: stackoverflow.com/q/71616547/7584240 – BATMAN_2008 Mar 30 '22 at 20:30
  • Don't forget to include the `name` attribute when using the `ref` in the `@ExampleObject`. The examples are defined as a map in the swagger.json. – Ivan Apr 14 '22 at 20:36
  • 1
    link expired https://github.com/springdoc/springdoc-openapi/blob/master/springdoc-openapi-webmvc-core/src/test/java/test/org/springdoc/api/app90/SpringDocTestApp.java – BartusZak Jun 17 '22 at 15:01
4

@ExampleObject can be used for @RequestBody and @ApiResponse to add examples for springdoc openapi : https://github.com/springdoc/springdoc-openapi/blob/master/springdoc-openapi-javadoc/src/test/java/test/org/springdoc/api/app90/HelloController.java

@RestController
public class HelloController {

    /**
     * Test 1.
     *
     * @param hello the hello
     */
    @GetMapping("/test")
    @ApiResponses(value = { @ApiResponse(description = "successful operation",content = { @Content(examples = @ExampleObject(name = "500", ref = "#/components/examples/http500Example"), mediaType = "application/json", schema = @Schema(implementation = User.class)), @Content(mediaType = "application/xml", schema = @Schema(implementation = User.class)) }) })
    public void test1(String hello) {
    }

    /**
     * Test 2.
     *
     * @param hello the hello
     */
    @PostMapping("/test2")
    @RequestBody(
            description = "Details of the Item to be created",
            required = true,
            content = @Content(
                    schema = @Schema(implementation = User.class),
                    mediaType = MediaType.APPLICATION_JSON_VALUE,
                    examples = {
                            @ExampleObject(
                                    name = "An example request with the minimum required fields to create.",
                                    value = "min",
                                    summary = "Minimal request"),
                            @ExampleObject(
                                    name = "An example request with all fields provided with example values.",
                                    value = "full",
                                    summary = "Full request") }))
    public void test2(String hello) {
    }

}

if you want to add OpenApiCustomiser in order to load your examples from resources you will need to start with something like this: https://github.com/springdoc/springdoc-openapi/blob/master/springdoc-openapi-javadoc/src/test/java/test/org/springdoc/api/app90/SpringDocTestApp.java

@Bean
    public OpenApiCustomiser openApiCustomiser(Collection<Entry<String, Example>> examples) {
        return openAPI -> {
            examples.forEach(example -> {
                openAPI.getComponents().addExamples(example.getKey(), example.getValue());
            });
        };
    }

For header, cookie, query or path params you can use @Parameter: https://docs.swagger.io/swagger-core/v2.0.0-RC3/apidocs/io/swagger/v3/oas/annotations/Parameter.html

with ParameterIn enum: https://docs.swagger.io/swagger-core/v2.0.0/apidocs/io/swagger/v3/oas/annotations/enums/ParameterIn.html

e.g.

@Parameter(in = ParameterIn.PATH, name = "id", description="Id of the entity to be update. Cannot be empty.",
        required=true, examples = {@ExampleObject(name = "id value example", value = "6317260b825729661f71eaec")})

Another way is to add @Schema(type = "string", example = "min") on your DTO. e.g. : https://www.dariawan.com/tutorials/spring/documenting-spring-boot-rest-api-springdoc-openapi-3/

Alex P.
  • 61
  • 3
0

If someone is still interested, this is how examples can be added programmatically to a specific endpoint:

@Bean
 public OpenApiCustomiser mockExamples() {
    return openAPI ->
        getRequestBodyContent(openAPI, PXL_MOCK_PATH + "/transactions", "application/json").ifPresent(request ->
            Arrays.stream(PxlMockCase.values()).forEach(mockCase -> {
                request.addExamples(
                    mockCase.name(),
                    new Example()
                        .description(mockCase.getDescription())
                        .value(TransactionCodeRequest.builder().accountId(mockCase.getAccountId()).workflowId(15).build())
                );
            }));
}

private Optional<MediaType> getRequestBodyContent(OpenAPI api, String path, String bodyType) {
    return Optional.ofNullable(api.getPaths())
        .map(paths -> paths.get(path))
        .map(PathItem::getPost)
        .map(Operation::getRequestBody)
        .map(RequestBody::getContent)
        .map(content -> content.get(bodyType));
}
flatbeat
  • 33
  • 5
-4

If we are using spring boot, to add it to our Maven project, we need a dependency in the pom.xml file.

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
@Configuration
@EnableSwagger2
public class SpringConfig {                                    
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
          .select()                                  
          .apis(RequestHandlerSelectors.any())              
          .paths(PathSelectors.any())                          
          .build();                                           
    }
}

Configuration Without Spring Boot

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
      .addResourceLocations("classpath:/META-INF/resources/");
 
    registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

Verify: To verify that Springfox is working, you can visit the following URL in your browser: http://localhost:8080/our-app-root/api/v2/api-docs

To use Swagger UI, one additional Maven dependency is required:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

You can test it in your browser by visiting http://localhost:8080/our-app-root/swagger-ui.html

Laurel
  • 5,965
  • 14
  • 31
  • 57
  • @user471011 is looking for a solution with SpringDoc, and your example is with SpringFox. – Joan Sep 02 '22 at 10:42