Search code examples
javaspring-bootswagger-uiopenapispringdoc

Generating Swagger API documentation with functional "Try it out" feature without excessive annotations


I have a RESTful API written in Java + Spring Boot and I need to generate the documentation for it, with Swagger's "Try it out" feature working. However, I hate having to pollute my code with Swagger annotations, because I think they compromise the readability of the code too much, in addition to making the code ugly.

Once the documentation is generated through the annotations, it is possible to export the openapi.yml file. I've tried doing that and then using that file as the source for the documentation and removing the code annotations, but when I do that the "Try it out" stops working.

Therefore, I would like to know if there is a way to generate API documentation with Swagger, with the "Try it out" working, but without having to flood my code with annotations.

I'm using springdoc-openapi, by the way.


Solution

  • What I've seen work reasonably well is to extract an interface from your controller class, and put all the OpenAPI annotations in the interface. Your controller class implements this interface, so all the OpenAPI annotations come along for the ride.

    Granted, this just moves the clutter of OpenAPI annotations around, but it does improve the readability of your concrete controller class.