BE/Spring Boot

[Spring Boot] Swagger란? / Swagger API 사용하기

셰욘 2025. 2. 19. 21:39
728x90

Swagger란?

 

Swagger는 RESTful API를 설계, 문서화, 그리고 테스트할 수 있도록 도와주는 오픈 소스 프레임워크

API의 설계 및 관리에 널리 사용된다.

 

공식 사이트 : https://swagger.io/

 

API Documentation & Design Tools for Teams | Swagger

Swagger and OpenAPI go hand‑in‑hand. Swagger offers powerful and easy to use tools to take full advantage of the OpenAPI Specification. See how we do it

swagger.io

 


Swagger API 사용하기

build.gradle에 추가

implementation 'org.springdoc:springdoc-openapi-starter-webflux-ui:2.8.3'

 

 

스웨거 설정 - SwaggerConfig

여기서 title과 설명을 적어준다.

 

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SwaggerConfig {
    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
                .components(new Components())
                .info(apiInfo());
    }
    
    // 스프링 버전에 따라서 Swagger의 버전도 맞춰서 변경
    private Info apiInfo() {
        return new Info()
                .title("Springdoc 테스트")
                .description("Springdoc을 사용한 Swagger UI 테스트")
                .version("1.0.0");
    }
}

 

 

 


컨트롤러 - @Tag, @Operation

컨트롤러에서는 Tag 어노테이션Operation 어노테이션을 달아서 사용해준다.

 

summary에는 이름, description에는 설명을 넣어준다.

@RequiredArgsConstructor
@RequestMapping("/a")
@RestController
@Tag(name = "A 관련 기능")
public class AController {
    private final AService aService;

    @Operation(summary = "A 등록", description = "A의 값을 등록하는 기능입니다.")
    @PostMapping("/register")
    public void register(@RequestBody ADto.ARegister dto) {
        aService.register(dto);
    }

    @Operation(summary = "A 상세 조회", description = "A의 idx 값으로 A를 조회하는 기능입니다.")
    @GetMapping("/{aIdx}")
    public ResponseEntity get(@PathVariable Long aIdx) {
        ADto.AResponse response = aService.get(aIdx);
        return ResponseEntity.ok().body(response);
    }

    @Operation(summary = "A 전체 조회", description = "A의 전체 목록을 조회하는 기능입니다.")
    @GetMapping("/list")
    public ResponseEntity getList() {
        List<ADto.AResponse> response  =  aService.list();
        return ResponseEntity.ok().body(response);
    }
}

 

 

 


DTO - @Schema

DTO에는 Schema 어노테이션을 붙여서 사용한다.

 

description에는 설명을 넣어주고, example에는 예시로 보여줄 값을 넣어준다.

public class ADto {
    @Getter
    public static class ARegister{
        @Schema(description = "A의 값", example = "a 01")
        private String value;
        private List<BRegister> bs;
        public A toEntity() {
            return A.builder()
                    .value(value)
                    .build();
        }
    }

    @Getter @NoArgsConstructor @AllArgsConstructor @Builder
    public static class AResponse {
        @Schema(description = "A 번호")
        private Long idx;
        @Schema(description = "A 값")
        private String value;
        @Schema(description = "B 리스트")
        private List<BResponse> bs;
        public static AResponse from(A a) {
            return AResponse.builder()
                    .idx(a.getIdx())
                    .value(a.getValue())
                    .bs(a.getB().stream().map(BResponse::from).toList())
                    .build();
        }
    }

    @Getter @NoArgsConstructor @AllArgsConstructor @Builder
    public static class BResponse {
        @Schema(description = "B 번호")
        private Long idx;
        @Schema(description = "B 값")
        private String value;

        public static BResponse from(B b) {
            return BResponse.builder()
                    .idx(b.getIdx())
                    .value(b.getValue())
                    .build();
        }
    }
}

 

 

 


Swagger API 문서

http://localhost:8080/swagger-ui/index.html#/ 에 들어가면 확인할 수 있다.

 

 

 

 

api마다 확인할 수 있다.

 

 

728x90