y0ngb1n

Aben Blog

欢迎来到我的技术小黑屋ヾ(◍°∇°◍)ノ゙
github

Spring Boot プロジェクトで Swagger ドキュメントを使用する

プロジェクトは GitHub にホストされています:y0ngb1n/spring-boot-samples、スターやフォークを歓迎します 😘


Swagger は「ストッキング兄」とも呼ばれ、プログラマーがコードを書きながらインターフェースドキュメントを生成できるとされています。

Swagger 2 依存関係の追加#

pom.xmlに Swagger 2 に必要な依存関係を追加します:

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

Swagger の Java 設定の追加#

@Configuration
@EnableSwagger2
public class SwaggerConfig {

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

Swagger 注釈の説明#

Swagger は注釈を使用してこのインターフェースがドキュメントを生成することを示します。これにはインターフェース名、リクエストメソッド、パラメータ、返却情報などが含まれます。

  • @Api:クラス全体を修飾し、Controller の役割を説明します
  • @ApiOperation:クラスのメソッド、またはインターフェースを説明します
  • @ApiParam:単一のパラメータの説明
  • @ApiModel:オブジェクトを使用してパラメータを受け取ります
  • @ApiProperty:オブジェクトでパラメータを受け取る際に、オブジェクトのフィールドを説明します
  • @ApiResponse:HTTP レスポンスの 1 つの説明
  • @ApiResponses:HTTP レスポンス全体の説明
  • @ApiIgnore:この API を無視するためにこの注釈を使用します
  • @ApiImplicitParam:1 つのリクエストパラメータ
  • @ApiImplicitParams:複数のリクエストパラメータ

これらは最も一般的に使用される注釈です。

具体的な他の注釈については、こちらを参照してください:https://github.com/swagger-api/swagger-core/wiki/Annotations

さらに詳しくはSwagger 注釈ドキュメントを参照してください。

Controller、Model を追加して効果をテストする#

@Api(value = "ユーザー管理", description = "ユーザー情報の「追加、削除、検索、更新」操作")
@RestController
@RequestMapping(path = "/sample/users")
public class UserController {

  private static Map<Long, UserModel> users = Collections.synchronizedMap(new HashMap<>());

  @ApiOperation(value = "ユーザーリスト")
  @GetMapping(path = "/")
  public List<UserModel> getUserList() {
    return new ArrayList<>(users.values());
  }

  @ApiOperation(value = "ユーザーを作成", notes = "Userオブジェクトに基づいてユーザーを作成します")
  @ApiImplicitParam(name = "user", value = "ユーザーの詳細エンティティ", required = true, dataTypeClass = UserModel.class)
  @PostMapping(path = "/")
  public UserModel createUser(@RequestBody UserModel user) {
    users.put(user.getId(), user);
    return user;
  }

  @ApiOperation(value = "ユーザーの詳細情報", notes = "IDに基づいてユーザーの詳細情報を取得します")
  @ApiImplicitParam(name = "id", value = "ユーザーID", required = true, dataType = "Long")
  @GetMapping(path = "/{id}")
  public UserModel getUser(@PathVariable Long id) {
    return users.get(id);
  }

  @ApiOperation(value = "ユーザーの詳細情報を更新", notes = "IDに基づいて更新オブジェクトを指定し、User情報に基づいてユーザーの詳細情報を更新します")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "id", value = "ユーザーID", required = true, dataTypeClass = Long.class),
      @ApiImplicitParam(name = "user", value = "ユーザーの詳細エンティティ", required = true, dataTypeClass = UserModel.class)
  })
  @PutMapping(path = "/{id}")
  public UserModel updateUser(@PathVariable Long id, @RequestBody UserModel user) {
    UserModel updateUser = users.get(id);
    updateUser.setName(user.getName());
    updateUser.setAge(user.getAge());
    updateUser.setEmail(user.getEmail());
    users.put(id, updateUser);
    return updateUser;
  }

  @ApiOperation(value = "ユーザーを削除", notes = "IDに基づいて削除オブジェクトを指定します")
  @ApiImplicitParam(name = "id", value = "ユーザーID", required = true, dataType = "Long")
  @DeleteMapping(path = "/{id}")
  public String deleteUser(@PathVariable Long id) {
    users.remove(id);
    return "成功";
  }
}
@Data
@ApiModel(value = "ユーザーモデル", description = "ユーザー詳細情報エンティティクラス")
public class UserModel {

  @ApiModelProperty(value = "ユーザーID")
  private Long id;

  @ApiModelProperty(value = "名前", allowableValues = "y0ngb1n, tony")
  private String name;

  @ApiModelProperty(value = "年齢", allowableValues = "range[1, 120]")
  private Integer age;

  @ApiModelProperty(value = "メール")
  private String email;
}

この時点でプロジェクトを起動して Swagger 2 が正常に統合されているかを確認できます。プロジェクトを起動すると、ログに Swagger が私たちにアクセスエンドポイント/v2/api-docsを追加したことが表示されます:

...
2019-12-28 22:19:53.880  INFO 11935 --- [main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
...

ブラウザでhttp://localhost:8080/v2/api-docsにアクセスすると、返された結果は一連の JSON 文字列であり、可読性は非常に低いことがわかります。幸いなことに Swagger 2 は私たちに視覚的なインタラクティブインターフェース SwaggerUI を提供しており、次に試してみましょう。

Swagger UI 依存関係の追加#

上記と同様に、pom.xmlに Swagger UI に必要な依存関係を追加します:

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

追加が完了したら、プロジェクトを再起動し、ブラウザでhttp://localhost:8080/swagger-ui.htmlにアクセスすると、以下のような効果が見られます:

Swagger 2

これで Swagger の統合が成功しました。さらに高度な操作については、ドキュメントや以下の参考リンクを見てさらに探求してください。学習を楽しんでください!

🔗️ 参考リンク#

読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。