본문 바로가기

개발 지식/개념

SWAGGER :: 스웨거 테스트 자동화 도구

 

 

Swagger

REST API를 문서화하고 테스트할 수 있는 도구

 

 

1. 프로젝트에 Swagger 의존성 추가

<dependencies>
    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>1.6.4</version>
    </dependency>
</dependencies>

 

 

2. Swagger 기본 설정

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;
import org.springframework.context.annotation.Configuration;

@Configuration
@OpenAPIDefinition(
    info = @Info(
        title = "My API",
        version = "1.0",
        description = "API 문서 예시"
    )
)
public class SwaggerConfig {
    // 별도의 설정을 추가
}

 

 

3. Swagger 어노테이션 사용하여 API 문서화
각 엔드포인트를 문서화하기 위해 Swagger 어노테이션을 사용

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Operation(summary = "모든 유저 조회", description = "모든 유저 정보를 조회합니다.")
    @ApiResponse(responseCode = "200", description = "유저 목록이 반환됩니다.")
    @GetMapping
    public List<User> getAllUsers() {
        // 비즈니스 로직 처리
        return userService.getAllUsers();
    }

    @Operation(summary = "특정 유저 조회", description = "유저 ID로 특정 유저를 조회합니다.")
    @ApiResponse(responseCode = "200", description = "유저 정보가 반환됩니다.")
    @GetMapping("/{id}")
    public User getUserById(
        @Parameter(description = "조회할 유저 ID") 
        @PathVariable Long id) {
        // 비즈니스 로직 처리
        return userService.getUserById(id);
    }
}

 

 

4. Swagger UI에서 API 문서 확인

이 페이지에서 API 문서를 보고, 직접 API를 테스트할 수 있다.

http://localhost:8787/swagger-ui/index.html
//본인 포트 번호 넣으면 된다

 

 

5. 세부 기능

import io.swagger.v3.oas.annotations.media.Schema;

@Schema(description = "유저 정보 객체")
public class User {
    @Schema(description = "유저 ID", example = "1")
    private Long id;

    @Schema(description = "유저 이름", example = "홍길동")
    private String name;

    // getter, setter
}

 

파라미터 설명: 각 요청 파라미터에 대해 설명을 추가 가능

@Parameter(description = "조회할 유저의 ID", required = true)

 

응답 코드와 설명 추가: 엔드포인트에서 가능한 응답 코드와 그에 대한 설명을 추가 가능

@ApiResponse(responseCode = "200", description = "정상 응답")
@ApiResponse(responseCode = "404", description = "해당 유저를 찾을 수 없음")

 

 

6. 테스트
Swagger UI를 통해 API를 직접 테스트할 수 있다. 각 엔드포인트에 대한 설명과 파라미터, 요청 본문 등을 설정하고 API를 실행하여 결과를 확인할 수 있다.