Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

springdoc-openapi: How to add example of POST request?

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.

like image 849
user471011 Avatar asked Feb 07 '26 18:02

user471011


1 Answers

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:

  • https://github.com/springdoc/springdoc-openapi/blob/master/springdoc-openapi-webmvc-core/src/test/java/test/org/springdoc/api/app90/SpringDocTestApp.java

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\": [email protected],"
                            + "\"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.

like image 61
brianbro Avatar answered Feb 09 '26 09:02

brianbro