Spring BootにおけるSwagger 2の導入と利用

Swaggerは、OpenAPI仕様に基づいたオープンソースのツール群であり、REST APIの設計、構築、文書化、および利用を支援します。その主な目的は、バックエンドのRESTful APIのテストを容易にし、動的な更新を可能にすることです。バックエンドのAPIが変更された場合、Swaggerは自動的に更新されるため、手動でのテストインターフェースのメンテナンスが不要になります。

Swaggerの主要アノテーション

Swaggerはアノテーションを使用して、APIドキュメントの生成を指示します。これには、API名、リクエストメソッド、パラメータ、およびレスポンス情報などが含まれます。

  • @Api: クラス全体に適用され、Controllerの役割を説明します。
  • @ApiOperation: クラスのメソッド、つまりAPIインターフェースを説明します。
  • @ApiParam: 個々のパラメータを説明します。
  • @ApiModel: オブジェクト形式でパラメータを受け取る際に使用し、そのオブジェクトを説明します。
  • @ApiProperty: オブジェクト形式でパラメータを受け取る際に、オブジェクトのフィールドを説明します。
  • @ApiResponse: HTTPレスポンスの個々の説明を提供します。
  • @ApiResponses: HTTPレスポンス全体の説明を提供します。
  • @ApiIgnore: このAPIをドキュメント生成から除外します。
  • @ApiError: エラー発生時のレスポンス情報を記述します。
  • @ApiParamImplicitL: 単一のリクエストパラメータを記述します。
  • @ApiParamsImplicit: 複数のリクエストパラメータを記述します。

Swaggerの統合

Swaggerの統合は比較的簡単です。ここでは、以前のプロジェクトを基に修正を加えます。まず、Swagger関連の依存関係をpom.xmlに追加します。


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

Swagger2設定クラスの作成

起動クラスと同じパッケージレベルに、Swagger2の設定クラスを作成します。


package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // APIドキュメントを生成するパッケージを指定
                .apis(RequestHandlerSelectors.basePackage("com.example.controller")) 
                .paths(PathSelectors.any())
                .build();
    }

    // APIドキュメントの詳細情報を構築するメソッド
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot RESTful APIs with Swagger 2")
                .contact(new Contact("Developer Name", "https://example.com", "dev@example.com"))
                .version("1.0")
                .description("User management API documentation")
                .build();
    }
}
  

ControllerでのAPI情報設定

UserControllerにAPIの情報を設定します。


package com.example.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.mapper.UserMapper;
import com.example.model.User;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(tags = "User Management API") // Controller全体をユーザー管理APIとしてタグ付け
@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @Autowired
    private UserMapper userMapper;
    
    @ApiOperation(value = "全ユーザーリスト取得", notes = "システム内の全ユーザー情報を取得します。", httpMethod = "GET")
    @GetMapping
    public List<User> getAllUsers() {
        return userMapper.findAll();
    }
    
    @ApiOperation(value = "ユーザー情報取得", notes = "指定されたIDのユーザー情報を取得します。", httpMethod = "GET")
    @ApiImplicitParam(name = "userId", value = "取得するユーザーのID", required = true, dataType = "String", paramType = "path")
    @GetMapping("/{userId}")
    public User getUserById(@PathVariable("userId") String id) {
        return userMapper.findById(id);
    }
    
    @ApiOperation(value = "新規ユーザー登録", notes = "新しいユーザー情報を登録します。", httpMethod = "POST")
    @ApiImplicitParam(name = "user", value = "登録するユーザー情報", required = true, dataType = "User", paramType = "body")
    @PostMapping
    public String createUser(@RequestBody User user) {
        int result = userMapper.save(user);
        return result > 0 ? "success" : "error";
    }
    
    @ApiOperation(value = "ユーザー情報更新", notes = "指定されたIDのユーザー情報を更新します。", httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "更新するユーザーのID", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "user", value = "更新後のユーザー情報", required = true, dataType = "User", paramType = "body")
    })
    @PutMapping("/{userId}")
    public String updateUser(@PathVariable("userId") String id, @RequestBody User user) {
        // IDをUserオブジェクトに設定して更新
        user.setId(id); 
        int result = userMapper.update(user);
        return result > 0 ? "success" : "error";
    }

    @ApiOperation(value = "ユーザー情報削除", notes = "指定されたIDのユーザー情報を削除します。", httpMethod = "DELETE")
    @ApiImplicitParam(name = "userId", value = "削除するユーザーのID", required = true, dataType = "String", paramType = "path")
    @DeleteMapping("/{userId}")
    public String deleteUser(@PathVariable("userId") String id) {
        int result = userMapper.deleteById(id);
        return result > 0 ? "success" : "error";
    } 
}
  

MapperScanの設定

起動クラスに@MapperScanアノテーションを追加し、Mapperインターフェースのパッケージを指定します。


// Example of Spring Boot Application class
@SpringBootApplication
@MapperScan("com.example.mapper") // Mapperインターフェースのパッケージを指定
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  

アプリケーションを起動し、ブラウザで http://localhost:8080/swagger-ui.html にアクセスすると、Swagger UIが表示され、APIドキュメントを確認できます。

以下は、プロジェクトの構造図です。

タグ: Spring Boot Swagger OpenAPI REST API Java

6月25日 17:53 投稿