Getting Started

Dependencies

The Springfox libraries are hosted on bintray and jcenter. The artifacts can be viewed accessed at the following locations:

Springfox has multiple modules and the dependencies will vary depending on the desired API specification standard. Below outlines how to include the springfox-swagger2 module which produces Swagger 2.0 API documentation.

Gradle

Release
repositories {
  jcenter()
}

dependencies {
    compile "io.springfox:springfox-swagger2:2.0.2"
}
Snapshot
repositories {
   maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
}

dependencies {
    compile "io.springfox:springfox-swagger2:2.0.3-SNAPSHOT"
}

Maven

Release
<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.0.2</version>
</dependency>
Snapshot
<repositories>
    <repository>
      <id>jcenter-snapshots</id>
      <name>jcenter</name>
      <url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
    </repository>
</repositories>

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

Springfox-swagger2 with Spring Boot

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/*
 *
 *  Copyright 2015 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *
 */

package springfox.springconfig;

import com.fasterxml.classmate.TypeResolver;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.schema.WildcardType;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.petstore.controller.PetController;

import java.util.List;

import static com.google.common.collect.Lists.*;
import static springfox.documentation.schema.AlternateTypeRules.*;

@SpringBootApplication
@EnableSwagger2(1)
@ComponentScan(basePackageClasses = {
    PetController.class
})(2)
public class Swagger2SpringBoot {

  public static void main(String[] args) {
    ApplicationContext ctx = SpringApplication.run(Swagger2SpringBoot.class, args);
  }


  @Bean
  public Docket petApi() {
    return new Docket(DocumentationType.SWAGGER_2)(3)
        .select()(4)
          .apis(RequestHandlerSelectors.any())(5)
          .paths(PathSelectors.any())(6)
          .build()(7)
        .pathMapping("/")(8)
        .directModelSubstitute(LocalDate.class,
            String.class)(9)
        .genericModelSubstitutes(ResponseEntity.class)
        .alternateTypeRules(
            newRule(typeResolver.resolve(DeferredResult.class,
                    typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                typeResolver.resolve(WildcardType.class)))(10)
        .useDefaultResponseMessages(false)(11)
        .globalResponseMessage(RequestMethod.GET,(12)
            newArrayList(new ResponseMessageBuilder()
                .code(500)
                .message("500 message")
                .responseModel(new ModelRef("Error"))(13)
                .build()))
        .securitySchemes(newArrayList(apiKey()))(14)
        .securityContexts(newArrayList(securityContext()))(15)
        ;
  }

  @Autowired
  private TypeResolver typeResolver;

  private ApiKey apiKey() {
    return new ApiKey("mykey", "api_key", "header");(16)
  }

  private SecurityContext securityContext() {
    return SecurityContext.builder()
        .securityReferences(defaultAuth())
        .forPaths(PathSelectors.regex("/anyPath.*"))(17)
        .build();
  }

  List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope
        = new AuthorizationScope("global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return newArrayList(
        new SecurityReference("mykey", authorizationScopes));(18)
  }

  @Bean
  SecurityConfiguration security() {
    return new SecurityConfiguration((19)
        "test-app-client-id",
        "test-app-realm",
        "test-app",
        "apiKey");
  }

  @Bean
  UiConfiguration uiConfig() {
    return new UiConfiguration((20)
        "validatorUrl");
  }
}
1 Enables Springfox swagger 2
2 Instructs spring where to scan for API controllers
3 Docket, Sringfox’s, primary api configuration mechanism is initialized for swagger specification 2.0
4 select() returns an instance of ApiSelectorBuilder to give fine grained control over the endpoints exposed via swagger.
5 apis() allows selection of RequestHandler’s using a predicate. The example here uses an `any predicate (default). Out of the box predicates provided are any, none, withClassAnnotation, withMethodAnnotation and basPackage.
6 paths() allows selection of Path’s using a predicate. The example here uses an `any predicate (default)
7 The selector requires to be built after configuring the api and path selectors. Out of the box we provide predicates for regex, ant, any, none
8 Adds a servlet path mapping, when the servlet has a path mapping. this prefixes paths with the provided path mapping
9 Convenience rule builder substitutes LocalDate with String when rendering model properties
10 Convenience rule builder that substitutes a generic type with one type parameter with the type parameter. In this example ResponseEntity<T> with T. alternateTypeRules allows custom rules that are a bit more involved. The example substitutes DeferredResult<ResponseEntity<T>> with T generically
11 Flag to indicate if default http response codes need to be used or not
12 Allows globally overriding response messages for different http methods. In this example we override the 500 error code for all `GET`s …​
13 …​and indicate that it will use the response model Error (which will be defined elsewhere)
14 Sets up the security schemes used to protect the apis. Supported schemes are ApiKey, BasicAuth and OAuth
15 Provides a way to globally set up security contexts for operation. The idea here is that we provide a way to select operations to be protected by one of the specified security schemes.
16 Here we use ApiKey as the security schema that is identified by the name mykey
17 Selector for the paths this security context applies to.
18 Here we same key defined in the security scheme mykey
19 Optional swagger-ui security configuration for oauth and apiKey settings
20 Optional swagger-ui ui configuration currently only supports the validation url

There are plenty of more options to configure the Docket. This should provide a good start.

Swagger UI

The springfox-swagger-ui web jar ships with Swagger UI. To include it in a standard Spring Boot application you can add the dependency as follows:

dependencies {
    compile 'io.springfox:springfox-swagger-ui:2.0.2'
}

Pulling in the dependency creates a webjar containing the swagger-ui static content. It adds a JSON endpoint /swagger-resources which lists all of the swagger resources and versions configured for a given application. The Swagger UI page should then be available at http://localhost:8080/swagger-ui.html

Swagger UI

The swagger ui version is specified in ./build.gradle where swaggerUiVersion is a git tag on the [swagger-ui repo] (https://github.com/wordnik/swagger-ui).

All content is served from a webjar convention, relative url taking the following form: webjars/${project.name}/${project.version} e.g: /webjars/springfox-swagger-ui/2.0.2-SNAPSHOT/swagger-ui.html

By default Spring Boot has sensible defaults for serving content from webjars. To configure vanilla spring web mvc apps to serve webjar content see the webjar documentation

Springfox samples

The springfox-demos repository contains a number of samples.