Using Swagger with Spring Boot

Overview

Swagger is the world’s largest framework of API developer tools for the OpenAPI Specification(OAS), enabling development across the entire API lifecycle, from design and documentation, to test and deployment.

Spring Boot takes an opinionated view of building production-ready Spring applications. Spring Boot favors convention over configuration and is designed to get you up and running as quickly as possible.

In this post, we will setup swagger with Spring boot leveraging the best of both the frameworks to create some APIs.

Here is what we will try to Achieve:

  • Create a Spring boot project
  • Configure Swagger to generate Interfaces and Documentation
  • Use a sample Petstore api yml file to generate API Interfaces and Documentation

Pre-Requisites and Tools Needed:

  • IDE with Spring support such as IntelliJ or Eclipse
  • JDK 8

This post will demonstrate steps using the IntelliJ IDEA IDE, however, the steps should mostly be similar for Eclipse.

Generating Code via Swagger

  1. Create a Gradle project using your favorite IDE.
  2. Replace the contents of the build.gradle file created in Step 1 with the following contents:
buildscript {
   ext {
      springBootVersion = '2.0.1.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
plugins {
   id "org.hidetake.swagger.generator" version "2.11.0"
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'org.petstore.apis'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
   jcenter()
}


dependencies {
   compile('org.springframework.boot:spring-boot-starter-actuator')
   compile('org.springframework.boot:spring-boot-starter-security')
   compile('org.springframework.boot:spring-boot-starter-web')
   runtime('org.springframework.boot:spring-boot-devtools')
   testCompile('org.springframework.boot:spring-boot-starter-test')
   testCompile('org.springframework.security:spring-security-test')
   swaggerCodegen 'io.swagger:swagger-codegen-cli:2.3.1'
}

swaggerSources {
   petstore {
      inputFile = file('src/main/resources/swagger/petstore.yml')
      code {
         language = 'spring'
         configFile = file('src/main/resources/swagger/config.json')
      }
   }
}
  • For Code Generation, we will also need a config file which defines generated sources metadata. Create a file config.json in folder src/main/resources/swagger with the following contents:
{
  "apiPackage" : "org.petstore.api",
  "modelPackage": "org.petstore.models",
  "invokerPackage": "org.petstore",
  "library": "spring-mvc",
  "dateLibrary": "java8",
  "hideGenerationTimestamp": true
}
  • Now Create an api.yml file in src/main/resources/swagger/ which will be used by Swagger to generate API related Java classes. For this exercise, we will use pet store sample API yml file available at https://editor.swagger.io/
  • To generate code run the following command at the root of the project in the command line:

    gradle -i generateSwaggerCode

  • This should generate Classes under build/swagger-code-petstore/srcScreen Shot 2018-04-14 at 9.13.07 PM

Generating and Publishing API Documentation

There are two ways of creating API documentation

  • Generate API documentation into static HTML files: This approach is useful when you want to generate Static HTML API documentation to be hosted on a different server
  • Publishing Documentation as an API: Alternatively, we can also publish a documentation API which can be consumed in any swagger UI based project.

Generating API Documentation

Add the following dependency to build.gradle file:

dependencies {
swaggerUI ‘org.webjars:swagger-ui:2.x.x’
}

In Command line run the following command:

gradle -i generateSwaggerUI

This creates HTML API documentation under folder build:

Screen Shot 2018-04-14 at 9.31.54 PM

Publishing Documentation as API Documentation:

  • Add the following dependencies to the build.gradle file:
swaggerUI 'org.webjars:swagger-ui:2.0.12'
compile group: 'io.swagger', name: 'swagger-annotations', version: '1.5.18'
compile group: 'io.swagger', name: 'swagger-core', version: '1.5.18'
compile group: 'io.swagger', name: 'swagger-models', version: '1.5.18'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.0.2'
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.8.0'
  • Configure Spring boot run by adding the following to the build.gradle file:
defaultTasks 'bootRun'
bootRun {
   main = 'org.petstore.apis.petstoreapis.PetstoreapisApplication'
}
  • Now Add the generated source directory to build.gradle source set config:
sourceSets {
   main {
      java {
         srcDirs 'build/swagger-code-petstore/src/main/java'
         srcDirs 'build/swagger-code-petstore/src/main/resources'
      }
   }
}
  • Add a Docket bean for swagger to map API endpoints as needed:
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}
  • Now Run the application by starting the default gradle command at the root of the Project:

./gradlew

Once the application starts API documentation is now available as an API at http://localhost:8080/v2/api-docs. This can be configured with Swagger UI project which converts the API response to HTML.

Implementing APIs

To add your own logic simply implement the PetApi interface. For e.g.

@RestController
@RequestMapping("/api")
public class APIController implements PetApi {

    @Override
    public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) {
        // Implement Your Logic
        return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
    }
}

The entire code for this is available on github

References

Leave a comment