86

I have a ReSTFul API written in simple Spring (no Spring Boot, no fancy stuff!). I need to implement Swagger into this. So far, EVERY page on the internet has only driven me crazy with confusing configurations and bloated code that I did not find portable at all.

Does anyone have a sample project (or a set of detailed steps) that can help me accomplish this? In particular, I am looking for a good sample that uses swagger-springmvc. I know it has 'samples', but at best, the esoteric code is discouraging.

I must clarify that I am not looking for "why Swagger is simply the best". I am not using (and for my current task will not use) Spring Boot or such.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
wavicle
  • 1,284
  • 1
  • 10
  • 12
  • 4
    By the samples, I assume you're referring to https://github.com/adrianbk/swagger-springmvc-demo. I'd actually encourage you to open a ticket directly on swagger-springmvc as it's important for them to know that some of their potential users may feel the docs are inadequate so that they could improve on it. – Ron Nov 03 '14 at 18:05
  • This one helps http://stackoverflow.com/questions/26807791/swagger-for-spring-mvc-project – spiderman Mar 01 '16 at 00:36
  • With latest Spec V3 - This can be useful with minimal configuration https://stackoverflow.com/a/64333853/410439 – Ravi Parekh Feb 18 '21 at 15:33

3 Answers3

127

Springfox (Swagger spec 2.0, current)

Springfox has replaced Swagger-SpringMVC, and now supports both Swagger specs 1.2 and 2.0. The implementation classes have changed, allowing for some deeper customization, but with some work. The documentation has improved, but still needs some details added for advanced configuration. The old answer for the 1.2 implementation can still be found below.

Maven dependency

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

The bare-minimum implementation looks more-or-less the same, but now uses the Docket class instead of the SwaggerSpringMvcPlugin class:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

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

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("TITLE")
            .description("DESCRIPTION")
            .version("VERSION")
            .termsOfServiceUrl("http://terms-of-services.url")
            .license("LICENSE")
            .licenseUrl("http://url-to-license.com")
            .build();
    }

}

Your Swagger 2.0 API documentation will now be available at http://myapp/v2/api-docs.

Note : If you are not using Spring boot then you should add jackson-databind dependency. Since springfox uses jackson for databinding.

Adding Swagger UI support is even easier now. If you are using Maven, add the following dependency for the Swagger UI webjar:

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

If you are using Spring Boot, then your web app should automatically pick up the necessary files and show the UI at http://myapp/swagger-ui.html (formerly: http://myapp/springfox). If you are not using Spring Boot, then as yuriy-tumakha mentions in the answer below, you will need to register a resource handler for the files. The Java configuration looks like this:

@Configuration
@EnableWebMvc
public class WebAppConfig 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/");
    }

}

The new static documentation generation feature also looks quite nice, though I have not tried it out myself.

Swagger-SpringMVC (Swagger spec 1.2, older)

The documentation for Swagger-SpringMVC can be a little bit confusing, but it is actually incredibly easy to set up. The simplest configuration requires creating a SpringSwaggerConfig bean and enabling annotation-based configuration (which you probably already do in your Spring MVC project):

<mvc:annotation-driven/>
<bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" />

However, I think it is well worth it to take the extra step of defining a custom Swagger configuration using the SwaggerSpringMvcPlugin, instead of the previous XML-defined bean:

@Configuration
@EnableSwagger
@EnableWebMvc
public class SwaggerConfig {

    private SpringSwaggerConfig springSwaggerConfig;

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
        this.springSwaggerConfig = springSwaggerConfig;
    }

    @Bean
    public SwaggerSpringMvcPlugin customImplementation(){

        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
                .apiInfo(apiInfo())
                .includePatterns(".*api.*"); // assuming the API lives at something like http://myapp/api
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("TITLE")
            .description("DESCRIPTION")
            .version("VERSION")
            .termsOfServiceUrl("http://terms-of-services.url")
            .license("LICENSE")
            .licenseUrl("http://url-to-license.com")
            .build();
    }

}

When you run your application, you should now see your API spec created at http://myapp/api-docs. To get the fancy Swagger UI set up, you need to clone the static files from the GitHub project and put them in your project. Make sure your project is configured to serve the static HTML files:

<mvc:resources mapping="*.html" location="/" />

Then edit the index.html file at the top level of the Swagger UI dist directory. Towards the top of the file, you'll see some JavaScript that refers to the api-docs URL of another project. Edit this to point to your project's Swagger documentation:

  if (url && url.length > 1) {
    url = url[1];
  } else {
    url = "http://myapp/api-docs";
  }

Now when you navigate to http://myapp/path/to/swagger/index.html, you should see the Swagger UI instance for your project.

Community
  • 1
  • 1
woemler
  • 7,089
  • 7
  • 48
  • 67
  • Thanks for sharing this tutorial. I am doing something similar but still I am not able to see UI (http://stackoverflow.com/questions/28178370/swagger-not-showing-ui). What am i doing wrong here? – plzdontkillme Jan 27 '15 at 20:42
  • What are Maven dependencies for Swagger 2 with Spring MVC? – Mikhail Batcer Sep 02 '15 at 14:13
  • 1
    @MikhailBatcer: I have updated the answer with the Maven dependency for Springfox. This is the only dependency you need to include in your project, unless you also want Swagger UI or Static Docs. – woemler Sep 02 '15 at 17:27
  • Great write up on the how-to. Also, keep in mind that the [springfox](http://springfox.io) site has fairly good and upto-date documentation. – Dilip Krishnan Oct 01 '15 at 12:57
  • @DilipKrishnan: No bias in the comment, eh ;) Yes, the documentation for the project is way better now, but I spent a lot of time scratching my head with the Swagger-SpringMVC docs. – woemler Oct 01 '15 at 13:19
  • @willOEM guilty as charged! – Dilip Krishnan Oct 01 '15 at 13:24
  • 2
    looks like the UI url is now /myapp/swagger-ui.html and not /springfox – chrismarx Oct 09 '15 at 19:05
  • 7
    For completeness: The 'regex' method in the springfox 'SwaggerConfig' example is from 'springfox.documentation.builders.PathSelectors.regex(String)'. If took me quite a while to figure that out ;) – cheneym Oct 22 '15 at 07:41
  • 2
    I've taken the liberty to add `PathSelectors.` to help people struggling with static import of `regex` – Tim Büthe Jan 25 '16 at 21:15
  • 2
    Worth noting: if following these instructions **exactly**, and not using SpringBoot, you'll get a runtime error due to the different versions of springfox and springfox-ui libraries retrieved from Maven. Instead, start out with the latest version of both if possible (`2.5.0` as I write this) – Kip Jul 29 '16 at 21:40
  • http://springfox.github.io/springfox/docs/current/#dependencies is a very good place to start and for further details. – BurnetZhong Mar 14 '17 at 06:19
13

Springfox Swagger UI works for me after adding WebJar dependency and resource mappings. http://www.webjars.org/documentation#springmvc

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.2.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.2.2</version>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.3.5</version>
    </dependency>

spring-servlet.xml:

<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>

or Spring Annotation https://github.com/springfox/springfox-demos/blob/master/spring-java-swagger/src/main/java/springfoxdemo/java/swagger/SpringConfig.java

Swagger2 should be enabled

 @EnableSwagger2
 public class SwaggerConfiguration {
 }
Yuriy Tumakha
  • 1,450
  • 17
  • 21
  • This helped me a lot, however I'm still getting a 404 on `/swagger-resources` when opening `swagger-ui.html`. Any tips? More resource mappings maybe? – Tim Büthe Jan 26 '16 at 14:19
  • It looks like swagger-resources are not in root context. It can be fixed by mapping DispatcherServlet to root context. Look at issue fix [issue 983](https://github.com/springfox/springfox/issues/983) and [Q. How does one configure swagger-ui for non-springboot applications?](http://springfox.github.io/springfox/docs/snapshot/#q13) – Yuriy Tumakha Jan 29 '16 at 08:23
1

You can also consider using swagger-maven-plugin to generate swagger.json and copy it to yours static swagger-ui.

Please check simple sample of working plugin with Spring MVC annotations on this repo:

https://github.com/khipis/swagger-maven-example

or for JAX-RS

https://github.com/kongchen/swagger-maven-example

kkhipis
  • 159
  • 7