Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ApiResponse.examples not showing in swagger ui #2538

Closed
stengvac opened this issue Jul 4, 2018 · 29 comments
Closed

ApiResponse.examples not showing in swagger ui #2538

stengvac opened this issue Jul 4, 2018 · 29 comments

Comments

@stengvac
Copy link

stengvac commented Jul 4, 2018

Version: springfox 2.9.2, springboot 2.0.2
What kind of issue is this?: Question.
Lang: Kotlin

Examples from ApiResponse annotations are not propagated to swagger-ui. See following code:

ApiResponse(code = 200, message = "Resource created", response = String::class,
                examples = Example(value = [ExampleProperty(value = "Example text")])
        )

After spring-boot start swagger-ui present example text of response 200 as "string". So my question is whether i am missing something or it is bug. Because my expectations were, that example text will be "Example text". For more detailed info see used config and rest controller.

Thx for answering, V

Used config

@Configuration
@EnableSwagger2
class SwaggerConfig(@Value("\${build.version}") private val buildVersion: String) {

    @Bean
    fun api(): Docket {
        val res404 = ResponseMessageBuilder()
                .code(404)
                .message("Not found")
                .build()
        return Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.regex("^/(?!error|probe).*"))
                .build()
                .useDefaultResponseMessages(false)
                .globalResponseMessage(RequestMethod.GET, listOf(res404))
                .globalResponseMessage(RequestMethod.PUT, listOf(res404))
                .globalResponseMessage(RequestMethod.POST, listOf(res404))
                .globalResponseMessage(RequestMethod.PATCH, listOf(res404))
                .apiInfo(apiInfo)
    }

    @Bean
    fun uiConfig(): UiConfiguration {
        return UiConfigurationBuilder.builder()
                .deepLinking(true)
                .displayOperationId(false)
                .defaultModelsExpandDepth(5)
                .defaultModelExpandDepth(1)
                .defaultModelRendering(ModelRendering.EXAMPLE)
                .displayRequestDuration(false)
                .docExpansion(DocExpansion.FULL)
                .filter(false)
                .maxDisplayedTags(null)
                .operationsSorter(OperationsSorter.ALPHA)
                .showExtensions(false)
                .tagsSorter(TagsSorter.ALPHA)
                .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
                .validatorUrl(null)
                .build()
    }
}

RestController:

@RestController
@RequestMapping(
        path = ["/path/bla"],
        consumes = [MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.APPLICATION_JSON_VALUE],
        produces = [MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.APPLICATION_JSON_VALUE]
)
class MyController {

    @ApiOperation(value = "some opeation")
    @ApiResponses(value = [
        ApiResponse(code = 200, message = "Resource created", response = String::class,
                examples = Example(value = [ExampleProperty(value = "Example text")])
        )
    ])
    fun performAction(): String {
          ....
    }
}
@dilipkrish
Copy link
Member

I think it may be a Swagger-ui thing, but the other thing to definitely try is to single quote the string example ...value="'Example text'"...

@stengvac
Copy link
Author

stengvac commented Jul 9, 2018

Same behavior when I added single quote.

@dilipkrish
Copy link
Member

Could you share an excerpt of your swagger specification json? Wondering if it may be about where you're looking in the UI.

@hanuman1988
Copy link

hi. is there any way so that we can provide different Request URL instead of swagger hosted on. actually we are implementing gateway in between thus request will go first gateway then it will come to main server.

@dilipkrish
Copy link
Member

Yes, you can.

@stengvac
Copy link
Author

stengvac commented Jul 24, 2018

Configuration used same as in 1st post.

@RestController
class ExampleController {

    @GetMapping(path = ["/hello"])
    @ApiResponses(ApiResponse(code = 200, message = "Resource created", response = String::class, examples = Example(value = [(ExampleProperty(value = "'Example text'"))])))
    fun example(): String = "Hello world"

}

output json from http://localhost:8082/v2/api-docs

{"swagger":"2.0","info":{"description":"Api Documentation","version":"1.0","title":"Api Documentation","termsOfService":"urn:tos","contact":{},"license":{"name":"Apache 2.0","url":"http://www.apache.org/licenses/LICENSE-2.0"}},"host":"localhost:8082","basePath":"/","tags":[{"name":"example-controller","description":"Example Controller"}],"paths":{"/hello":{"get":{"tags":["example-controller"],"summary":"example","operationId":"exampleUsingGET","produces":["*/*"],"responses":{"200":{"description":"Resource created","schema":{"type":"string"}},"404":{"description":"Not found"}},"deprecated":false}}}}

@dilipkrish
Copy link
Member

@stengvac just confirming, are you using 2.9.2?

@stengvac
Copy link
Author

yup

@mikhalchenko-alexander
Copy link

mikhalchenko-alexander commented Jul 25, 2018

Same problem here. Springfox 2.9.2, Kotlin 1.2.51, SpringBoot 2.0.3.RELEASE. examples parameter ignored in @ApiResponse.

@dilipkrish
Copy link
Member

According to this test

@RequestMapping(value = "/1570", method = RequestMethod.POST)
@ApiOperation(value = "Demo using examples")
@ApiResponses(value = {@ApiResponse(code = 404, message = "User not found"),
@ApiResponse(
code = 405,
message = "Validation exception",
examples = @io.swagger.annotations.Example(
value = {
@ExampleProperty(
mediaType = "Example json",
value = "{\"invalidField\": \"address\"}"),
@ExampleProperty(
mediaType = "Example string",
value = "The first name was invalid")}))})
public void saveUser() {
//No-op
}

We see this output

"/features/1570": {
"post": {
"consumes": [
"application/json"
],
"deprecated": false,
"operationId": "saveUserUsingPOST_1",
"responses": {
"200": {
"description": "OK"
},
"404": {
"description": "User not found"
},
"405": {
"description": "Validation exception",
"examples": {
"Example json": "{\"invalidField\": \"address\"}",
"Example string": "The first name was invalid"
}
}
},
"summary": "Demo using examples",
"tags": [
"feature-demonstration-service"
]
}
},

Not sure, if its something with Kotlin or springboot 2.0

@stengvac
Copy link
Author

stengvac commented Aug 9, 2018

Tried same code as provided in test example with controller written in Java and examples are not showing.
example project https://github.com/stengvac/spring-boot-swagger2 where you see and try swagger ui if you want.

so it is possible, that problem is in spring-boot?

@dilipkrish
Copy link
Member

@stengvac sorry I assumed it was part of 2.9.2. Unfortunately it was included after it was released via #1570. Sorry for the confusion

@prisin
Copy link

prisin commented Jan 17, 2019

Hi,

I am facing the same issue ApiResponse.examples not showing in swagger ui. May i know when this feature will be available.

@ptheohar
Copy link

ptheohar commented Mar 4, 2019

Hey, I need this feature also. When will this be released?

@tdoan2010
Copy link

According to this test
springfox/springfox-spring-web/src/test/java/springfox/documentation/spring/web/dummy/controllers/FeatureDemonstrationService.java

Lines 291 to 307 in ac4c54e

@RequestMapping(value = "/1570", method = RequestMethod.POST)
@ApiOperation(value = "Demo using examples")
@ApiResponses(value = {@ApiResponse(code = 404, message = "User not found"),
@ApiResponse(
code = 405,
message = "Validation exception",
examples = @io.swagger.annotations.Example(
value = {
@ExampleProperty(
mediaType = "Example json",
value = "{"invalidField": "address"}"),
@ExampleProperty(
mediaType = "Example string",
value = "The first name was invalid")}))})
public void saveUser() {
//No-op
}
We see this output

springfox/swagger-contract-tests/src/test/resources/contract/swagger2/declaration-feature-demonstration-service.json

Lines 206 to 233 in ac4c54e

"/features/1570": {
"post": {
"consumes": [
"application/json"
],
"deprecated": false,
"operationId": "saveUserUsingPOST_1",
"responses": {
"200": {
"description": "OK"
},
"404": {
"description": "User not found"
},
"405": {
"description": "Validation exception",
"examples": {
"Example json": "{"invalidField": "address"}",
"Example string": "The first name was invalid"
}
}
},
"summary": "Demo using examples",
"tags": [
"feature-demonstration-service"
]
}
},
Not sure, if its something with Kotlin or springboot 2.0

I see that you use @Controller in your source code. If you switch to @RestController, it doesn't work.

@kduhyun
Copy link

kduhyun commented Mar 20, 2019

Anyone who is interested in this feature can use 3.0.0-SNAPSHOT that supports the @ExampleProperty.

To convert the library from 2.9.2 to 3.0.0-SNAPSHOT, please refer to the configuration demo;
https://github.com/springfox/springfox-demos/tree/master/springfox-integration-webmvc

You may need to include additional libraries.

compile group: 'io.springfox', name: 'springfox-spring-webmvc', version:'3.0.0-SNAPSHOT'
compile group: 'io.springfox', name: 'springfox-spring-integration-webmvc', version:'3.0.0-SNAPSHOT'

@prisin @ptheohar

@ksrh
Copy link

ksrh commented Apr 10, 2019

@dilipkrish Hello! Are there any updates about that issue?

@Toumani
Copy link

Toumani commented Oct 9, 2019

@kduhyun Can't run demo example at https://github.com/springfox/springfox-demos/tree/master/springfox-integration-webmvc.

Cannot resole io.springfox.springfox-swagger2 at version 3.0.0-SNAPSHOT. Is this version still available ?

@coding8282
Copy link

Is there anyone resolve the problem?? it's not working stil....

@coding8282
Copy link

Anyone who is interested in this feature can use 3.0.0-SNAPSHOT that supports the @ExampleProperty.

To convert the library from 2.9.2 to 3.0.0-SNAPSHOT, please refer to the configuration demo;
https://github.com/springfox/springfox-demos/tree/master/springfox-integration-webmvc

You may need to include additional libraries.

compile group: 'io.springfox', name: 'springfox-spring-webmvc', version:'3.0.0-SNAPSHOT'
compile group: 'io.springfox', name: 'springfox-spring-integration-webmvc', version:'3.0.0-SNAPSHOT'

@prisin @ptheohar

3.0.0 - SNAPSHOT with Kotlin not working still...

@JuanGQCadavid
Copy link

I used @ApiResponses(..). It worked.

@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK -> The user has been fetched successfully"),
@ApiResponse(code = 201, message = "OK -> The user has been created successfully"),
@ApiResponse(code = 202, message = "Accepted -> The user has been updated successfully"),
@ApiResponse(code = 204, message = "NO CONTENT -> The user has been removed successfully")
})

You can use it at the class level or a method level.

@raghu4
Copy link

raghu4 commented Apr 15, 2020

@dilipkrish what version of springfox supports response examples?
Can you give me an example ?

@Algeran
Copy link

Algeran commented Apr 23, 2020

@dilipkrish As I understand, that feature will be repaired in 3.0.0 release?

@dilipkrish
Copy link
Member

Yes absolutely... Im hoping to release in the next couple weeks

@Algeran
Copy link

Algeran commented Apr 23, 2020

Great! Will be waiting for it

@brant-hwang
Copy link

When do you plan to deploy the version of the issue solved?

@ml-milan-vit
Copy link

ml-milan-vit commented Jun 2, 2020

While trying to figure this one out, I noticed that the example response is properly returned if you give up on specifying correct media type. In other words, the example below somewhat works for me:

@PostMapping
@ApiResponses({
	@ApiResponse(code = 400, message = "Bad Request", examples = @Example({
		@ExampleProperty(mediaType = "*/*", value = "{\"status\": \"BAD_REQUEST\"}")
	}))
})
public ResponseEntity<RegistrationResource> register(@RequestBody @Valid RegistrationDTO registrationDTO) {
…
}

Tested with the 3.0.0-SNAPSHOT version of Springfox.

Edit: better yet, you can just specify the produces = "application/json" parameter in the @PostMapping annotation, and then use the same media type for @ExampleProperty. It seems that SpringFox simply doesn’t understand that @RestController specifies JSON as the output type.

@priyanshuwustl
Copy link

For some reason, putting .useDefaultResponseMessages(false) at the very end of the chain worked for me (and generated the x-example tags as expected). I did not have any .globalResponseMessage(xx,xx) in my Docket.

@dilipkrish
Copy link
Member

It seems that SpringFox simply doesn’t understand that @RestController specifies JSON as the output type.
It does now @ml-milan-vit :)

@priyanshuwustl it should be fixed now via #2767

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests