Swagger 설정 및 사용방법

wjd15sheep·2024년 6월 16일
2

Spring Boot

목록 보기
6/19

Swagger란?

Swagger는 RESTful API를 설계하고 문서화하는데 사용되는 오픈 소스 프레임워크입니다.
Swagger는 API의 구조를 정의하는데 사용할 수 있는 여러 도구와 라이브러리를 제공합니다. 이를 통해 API의 구조를 정의하는데 사용할 수 있는 여러 도구와 라이브러리를 제공합니다. 이를 통해 API 문서를 자동으로 생성하고, API를 테스트하는 인터페이스를 제공할 수 있습니다.

장점

  • 자동화된 문서화
    Swagger는 API문서를 자동으로 생성해주기 때문에 개발자가 일일이 문서를 작설할 필요가 없습니다.
  • 시간적 인터페이스
    Swagger UI를 통해 API를 시각적으로 테스트하고 탐색할 수 있습니다.
  • 표준화
    Swagger는 OpenAPI Specification(OAS)을 사용하여 API 문서화를 표준화합니다. 이를 통해 다른 팀이나 회사에서도 쉽게 이해하고 사용할 수 있습니다.
  • 코드 생성
    Swagger는 클라이언트 SDK와 서버 스텁 코드를 자동으로 생성할 수 있습니다.
  • API 테스트
    Swagger UI를 통해 API를 직접 호출하고 테스트 할 수 있습니다.

단점

  • 초기 설정
    프로젝트에서 Swagger를 설정하고 통합하는 초기 과정이 다소 복잡할 수 있습니다.
  • 오버헤드
    Swagger를 사용하면 API 문서화와 관련된 추가 코드와 설정이 필요해지기 때문에 프로젝트 규모가 커질수록 관리가 복잡해질 수 있습니다.
  • 실시간 반영 제한
    코드 변경 사항이 항상 실시간으로 문서화에 반영되지 않을 수 있습니다. 주기적으로 문서를 업데이트해야 할 필요가 있습니다.

사용 방법

설정

  • Swagger 라이브러리를 프로젝트에 추가합니다.
    build.gradle dependencies에 한 줄을 추가 합니다.
    (Spring boot 3.0 버전부터 하나만 선언

    dependencies {
    // swagger
    implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'
    }
  • Swagger 설정 파일을 생성합니다.
    config 폴더 안에 Swagger.class(yaml) 파일을 생성
    Swagger의 기본적의 정보를 정의한 파일입니다.

    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 Swagger {
    
    	@Bean
        public OpenAPI openAPI() {
    	    return new OpenAPI()
        	        .info(info);
    	}
        
        Info info = new Info().title("Swagger Test").version("0.0.1").description(
            "<h3>Swagger test</h3>");
    }

Controller

컨트롤러에서 Swagger 어노테이션을 사용하는 방법입니다.

  • @Tag
    API 엔드포인트를 그룹화하는데 사용합니다.

  • @Operation
    API 메서드에 대한 문서화 정보를 제공합니다.
    메서드의 설명, 요청/응답 모델, 파라미터 등을 지정할 수 있습니다.

  • @ApiResponses
    Swagger에서 API 메서드의 응답 정보를 문서화하는 데 사용되는 주석(Annotation)입니다.

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Tag(name = "Example Controller", description = "This is an example controller")
public class ExampleController {

    @GetMapping("/hello")
     @Operation(summary = "accountId 조회", description = "accessKey와 secretKey로 accountId를 조회하는 메서드입니다.",
            parameters = {
                    @Parameter(in = ParameterIn.HEADER, name = "region", description = "test1", required = true, example = "test1"),
                    @Parameter(in = ParameterIn.HEADER, name = "access-key", description = "test2", required = true, example = "test2"),
                    @Parameter(in = ParameterIn.HEADER, name = "secret-access-key", description = "test3", required = true, example = "test3")
            })
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "조회 성공", content = @Content(schema = @Schema(implementation = BaseResponseStatus.class),
                    examples = {@ExampleObject(
                            name = "SuccessRequestExample",
                            value = "{\"success\": true, \"id\": -\"}"
                    ),
                            @ExampleObject(
                                    name = "BadRequestExample",
                                    value = "{\n" +
                                            "  \"success\":false,\n" +
                                            "  \"id\":\"\",\n" +
                                            "  \"message\":\"The security token included in the request is invalid. (Service: Sts, Status Code: 403, Request ID: -)\"\n" +
                                            "}"
                            )
                    })),
            @ApiResponse(responseCode = "400", description = "조회 실패", content = @Content(
                    examples = @ExampleObject(
                            name = "ClientBadRequestExample",
                            value = "{\n" +
                                    "  \"timestamp\": \"2024-06-16T06:36:10.860+00:00\",\n" +
                                    "  \"status\": 400,\n" +
                                    "  \"error\": \"Bad Request\",\n" +
                                    "  \"path\": \"test\n" +
                                    "}"
                    ))),
            @ApiResponse(responseCode = "500", description = "서버 응답 실패", content = @Content(
                    examples = @ExampleObject(
                            name = "ServerBadResponseExample",
                            value = "{\n" +
                                    "  \"timestamp\": \"2024-06-04T06:51:14.175+00:00\",\n" +
                                    "  \"status\": 500,\n" +
                                    "  \"error\": \"Internal Server Error\",\n" +
                                    "  \"path\": \"/test\"\n" +
                                    "}"
                    ))),
    })
}

DTO

  • @Schema
    Swagger에서 API 요청/응답 모델의 스키마 정보를 문서화하는 데 사용되는 주석(Annotation)입니다.
    @Schema의 주요 속성은 다음과 같습니다
    • name: 모델의 이름을 지정합니다.
    • description: 모델에 대한 설명을 제공합니다.
    • required: 필수 필드를 지정합니다.
    • properties: 모델의 필드 정보를 제공합니다.
    • implementation: 모델을 구현하는 클래스를 지정합니다.
import io.swagger.v3.oas.annotations.media.Schema;

public class UserDto {

    @Schema(description = "The unique identifier of the user", example = "1")
    private Long id;

    @Schema(description = "The name of the user", example = "John Doe")
    private String name;

    // Getters and Setters
}

위와 같이 설정한다면 애플리케이션을 실행하고 http://localhost:8080/swagger-ui.html로 들어간다면 Swagger UI에 API 메서드의 정의한 내용 및 API 테스트를 할 수 있습니다.


[참고]

profile
성장 위해 노력하는 웹 개발자 주니어

0개의 댓글