NGMsoftware

NGMsoftware
로그인 회원가입
  • 매뉴얼
  • 학습
  • 매뉴얼

    학습


    Web Spring boot에서 Swagger를 이용한 API 문서화.

    페이지 정보

    본문

    안녕하세요. 엔지엠소프트웨어입니다. 웹프로젝트를 처음 시작할 때 준비해야 하는것들이 몇가지 있습니다. DevOps부터 Documentation까지 필수로 해야 하는것들입니다. 스프링부트 프로젝트인 경우에는 대부분 RESTful을 이용한 서비스를 제공할겁니다. Backend에서 Frontend로 데이타를 내려주는 모든 행위를 서비스라고 부릅니다. 이 서비스들은 보통 RESTful을 이용한 API이거나 웹서비스(Web Service)입니다.

    [ Spring boot 프로젝트 만들기 ]

     

    스프링 프로젝트에서 그래들(Gradle)을 사용하면 build.gradle에 아래 패키지를 추가해야 합니다.

    implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'

     

    InfluxDB를 사용중이라면 아래 패키지도 같이 추가하세요. (InfluxDB Properties 초기화 에러가 발생할 수 있습니다.)

    implementation group: 'org.hibernate', name: 'hibernate-validator', version: '6.1.1.Final'

     

    SwaggerConfig.java 파일을 추가하고, 아래와같이 코드를 작성하세요.

    @Configuration
    public class SwaggerConfig {
    
        @Bean
        public OpenAPI openAPI(@Value("v2") String version) {
    
            Info info = new Info().title("NGMsoftware Service APIs").version(version)
                    .description("OpenAPI")
                    .contact(new Contact().name("- NGMaster").email("ngmaster@ngmsoftware.com"));
    
            return new OpenAPI()
                    .components(new Components())
                    .info(info);
        }
    
        @Bean
        public GroupedOpenApi main() {
            return GroupedOpenApi.builder()
                    .group("main")
                    .pathsToMatch("/api/v1/**")
                    .build();
        }
    
        @Bean
        public GroupedOpenApi group1() {
            return GroupedOpenApi.builder()
                    .group("그룹1")
                    .pathsToMatch("/api/v1/editor/**")
                    .build();
        }
    
        @Bean
        public GroupedOpenApi group2() {
            return GroupedOpenApi.builder()
                    .group("그룹2")
                    .pathsToMatch("/api/v1/player/**")
                    .build();
        }
    }

     

    프로젝트를 실행하고, localhost:8080/swagger-ui/index.html로 이동해보세요. 프로젝트의 API를 확인할 수 있고, 테스트도 가능합니다. 혼자서 진행하는 간단한 프로젝트라면 Postman을 사용해도 충분합니다. 하지만, 3명 이상의 팀이 협업해야 한다면 스웨거를 이용하시는게 효율적입니다. CI/CD를 통해 특정 서버에 배포가 되면, Frontend 개발자들이 API를 확인하고 페이지를 만들 수 있기 때문입니다. 스웨거를 사용하지 않는다면 Backend 개발자가 문서를 작성해서 전달해야 하는데~ 프로젝트 초기에 빈번하게 발생되는 변경에 대해 문서를 수정하는건 매우 번거로운 일입니다.

    7U8S4NK.png

     

     

    @Tag 어노테이션(Annotation)은 name이 같은 api를 하나의 그룹으로 묶어줍니다. 주로 Controller나 Controller의 Method에 설정합니다.

    @Tag(name = "editor", description = "매크로 에디터 API")
    @RestController
    @RequiredArgsConstructor
    @RequestMapping("/api/v1/")
    public class EditorApiController {
        ...

     

    @Schema 어노테이션은 모델의 정보를 표시합니다. 스키마(Schema)를 작성하면 완성도 높은 Swagger UI 문서를 만들 수 있습니다. 보통 Model 또는 DTO를 말하며 이들 클래스의 속성 정보입니다. 아래 코드와 같이 모델의 명세를 친절하게 작성 해줍니다.

    @Schema(description = "매크로 에디터 라이센스 정보")
    @Getter
    public class EditorInfoModel {
        @Schema(description = "일자")
        private Long id;
    
        @Schema(description = "에디터 정보", defaultValue = "라이센스", allowableValues = {"기간", "갯수"})
        private String title;
    
        @Schema(description = "내용")
        private String content;
    
        @Schema(description = "수정일자")
        private LocalDateTime modifiedDate;
    
        public PostsListResponseDto(EditorInfoModel editor) {
            this.id = editor.getId();
            this.title = editor.getTitle();
            this.content = editor.getContent();
            this.modifiedDate = editor.getModifiedDate();
        }
    }

     

    아래와 같이 패턴을 추가할수도 있습니다.

    @Pattern(regexp = "[1-2]")
    @Schema(description = "성별", defaultValue = "1", allowableValues = {"1", "2"})
    private String sex;
    
    @DateTimeFormat(pattern = "yyMMdd")
    @Schema(description = "생년월일", example = "yyMMdd", maxLength = 6)
    private String birthDate;

     

    @Operation 어노테이션은 API 동작에 대한 명세를 작성할 때 사용합니다. summary에 간략한 정보를 입력하고, 자세한 내용은 description에 작성 해줍니다.

    @PostMapping("/editor")
    @Operation(summary = "에디터 정보", description = "엔지엠 에디터의 라이센스 정보를 가져옵니다.")
    public LicenseModel getLicense(@RequestBody EditorLicenseInfo editorModel) {
        return editorService.license(editorModel);
    }

     

    @ApiResponses, @ApiResponse는 API 요청(Request)에 대한 응답(Response) 구조를 미리 확인할 수 있도록 해줍니다. Frontend 개발자는 이 내용을 확인하여 메세지 처리나 예외 처리를 작성할 수 있습니다. ApiResponse를 작성하지 않으면 Swagger UI에서는 상태코드 200과 비어있는 Response Body를 보여줍니다. 일반적으로 스프링 웹프로젝트의 경우 REST Handler를 재정의해서 사용합니다. 그래서, 별도로 ApiResponse를 작성하지 않아도 핸들러에 작성되어 있는 기본 값들이 표시됩니다.

    @PostMapping("/editor")
    @Operation(summary = "에디터 정보", description = "엔지엠 에디터의 라이센스 정보를 가져옵니다.")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "조회 성공", content = @Content(schema = @Schema(implementation = LicenseModel.class))),
            @ApiResponse(responseCode = "404", description = "조회 실패", content = @Content(schema = @Schema(implementation = ErrorResponse.class))) })
    @GetMapping("/license/{id}")
    public LicenseModel getLicense(@PathVariable long id) {
        return editorService.license(id);
    }

     

    마지막으로 @Parameter 어노테이션에 대해 알아볼까요? 파라메터는 ResponseBody가 아닌 인자(Argument)에 대한 설명을 작성할 수 있습니다.

    @PostMapping("/editor")
    @Operation(summary = "에디터 정보", description = "엔지엠 에디터의 라이센스 정보를 가져옵니다.")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "조회 성공", content = @Content(schema = @Schema(implementation = LicenseModel.class))),
            @ApiResponse(responseCode = "404", description = "조회 실패", content = @Content(schema = @Schema(implementation = ErrorResponse.class))) })
    @GetMapping("/license/{id}")
    public LicenseModel getLicense(@Parameter(name = "id", description = "사용자의 id", in = ParameterIn.PATH) @PathVariable Long id) {
        return editorService.license(id);
    }

     

    path로부터 들어올 파라메터인 id에 대해 설정을 추가 했습니다. @Parameter나 @Operation에 파라메터를 설정하는 경우 어떤 파라메터에 대한 설명인지 알 수 없기 때문에 name은 꼭~ 추가해주는게 좋습니다. 일부 속성들은 생략해도 크게 문제가 되지 않습니다. 하지만, 가급적이면 자세하게 작성하는게 좋습니다. 내가 보기위해 작성하는게 아닌 다른 개발자가 이 내용을 참고해서 개발하게 하기 위함이니까요.

     

    개발자에게 후원하기

    MGtdv7r.png

     

    추천, 구독, 홍보 꼭~ 부탁드립니다.

    여러분의 후원이 빠른 귀농을 가능하게 해줍니다~ 답답한 도시를 벗어나 귀농하고 싶은 개발자~

    감사합니다~

    • 네이버 공유하기
    • 페이스북 공유하기
    • 트위터 공유하기
    • 카카오스토리 공유하기
    추천0 비추천0

    댓글목록

    등록된 댓글이 없습니다.