In this micro-services era we develop many API in given languages but the question is how are we going to document those. The usual approach followed by any developer is to document in word or in markdown syntax and share the same to others. This way of documentation has become outdated.

That’s where swagger comes into picture. Swagger is a framework which converts the API into well-documented and standard format and provides the export option to various formats of our choice.

Remember WSDL which provides the definition for the SOAP services, similarly we have swagger which does the job for REST API’s.

Not only this is a documentation tool, it is so powerful that it aids in the automation of the process of registering these definitions into the API gateway which will get to see in later articles.

Let’s get started with an example. Below are the tools we’re going to use:

  • Java 7+
  • Spring Boot – 1.4.7
  • Swagger Springfox framework – 2.6.1
  • Maven based project


Adding dependencies

This is the core swagger dependency to be added into pom.xml

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


Integration of swagger in code

Annotate the main class with @EnableSwagger2. This enables the application to identify all the swagger annotations in spring autoscanning phase.

import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2
@SpringBootApplication
public class SwaggerdemoApplication {
   ....   
}


Swagger annotations

Obviously swagger doesn’t know what kind of API’s you are going to expose from your controller. So it needs to be taught that these are my API’s and those are only to be documented. And that’s why there comes the swagger annotations. I’m going to walk you through with couple of annotations which are most used in applications and more on this you can follow the documentation.

NOTE: Given example is intended to demonstrate only the swagger implementation.


@Api

Per the listing-1, This is used to annotate the controller class when you want expose them into the documentation.

Listing 1:

@Controller
@RequestMapping(value = "/movie", produces = { APPLICATION_JSON_VALUE })
@Api(value = "/movie", description = "Operations on movie database")
public class MovieController {
  ....	
}


@ ApiOperation

Per Listing-2, the @ApiOperation is used to declare a single operation. An operation is considered a unique combination of a path and a HTTP method. In spring this is annotated on @RequestMapping handlers.


@ApiResponses, @ApiResponse

For a given API there will be multiple responses one is anyway success and others might be an invalid response. For each scenario you might be having different response data structures. From Listing-2, getMovieById method returns a success response which is encapsulated in MovieInfo object. Each response will have a HTTP status code, a message and a response object. The response object might be a user-defined object like here MovieInfo in case of success response.

Listing 2:

@ApiOperation(value = "Find movie info by id", notes = "Returns movie information for given id")
      @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = MovieInfo.class),
                  @ApiResponse(code = 400, message = "Invalid ID supplied"),
                  @ApiResponse(code = 409, message = "Unknown error") })
      @RequestMapping(value = "/{movieId}", method = GET)
      public ResponseEntity<MovieInfo> getMovieById(
                  @ApiParam(required = true, allowMultiple = false, example = "100", name = "movieId") @PathParam("movieId") int movieId) {
            // TODO : implementation
            return null;
      }


@ApiParam

This defines the path parameter definitions. From Listing-2, the @ApiParamis annotated on path parameters. In case of spring based handlers, it’s used to annotate the @PathParam. For more info on the attributes check the documentation.


Verification

Run the application and type the url ` http://localhost:8080/v2/api-docs` in browser and you should be seeing the below JSON output. Later in the articles we would see how can we use this bare JSON definition and automate the unification of the API’s in API gateway.

enter image description here


Using Swagger –UI plugin

Now you would be saying how come this auto generated JSON is useful to understand the API specification. I knew you would be saying that and that’s why swagger UI plug-in is introduced. This plug-in uses the auto generated JSON and converts into a HTML format which is far more understandable when compared to the bare JSON definition.


Few more dependencies

This is another dependency to be added into pom.xml which generates html formatted documentation at compilation time.

NOTE: Make sure to add the scope as compile as it is not needed in the runtime.

io.springfox springfox-swagger-ui 2.6.1 compile


Verification

No run the application and type the url http:localhost:8080/swagger-ui.html in browser and you should be seeing the below page. Play around for some time and you’ll for sure understand the benefit of swagger and how effective it is.

enter image description here


References

Swagger Tool Website


Download Source Code Browse Source Code