Dev

Swagger 사용하기

khjoon 2024. 12. 4. 21:06

Swagger

  • API 문서화 자동화 툴
  • 어떤 API가 있고 해당 API를 쓰기 위한 양식을 알려주고 API를 호출해보고 테스트 할 수 있다.
  • 프론트에서 API를 쉽고 빠르게 이해하기 위해 활용한다.

SpringDoc

  • Swagger UI를 만들고 Swagger annotation을 제공하는 라이브러리이다.
  • SpringFox UI와 SpringDoc UI가 있는데 spring의 버전이 올라갈수록 SpringFox는 지원을 못하는 경우가 많다.

dependency 설정

implementation 'org.springdoc:springdoc-openapi-ui:1.6.15'

Swagger Configure 작성

import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import io.swagger.v3.oas.models.Components; 
import io.swagger.v3.oas.models.OpenAPI; 
import io.swagger.v3.oas.models.info.Info; 
@Configuration 
public class OpenApiConfig { 
/** * OpenAPI bean 구성 * @return */
@Bean public OpenAPI openAPI() { 
    Info info = new Info() 
                    .title("swagger 테스트") 
                    .version("1.0") 
                    .description("API에 대한 설명 부분"); 
       return new OpenAPI() .components(new Components()) .info(info); 
    } 
}

Swagger 관련 annotation

  • annotation을 이용하면 API의 설명, 매개변수, 반환형 등의 메타 데이터를 기술할 수 있다.
    • Swagger는 JavaDoc을 이용해서 API 메타 데이터를 읽고, 메타 데이터를 Swagger UI에 제공한다.
  • Spring framework의 기본 annotation만 사용해도 Swagger UI를 만들 수 있지만 디테일한 정보를 표기할 때 annotation을 사용한다.
  • import io.swagger.v3.oas.annotations 라이브러리에 있는 annotaion 사용

@Tag

  • Domain 단위로 API를 그룹화할 때 사용 Controller class에 annotation 작성

예시:

@RestController  
@Tag(name = "User",description = "유저 Domain")

Operation

  • 어떤 리소스를 나타내는지 간략한 설명 추가할 수 있다.
  • 예시:
    @GetMapping("/users/login) 
    @Operation(summary ="로그인 API ", description = "클라이언트 요구사항 적기 " )

@ApiResponse

  • 해당 API의 Response 정보들을 나타낼수 있다.
  • ApiResponse가 여러개일 때 @ApiResponses로 묶어서 표현

예시 :

@ApiResponses({
          @ApiResponse(responseCode = "COMMON200",description = "OK, 성공"),
          @ApiResponse(responseCode = "AUTH003", description = "access 토큰을 주세요!",content = @Content(schema = @Schema(implementation = ApiResponse.class))),
          @ApiResponse(responseCode = "AUTH004", description = "acess 토큰 만료",content = @Content(schema = @Schema(implementation = ApiResponse.class))),
          @ApiResponse(responseCode = "AUTH006", description = "acess 토큰 모양이 이상함",content = @Content(schema = @Schema(implementation = ApiResponse.class)))})

@Parameter

  • API의 parameter에 대한 설명을 위한 annotation이다.

예:

@Parameter(name = "userId", description = "유저의 아이디입니다.")

@Schema

  • Request, Response 객체에 대한 설정을 위한 annotation이다.
  • description으로 설명을 추가할 수 있고 defaultValue로 기본적으로 사용할 값 설정할 수 있고 example을 통해 예시 설정 가능
    @Getter
    @AllArgsConstructor
    public static class ApiResponse {
      @Schema(description = "성공")
      private String success;
      @Schema(description = "토큰")
      private String token;
    }