app dev tools

Why choose Swagger framework for designing and documenting APIs

Software development is a complicated process requiring experienced developers, QA engineers, business analysts, designers, and project managers. Surely, having them all in a company isn’t enough for delivering great projects.

The tools and technologies they use are essential components of project success as exactly they enable to build secure quality solutions. It’s like painting: you can be the best painter in the world, but with no brushes, paints, pencils it will be more difficult for you to paint pictures.

In our blog, we love speaking of app development technologies we use. Being passionate about our work and everything that matters, we enjoy sharing our experience, knowledge, and opinions.

In this post, we’ll speak about Swagger, the largest and most popular framework of API developer tools that simplifies our work and helps build good applications.

 

A bit of introduction

 

API is the best way of connecting programmers and sharing useful data and developments. Through API, engineers access a network of shared pieces of code and valuable experiences. However, to access them they need clear documentation.

Noteworthy that earlier not only was there no industry standard for developing APIs, but there was no standard for documenting them. Swagger tool appeared as an approach to designing APIs and soon became the most popular framework for this purpose.

Two years ago Swagger spec was renamed the OpenAPI Specification and moved to the Linux Foundation. One should note that Swagger is supported by corporations like Google, Microsoft, and Atlassian, and such giants as Yelp and Netflix have already used it. As of July 2017, Swagger tools are downloaded more than 100,000 times per day.

 

What is Swagger

 

Swagger is the largest framework for designing APIs using a common language and enabling the development across the whole API lifecycle, including documentation, design, testing, and deployment.

The framework provides set of tools that help programmers generate client or server code and install self-generated documentation for web services.

However, there are many other frameworks like RAML, APIBlueprint, Summation, etc. So, how to explain the huge popularity of Swagger? The answer is that it offers more advantages and besides creating clear documentation allows other great things.

 

Swagger framework tools and benefits

 

First and foremost, as Swagger uses a common language that everyone can understand, it’s easily comprehensible for both programmers and non-programmers. Thus, product and project managers, business analysts and even potential customers can access your API design.

Also, as a Swagger framework is easily adjustable, it can be successfully used for API testing and bugfixing. Another important point is that the same documentation can be used for accelerating various API-dependent processes.

Swagger provides a set of great tools for designing APIs and improving the work with web services. Take a look at the most important:

  • Swagger Editor – allows software engineers to write API documentation, design and describe new APIs, and edit the existing ones. The first open-source editor visually renders OAS/Swagger definition with error handling and real-time feedback. The tool provides a plenty of useful features and suits best for getting started with Swagger spec. Swagger Editor runs everywhere and enables to write syntax more quickly with a smart auto-completion.
  • Swagger Codegen – enables programmers to generate client library code for different platforms. As the tool helps simplify the dev process by generating server stubs and client SDKs (in over 40 different languages!), software engineers get the ability to faster build your API and better focus on its adoption.
  • Swagger UI – allows engineers to get self-generated documentation for different platforms. Swagger UI is a fully customizable tool that can be hosted in any environment. A great plus is that it enables developers to save a lot of time for API documentation.
  • Swagger Inspector – is a tool for testing and auto-generating OpenAPI documentation for any API. Swagger Inspector allows to easily validate and test APIs with no limitations on what you test. Tests are automatically saved in the cloud with a simple access.

Here at Smartym, we enjoy Swagger for its wide range of fully customizable tools that help faster build APIs and improve the work with web services. We use Swagger framework in Spring MVC projects. Find out, how to set up Swagger for applications of this type. Let’s start.

 

Basic configuration

 

So as the start point you should have Spring boot or Spring MVC project with implemented rest controllers. To set up Swagger project we need a couple of additional dependencies:
Gradle

repositories {
 jcenter()
}
dependencies {
   compile “io.springfox:springfox-swagger2:2.4.0”

   compile ‘io.springfox:springfox-swagger-ui:2.4.0’
}

Maven

<repositories>
   <repository>
     <id>jcenter-snapshots</id>
     <name>jcenter</name>
     <url>https://jcenter.bintray.com/</url>
   </repository>
</repositories>

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

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.4.0</version>
</dependency>
After dependency was added to the project you should also enable Swagger and configure it at Spring configuration file. If you work with Spring boot application, all you need is to add Swagger docket configuration:
@Configuration

@EnableSwagger2

public class SwaggerConfig {                                

   @Bean

   public Docket docket() {

       return new Docket(DocumentationType.SWAGGER_2)

         .select()                              

         .apis(RequestHandlerSelectors.any())          

         .paths(PathSelectors.any())                      

         .build();                                       

   }

}
In this code Swagger 2 was enabled through the @EnableSwagger2 annotation and configured with docket bean.

In case you don’t have a Spring boot project, you should configure application resource handlers to expose swagger-ui resources such as swagger-ui.html and js/css that used in this html from springfox-swagger-ui dependency.

For that you should create new class with next configuration:

@Configuration

@EnableWebMvc

public class WebConfiguration extends WebMvcConfigurerAdapter {

  @Override

  public void addResourceHandlers(ResourceHandlerRegistry registry) {     

registry.addResourceHandler(“swagger-ui.html”).addResourceLocations(“classpath:/META-INF/resources”);

registry.addResourceHandler(“/webjars/**”).addResourceLocations(“classpath:/META-INF/resources/webjars/”);

  }

 

Advanced configuration

 

1. API documentation

Swagger has a list of annotations that can be used together with requests description and dto beans to better describe requests and used models.

For example you can use annotation @ApiOperation to set up name, description and response class for exact request:

@ApiOperation(value=”Get all persons”, notes = “Description of notes”, response = PersonsResponseBean.class)

@RequestMapping(method = RequestMethod.GET)

public ResponseEntity<String> getPersons() {

  return new ResponseEntity<String>(HttpStatus.OK);

}

 

2. Types mapping

We can change some class representation in Swagger. For example, we can configure that LocalDateTime will be shown in Swagger as Long in documentation.

We should configure docket entity with method directModelSubstitute.

Example:

@Bean

public Docket docket() {

  return new Docket(DocumentationType.SWAGGER_2).select().apis(

          RequestHandlerSelectors.basePackage(“pro.smartum.controllers”)).paths(PathSelectors.ant(“/persons/**”))

          .build().directModelSubstitute(LocalDate.class, Long.class).apiInfo(apiInfo());

}

 

3. Beans validation(support for JSR-303)

To add support for bean validation by annotations you should add an additional dependency:

Gradle

dependencies {

   compile “io.springfox:springfox-bean-validators:2.3.2+”
}

Maven

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-bean-validators</artifactId>
   <version>2.3.2+</version>
</dependency>

And then import configuration class:

@Import({BeanValidatorPluginsConfiguration.class})

 

4. Exposed API filtration

We can filter API controllers that exposed by Swagger and have methods apis() and paths() for this purpose, that can get flex predicates.

Method APIs filters by classes that handle requests. An argument for this method can be created by class RequestHandlerSelectors that can adjust filter by package, class or annotation.

Method paths filters by uri path of requests. An argument for this method can be created by class PathSelectors that can adjust filter by pattern ant or regexp.

@Bean

public Docket docket() {

  return new Docket(DocumentationType.SWAGGER_2).select().

apis(RequestHandlerSelectors.basePackage(“pro.smartum.controllers”)).paths(

          PathSelectors.ant(“/persons/*”)).build();

}

 

5. API information

Developers can also provide additional information about application for Swagger. This information should be passed to constructor of ApiInfo object. ApiInfo object should be passed docket bean:

@Bean

public Docket docket() {

  return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage(“pro.smartum.controllers”)).paths(

          PathSelectors.ant(“/persons/*”)).build().apiInfo(apiInfo());

}

private ApiInfo apiInfo() {

  return new ApiInfo(“Swagger test app”, “test app description”, “0.1”, null,

}
Swagger framework is so loved by software dev teams for many advantages it provides. We use Swagger for various reasons as it helps optimize the developers’ work, enhance team collaboration, and faster generate high-quality code.

In case you have some questions or need smart recommendations to your project, you’re welcome to apply to us with all your issues!