Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Implement Swagger Documentation for REST APIs

DZone's Guide to

Implement Swagger Documentation for REST APIs

We all know documentation is important. Here's how to set up Swagger to help map out your REST APIs.

Free Resource

Modernize your application architectures with microservices and APIs with best practices from this free virtual summit series. Brought to you in partnership with CA Technologies.

Looking for some help with documentation? Look no further. Let's get Swagger up and running to give you a hand.

First, add the below Swagger and Swagger UI dependencies to pom.xml to enable Swagger documentation:

<!-- http://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.4.0</version>
</dependency>
<!-- http://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.4.0</version>
</dependency>


Add the below entry to the applicationcontext.xml file to register the SwaggerConfig bean and restservices package scanning from where Swagger documentation is retrieved.

<context:component-scan base-package="yourpackage.restservices" />
<bean name="swaggerConfig" class="yourpackage.SwaggerConfig" />


Create a SwaggerConfig.java file to enable the path for the REST services:

package yourpackage;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig extends WebMvcConfigurerAdapter {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).pathProvider(new BasePathAwareRelativePathProvider("/yourcontextroot/api")).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("REST Web Services").description("Swagger documentation for your project REST webservices").termsOfServiceUrl("")
        .license("client license").licenseUrl("").version("1.0").build();
    }

    @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/");
    }
}


Create BasePathAwareRelativePathProvider.java, which takes the API path from SwaggerConfig:

package yourpackage;

import org.springframework.web.util.UriComponentsBuilder;

import springfox.documentation.spring.web.paths.AbstractPathProvider;
import springfox.documentation.spring.web.paths.Paths;

class BasePathAwareRelativePathProvider extends AbstractPathProvider {
    private String basePath;

    public BasePathAwareRelativePathProvider(String basePath) {
        this.basePath = basePath;
    }

    @Override
    protected String applicationPath() {
        return basePath;
    }

    @Override
    protected String getDocumentationPath() {
        return "/";
    }

    @Override
    public String getOperationPath(String operationPath) {
        UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromPath("/");
        return Paths.removeAdjacentForwardSlashes(uriComponentsBuilder.path(operation Path.replaceFirst(basePath, "")).build().toString());
    }
}


Modify web.xml to enable the API path so that it will be displayed properly in the browser:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/applicationcontext.xml
    </param-value>
</context-param>

<servlet>
    <servlet-name>servletname</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>servletname</servlet-name>
    <url-pattern>/api/*</url-pattern>
</servlet-mapping>


Start the server and head for the URL below to start the API documentation of your REST web services. It will list all the rest API calls in detail:

http://<yourhost>:<ip>/<yourcontextroot>/api/swagger-ui.html

The Integration Zone is proudly sponsored by CA Technologies. Learn from expert microservices and API presentations at the Modernizing Application Architectures Virtual Summit Series.

Topics:
swagger ,rest api

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}