LoginSignup
29
30

More than 5 years have passed since last update.

SpringFoxを試してみた

Last updated at Posted at 2015-12-20

SpringFoxとは

Springと組み合わせて使うライブラリ。
Rest APIのドキュメントを自動で生成してくれる。また、ドキュメント上からAPIをコールするクライアントを用意してくれる。

試す

build.gradleに以下を追記

repositories {
    jcenter()
}

dependencies {
    compile 'io.springfox:springfox-swagger2:2.2.2'
    compile 'io.springfox:springfox-swagger-ui:2.2.2'
    compile "com.google.guava:guava:17.0"
}

GuavaはAPIのエントリポイントの指定を正規表現で指定するときに使います。

Spring Bootで適当にAPIを作りました。

@RestController
@RequestMapping("api/foo")
public class SampleController {
    @RequestMapping(value = "hoge", method = RequestMethod.GET)
    public Sample hoge(@RequestParam(value = "name") String name) {
        return new Sample(1, name, "hogehoge");
    }

    @RequestMapping(value = "fuga", method = RequestMethod.POST)
    public Sample fuga(@RequestBody Sample sample) {
        return sample;
    }
}

Spring BootのConfigurationクラスを以下のように書きました。

AppConfig.java
package sample.springFox;

import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import static com.google.common.base.Predicates.*;


@Configuration
@EnableSwagger2  // Springfoxを使用可能にするためのアノテーション
 public class AppConfig {

    @Bean
    public Docket document() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select().paths(paths()).build().apiInfo(apiInfo());
    }


    private Predicate<String> paths() {
        return or(containsPattern("/api*"));  //APIのエントリポイントを正規表現で指定
    }

    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfo("Sample API", "",
                "terms of service", "", "", "", "");
        return apiInfo;
    }
}

初回は以下を実行しましょう

./gradlew cleanIdea idea

次に以下でアプリケーションを起動しましょう。

./gradlew bootrun

以下のURLにアクセスすると・・・
http://localhost:8080/swagger-ui.html

FireShot Capture - Swagger UI_ - http___localhost_8080_swagger-ui.htm.png

ドキュメントが現れました!

ここからAPIをコールすることもできます。
パラメータのテンプレートをドキュメント上からワンクリックで入力してくれたりするのでとっても便利です。

ちなみにコードの変更時も再起動してくれたらドキュメントも更新されます。

ソースコードは以下に公開しています。
https://github.com/ftsan/SpringFox-Sample

APIのドキュメントが無くてお困りの方、ドキュメントはあるけどメンテナンスが面倒でお困りの方は試してみてはいかがでしょうか。

29
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
30