반응형

Swagger3

dependencies

implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.1.0")

application.properties

springdoc.swagger-ui.operations-sorter=method

SwaggerConfig

@Configuration
public class SwaggerConfig {
    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
            .info(new Info()
                .title("demo-api")
                .description("demo-api document")
                .version("v1.0.0")
            );
//            .components(new Components()
//                // 인증 헤더 설정 버튼 노출
//                .addSecuritySchemes(
//                    "Authorization",
//                    new SecurityScheme()
//                        .name("Authorization")
//                        .type(SecurityScheme.Type.HTTP)
//                        .scheme("Bearer")
//                        .bearerFormat("JWT")
//                )
//            );
    }

//    @Bean
//    public GroupedOpenApi authorizedApi() {
//        return GroupedOpenApi.builder()
//            .group("API - authorized")
//            .packagesToExclude("/api/v**/authentication")
//            .addOpenApiCustomizer(openApi -> {
//                // 공통 헤더 설정
//                openApi.getPaths().values().forEach(operation -> {
//                    operation.addParametersItem(new Parameter()
//                        .name("TX_DEVICE_ID")
//                        .in("header")
//                        .description("디바이스 아이디")
//                        .required(true)
//                        .schema(new StringSchema())
//                    );
//                });
//
//                // 인증 헤더 설정
//                openApi.security(List.of(
//                    new SecurityRequirement().addList("Authorization")
//                ));
//            })
//            .build();
//    }
}

DemoController

@Tag(name = "데모 API", description = "데모 API입니다.")
@RestController
public class DemoController {
    @GetMapping("/api/demo/basic")
    public void basic() {
    }

    @Hidden
    @GetMapping("/api/demo/hidden")
    public void hidden() {
    }

    @Operation(summary = "echo api", description = "파라미터로 전달 받은 문자열을 그대로 응답")
    @GetMapping("/api/demo/echo")
    public String echo(
        @Parameter(description = "응답으로 전달할 파라미터")
        @RequestParam String message
    ) {
        return message;
    }

    @Operation(
        summary = "login api",
        description = "파라미터 검증 후 로그인 처리를 수행",
        responses = {
            @ApiResponse(responseCode = "200", description = "성공", content = @Content(schema = @Schema(implementation = LoginRes.class))),
            @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content(schema = @Schema(implementation = LoginRes.class)))
        }
    )
    @PostMapping("/api/demo/login")
    public LoginRes login(@RequestBody LoginReq req) {
        return new LoginRes(true);
    }

    @Getter
    @RequiredArgsConstructor
    public static class LoginReq {
        @Schema(description = "아이디", defaultValue = "anonymous")
        private final String id;
        @Schema(description = "비밀번호")
        private final String pw;
    }

    @Getter
    @RequiredArgsConstructor
    public static class LoginRes {
        @Schema(description = "성공여부")
        private final boolean success;
    }
}

실행 후 swagger-ui 접속

참고

Swagger2

의존성 추가

<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>

SwaggerConfig

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket apiV1() {
        String version = "v1";

        return new Docket(DocumentationType.SWAGGER_2)
            .useDefaultResponseMessages(false)
            .groupName(version)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example"))
            .paths(PathSelectors.ant("/api/v1/**"))
            .build()
            .apiInfo(apiInfo(version));
    }

    @Bean
    public Docket apiV2() {
        String version = "v2";

        return new Docket(DocumentationType.SWAGGER_2)
            .useDefaultResponseMessages(false)
            .groupName(version)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example"))
            .paths(PathSelectors.ant("/api/v2/**"))
            .build()
            .apiInfo(apiInfo(version))
            .globalResponseMessage(RequestMethod.POST, List.of(
                new ResponseMessageBuilder().code(200).message("OK !!!").build(),
                new ResponseMessageBuilder().code(404).message("NOT FOUND !!!").build(),
                new ResponseMessageBuilder().code(500).message("INTERNAL SERVER ERROR !!!").build()
            ));
    }

    private ApiInfo apiInfo(String version) {
        return new ApiInfoBuilder()
            .title("Spring API Documentation")
            .description("앱 개발시 사용되는 서버 API에 대한 연동 문서입니다")
            .license("sgchoi")
            .licenseUrl("http://sgchoi.com")
            .version(version)
            .build();
    }
}

User

@ApiModel
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
    @ApiModelProperty(value = "역할", required = true, example = "ADMIN", allowableValues = "USER, GUEST, ADMIN")
    private String role;
    @ApiModelProperty(value = "이메일", required = true, example = "test@example.com")
    private String email;
    @ApiModelProperty(value = "이름", required = false, example = "john")
    private String name;
}

UserControllerV1

@Api(value = "User API v1")
@RequestMapping("/api/v1")
@RestController
public class UserControllerV1 {
    @ApiOperation(value = "사용자 조회", notes = "사용자 단건 조회 API")
    @ApiResponses({
        @ApiResponse(code = 200, message = "OK !!"),
        @ApiResponse(code = 500, message = "Internal Server Error !!"),
        @ApiResponse(code = 404, message = "Not Found !!")
    })
    @GetMapping(value = "/users/{role}")
    public User getUser(
        @ApiParam(value = "역할", required = true, example = "ADMIN", allowableValues = "USER, GUEST, ADMIN") @PathVariable String role,
        UserParam userParam
    ) {
        return new User(role, userParam.getEmail(), "john");
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class UserParam {
        @ApiParam(value = "이메일", required = true, example = "test@example.com")
        private String email;
    }
}

UserControllerV2

@Api(value = "User API v2")
@RequestMapping("/api/v2")
@RestController
public class UserControllerV2 {
    @ApiOperation(value = "사용자 추가", notes = "사용자 추가 API")
    @PostMapping(value = "/users")
    public void saveUser(@ApiParam(value = "사용자 정보", required = true) @RequestBody User user) {
        // do nothing
    }
}

Swagger UI 접속

참고

반응형

'Development > Spring' 카테고리의 다른 글

[Spring] Cookie & Session  (0) 2020.12.27
[Spring] Cache (with Redis)  (0) 2020.12.27
[Spring] Argument Resolver  (0) 2020.12.27
[Spring] Filter & Interceptor  (0) 2020.12.27
[Spring] Validation  (0) 2020.12.27

+ Recent posts