Swagger 2 with the Spring Boot

Knoldus Inc.
4 min readJan 4, 2022

--

Overview

Documentation is an essential part of building REST APIs. Nowadays, front-end and back-end components often separate a web application. Usually, we expose APIs as a back-end component for the front-end component or third-party app integrations.

Moreover, reference documentation should simultaneously describe every change in the API. Accomplishing this manually is a tedious exercise, so automation of the process was inevitable. We are going to achieve this by integrating swagger 2 with the spring boot or plain spring projects.

If you are not familiar with Swagger, visit its web page to learn more

Annotations

io.swagger.annotations.*

Annotation Type Description Api Marks a class as a Swagger resource. ApiImplicitParam Represents a single parameter in an API Operation. ApiImplicitParams A wrapper to allow a list of multiple ApiImplicitParam objects. ApiKeyAuthDefinition Annotation used to construct ApiKey Auth security definition. ApiModel Provides additional information about Swagger models. ApiModelProperty Adds and manipulates data of a model property. ApiOperation Describes an operation or typically a HTTP method against a specific path. ApiParam Adds additional meta-data for operation parameters. ApiResponse Describes a possible response of an operation. ApiResponses A wrapper to allow a list of multiple ApiResponse objects. Authorization Defines an authorization scheme to be used on a resource or an operation. AuthorizationScope Describes an OAuth2 authorization scope. BasicAuthDefinition Annotation used to construct Basic Auth security definition. Contact Contact metadata available within the info section of a Swagger definition. Example An optionally named list of example properties. ExampleProperty A mediaType/value property within a Swagger example. Extension An optionally named list of extension properties. ExtensionProperty A name/value property within a Swagger extension. ExternalDocs Represents an external documentation description. Info High-level metadata for a Swagger definition. License License metadata available within the info section of a Swagger definition. OAuth2Definition Annotation used to construct OAuth security definition. ResponseHeader Represents a header that can be provided as part of the response. Scope The available scopes for an OAuth2 security scheme. SecurityDefinition An aggregation of all security definitions. SwaggerDefinition Annotation that configures definition level metadata. Tag A definition level Tag object.

springfox.documentation.oas.annotations.EnableOpenApi

Annotation Type Description EnableOpenApi Indicates that Swagger support should be enabled.

Configure with Spring Boot

For each path, you define operations (HTTP methods) that can be used to access that path. Swagger 2.0 supports get, post, put, patch, delete, head, and options. A single path can support multiple operations, for example, GET /users to get a list of users and POST /users to add a new user. Swagger defines a unique operation as a combination of a path and an HTTP method. This means that two GET or two POST methods for the same path are not allowed – even if they have different parameters (parameters have no effect on uniqueness).

Maven Dependency

We will use the Springfox implementation of the Swagger specification. The latest version can be found on Maven Repository.

To add it to our Maven project, we need a dependency in the pom.xml file:

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>

Spring Boot Dependency

For the Spring Boot based projects, it’s enough to add a single springfox-boot-starter dependency:

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>

We can add any other starters we need, with a version managed by the Spring Boot parent:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.8</version>
</dependency>

Integrating Swagger with the Project

The configuration of Swagger mainly centers around the Docket bean:

@Configuration
public class SwaggerConfig {

@Bean
public Docket api() {
var apiInfo = new ApiInfoBuilder()
.title("my-example-service")
.version("1.0")
.license(null)
.licenseUrl(null)
.termsOfServiceUrl(null)
.description("The my-example-service to show the integration of swagger ui.")
.build();

return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo)
.useDefaultResponseMessages(false)
.select()
.apis(RequestHandlerSelectors
.basePackage("com.example.myexampleservice.api"))
.paths(PathSelectors.regex("/.*"))
.build();
}
}

After defining the Docket bean, its select() method returns an instance of ApiSelectorBuilder, which provides a way to control the endpoints exposed by Swagger.

We can configure predicates for selecting RequestHandlers with the help of RequestHandlerSelectors and PathSelectors.

In plain Spring projects, we need to enable Swagger 2 explicitly. To do so, we have to use the @EnableOpenApi on our configuration class.

Additionally, without Spring Boot, we don’t have the luxury of auto-configuration of our resource handlers.

Verification

To verify that Springfox is working, we can visit this URL in our browser:

http://localhost:8080/v3/api-docs

The result is a JSON response with a large number of key-value pairs, which is not very human readable. Fortunately, Swagger provides Swagger UI for this purpose.

Swagger UI Dependency for Project without Spring Boot

To use Swagger UI, we need to add an additional Maven dependency:

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>

Now we can test it in our browser by visiting:

http://localhost:8080/swagger-ui/

After clicking on the above url we will see Swagger UI.

We can easily see schemas by clicking on Schemas tab.

By clicking on the controller tab we will be able to see all our defined endpoints.

When we click one of the endpoints, we will see the information related to required or non-required parameters, example responses which we have configured, all the error responses handled by the endpoint, etc.

By clicking on Try it out, we will be able to test our endpoints. We have to give the value in the fields required by our API , then we will click on Execute. The generated response can be an error response or a successful response depending on the functioning of our API.

The full implementation can be found here

--

--

Knoldus Inc.

Group of smart Engineers with a Product mindset who partner with your business to drive competitive advantage | www.knoldus.com