개발바닥곰발바닥
article thumbnail
728x90

Swagger-ui로 API Docs 자동화하기

기존에 Notion을 사용해서 API 명세서를 작성하다가, API 서버에 변경이 생기면 문서도 같이 수정해줘야 하는 번거로움에 자동화의 필요성을 느껴 Swagger를 적용하게 되었다. Spring Boot에서 Swagger를 적용하여 API 문서를 작성하는 방법에 대해 알아보도록 하자 🙉

의존성 추가

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

Swagger-ui를 사용하기 위해 gradle에 Springdoc 의존성을 추가해준다. swagger를 사용하는 다른 라이브러리로는 Springfox도 있지만, 활발히 업데이트가 이루어지는 Springdoc에 비해 2020년 이후로 업데이트가 이루어지지 않고 있기 때문에 Springdoc을 사용하게 되었다.

Springdoc은 OpenAPI를 지원하기 위한 라이브러리로 Springdoc에서 지원하는 기능은 아래와 같다.

  • OpenAPI 3
  • Spring-boot (v1 and v2)
  • JSR-303, specifically for @NotNull, @Min, @Max, and @Size.
  • Swagger-ui
  • OAuth 2
  • GraalVM native images

SwaggerConfig 생성

@Configuration
public class SwaggerConfig {
	@Bean
	public OpenAPI customOpenAPI() {
		return new OpenAPI()
			.components(new Components())
			.info(new Info().title("Sample API").version("1.0")
				.description("Sample API 명세서"));
	}
}

API와 Swagger-ui의 연동을 위해 Configuration 클래스를 생성하여 OpenAPI를 Bean으로 등록해준다.

이 떄 version같은 경우는 properties 파일에서 관리할 수도 있다.

Spring Security 설정

@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/swagger-ui/**", "/v3/api-docs/**");
	}

Spring Security를 사용하는 경우 swagger-ui에 대해 무시하지 않으면 접속이 되지 않으므로 ignoring 설정을 해주어야 한다. swagger-ui와 api-docs에 대해 무시하도록 설정한다.

Controller에 Swagger 적용하기

@Operation(summary = "회원가입", description = "아이디와 비밀번호로 회원가입합니다.")
	@ApiResponses({
		@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = AuthResponse.class), mediaType = MediaType.APPLICATION_JSON_VALUE)),
		@ApiResponse(responseCode = "400", description = "BAD REQUEST", content = @Content(schema = @Schema(implementation = ErrorResponse.class), mediaType = MediaType.APPLICATION_JSON_VALUE))
	})
	@PostMapping("/signup")
	public ResponseEntity<BasicResponse> signup(
		@Validated(ValidationSequence.class) @RequestBody AuthRequest authRequest) {
		//...
	}

Operation : 해당 API 메소드에 대한 설명

ApiResponse : 200, 400, 404 등 각 Response에 대한 설명 및 Response 값은 content에서 schema로 설정할 수 있고 mediaType에 대해 설정할 수 있다.

위 예시 코드에선 Request Body로 데이터를 보내기 때문에 적혀있지 않지만 Request Paramter를 전송하는 경우 @Parameter 어노테이션을 사용해 Parameter에 대한 설명을 기술할 수 있다.

적용 결과

 

참고 (springdoc 공식 문서)

https://springdoc.org/

 

OpenAPI 3 Library for spring-boot

Library for OpenAPI 3 with spring boot projects. Is based on swagger-ui, to display the OpenAPI description.Generates automatically the OpenAPI file.

springdoc.org

 

728x90
profile

개발바닥곰발바닥

@bestinu

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!