“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
– Martin Fowler

What is Swagger ?

Swagger is a specification and complete framework implementation for describing, producing, consuming, and visualizing RESTful web services. The goal of Swagger is to enable client and documentation systems to update at the same pace as the server. The documentation of methods, parameters, and models are tightly integrated into the server code, allowing APIs to always stay in sync.

Why is Swagger useful?

The  framework simultaneously solves server, client, and documentation/sandbox needs.

With Swagger’s declarative resource specification, clients can understand and consume services without knowledge of server implementation or access to the server code. The Swagger UI framework allows both developers and non-developers to interact with the API in a sandbox UI that gives clear insight into how the API responds to parameters and options.

It happily speaks both JSON and XML, with additional formats in the works.

Now let’s see a working example and how do we configure Swagger, to generate API documentation of our sample REST API created using Spring Boot.

How to Enable Swagger in your Spring Boot Web Application ?

If you are one of those lazy people who hates reading the configurations, download the complete working example here , otherwise go on –

Step 1 : Include Swagger-SpringMVC dependency in Maven

Step 2 : Create Swagger Java Configuration

  • Use the @EnableSwagger annotation.
  • Autowire SpringSwaggerConfig.
  • Define one or more SwaggerSpringMvcPlugin instances using springs @Bean annotation.
[gist https://gist.github.com/saurzcode/9dcee7110707ff996784/]

Step 3 : Create Swagger UI using WebJar

For using webjar dependency add, following repository and dependency, which will auto configure swagger UI for you.

 

That’s it. Now run the Application.java as a java application in your IDE , and you will see the application running in embedded tomcat/jetty server running at default port 8080.

Verify the API Configuration by pointing your browser at  – http://localhost:8080/api-docs

And finally ,you can see the Swagger API Docs  and test the APIs at  http://localhost:8080/index.html

Swagger: API Doc for Spring Boot Application
Swagger : API Doc for RESTful API

 

Also, please note that default url in webjar files is - http://petstore.swagger.wordnik.com/api/api-docs So you might see an error like this, "Can't read from server. It may not have the appropriate access-control-origin settings." Solution : Just replace the URL [http://petstore.swagger.wordnik.com/api/api-docs] on screen with [http://localhost:8080/api-docs] and you will see UI as above.

 

Again, complete project is available at GitHub.

https://github.com/saurzcode/saurzcode-swagger-spring/

References :

Do write back in comments,  if you face any issues or concerns !!


You may also like :-