Document Your REST API using Spring Boot and Swagger

Sharing is caring!

Overview

As a developer, you considerably have two main tasks while developing the system. One part is coding itself. Of course, when I say coding, it means code and testing (I would say a TDD technique). The other one is documentation. It is the most boring part. EVER. However, we can make a fun of it. At least, for spring-boot project we have already been provided a very cool REST API documentation. We can use Swagger for lifting some heavy burden while doing documentation. Only by adding some few configurations, swagger will automatically format your REST API documentations.

If you want to know more details about Swagger, you can visit their website here.

Use Case

For these demo I will enhance my spring-demo-cors project. My purpose is to expose all my REST API documentations within /api context.

Configure Project

First of all, I need to alter pom.xml a little bit. I put required library for swagger configuration and bootstrap library from webjars. I need bootstrap library for the REST API documentation web page.

After pom is all set up, then I move to create a spring bean. I will give it a name SwaggerConfig. I do some configurations in this bean, including path selector and API information.

Here are the snippets:

Running

Once I finish the configuration, which is only few lines, then it is time to run the application. If you are using Spring Tools Suite, you can just run the main class. Or whenever you want to run in console, just type

Then open your favorite browser, and type http://localhost:8080/swagger-ui.html. Then you will see page, similarly like this one

swagger-ui
swagger-ui

Conclusion

Now you can see, how easy to document your REST API. So, whenever you are working with spring-boot and creating a REST API, you will have no more excuse for not documenting it. Again, the full sample is on my github.

Happy Rooster Year!

Author: ru rocker

I have been a professional software developer since 2004. Java, Python, NodeJS, and Go-lang are my favorite programming languages. I also have an interest in DevOps. I hold professional certifications: SCJP, SCWCD, PSM 1, AWS Solution Architect Associate, and AWS Solution Architect Professional.

Leave a Reply

Your email address will not be published. Required fields are marked *