| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 1차원 DP
- 2차원 dp
- 99클럽
- @BeforeAll
- @BeforeEach
- @Builder
- @Entity
- @GeneratedValue
- @GenericGenerator
- @NoargsConstructor
- @Query
- @Table
- @Transactional
- Actions
- Amazon EFS
- amazon fsx
- Android Studio
- ANSI SQL
- api gateway 설계
- api gateway 필터
- ApplicationEvent
- argocd
- assertThat
- async/await
- AVG
- AWS
- aws autoscaling
- aws eks
- aws iam role
- AWS KMS
- Today
- Total
기록
[Swagger] annotation 정리 본문
1. 들어가며
Swagger(OpenAPI)는 단순히 API 목록을 보여주는 도구가 아니라, 코드에 어노테이션을 부여해 API의 목적, 요청 구조, 응답 모델을 명세화하는 문서 도구이다. 이 글에서는 OpenAPI 3.x 기준으로 자주 사용하는 Swagger 어노테이션을 정리한다.
2. 어노테이션 기반 문서화의 구조
Spring Boot에서 springdoc-openapi는 Controller, DTO, Validation 정보를 스캔해 /v3/api-docs에 반영한다. 이때 Swagger 어노테이션들은 각 역할별로 다음처럼 매핑된다.
| 적용 범위 | 어노테이션 | 역할 |
| API 그룹 | @Tag | 컨트롤러 단위 그룹 지정 |
| 개별 엔드포인트 | @Operation | API 요약 및 상세 설명 |
| 파라미터 | @Parameter | Path, Query, Header 등 파라미터 정의 |
| 요청 본문 | @RequestBody, @Schema | 요청 DTO 구조 정의 |
| 응답 | @ApiResponse, @ApiResponses | 상태 코드별 응답 명세 |
| 데이터 모델 | @Schema | 필드 수준 설명 및 예시 정의 |
참고: Swagger 공식 어노테이션 문서
참고: springdoc-openapi Annotations Reference
3. Controller 문서화
Swagger는 @RestController 클래스에 @Tag를 부여해 API 그룹을 구분한다.
각 메서드에는 @Operation을 이용해 요약과 설명을 추가하고, @ApiResponse를 통해 응답 상태를 정의한다.
@Tag(name = "사용자 관리", description = "사용자 CRUD 관련 API")
@RestController
@RequestMapping("/api/users")
public class UserController {
@Operation(summary = "사용자 등록", description = "새로운 사용자를 등록한다.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "정상 등록 완료"),
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터")
})
@PostMapping
public UserResponse registerUser(@RequestBody UserRequest request) {
return new UserResponse(1L, request.getName(), request.getEmail());
}
@Operation(summary = "사용자 목록 조회", description = "전체 사용자 목록을 조회한다.")
@ApiResponse(responseCode = "200", description = "성공")
@GetMapping
public List<UserResponse> getUsers() {
return List.of(new UserResponse(1L, "홍길동", "hong@test.com"));
}
@Operation(summary = "사용자 단건 조회", description = "ID로 사용자를 조회한다.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "성공"),
@ApiResponse(responseCode = "404", description = "사용자 없음")
})
@GetMapping("/{id}")
public UserResponse getUser(
@Parameter(description = "사용자 ID", example = "1") @PathVariable Long id) {
return new UserResponse(id, "홍길동", "hong@test.com");
}
}
4. DTO 문서화
요청(Request)과 응답(Response) DTO에는 @Schema를 적용하여 각 필드의 의미와 예시를 명시할 수 있다. 이 정보는 Swagger UI에서 자동으로 표시된다.
@Schema(description = "사용자 등록 요청")
public class UserRequest {
@Schema(description = "사용자 이름", example = "홍길동")
private String name;
@Schema(description = "이메일 주소", example = "hong@test.com")
private String email;
}
@Schema(description = "사용자 응답 모델")
public class UserResponse {
@Schema(description = "사용자 ID", example = "1")
private Long id;
@Schema(description = "이름", example = "홍길동")
private String name;
@Schema(description = "이메일", example = "hong@test.com")
private String email;
}
Swagger UI에서는 필드 이름뿐 아니라 설명과 예시 값이 함께 표시되어 문서 품질이 높아진다.
5. 주요 어노테이션 요약
Swagger 어노테이션의 핵심 속성을 표로 정리하면 다음과 같다.
| 어노테이션 | 적용 위치 | 주요 속성 | 설명 |
| @Tag | 클래스 | name, description | 컨트롤러 단위 그룹 정의 |
| @Operation | 메서드 | summary, description, tags | API의 목적과 상세 설명 |
| @Parameter | 메서드 파라미터 | description, example, required | Path/Query/헤더 파라미터 설명 |
| @ApiResponse | 메서드 | responseCode, description, content | 상태 코드별 응답 설명 |
| @Schema | 클래스/필드 | description, example, defaultValue | DTO 필드 정의 및 예시 |
OpenAPI Specification Reference: Operation Object, Schema Object
6. 복합 응답 구조 정의
공통 응답 포맷(Response Wrapper)을 사용하는 경우, @ApiResponse와 @Schema를 조합해 응답 구조를 정의한다.
@Operation(summary = "사용자 조회", description = "ID로 사용자 정보를 조회한다.")
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "성공",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = UserResponse.class)
)
),
@ApiResponse(responseCode = "404", description = "사용자 없음")
})
@GetMapping("/{id}")
public UserResponse getUser(@PathVariable Long id) { ... }
Swagger UI에서는 “200” 응답을 클릭하면 UserResponse의 필드 구조가 자동 표시된다.
7. JSON 예시 자동 생성
요청 DTO에 예시 값을 설정하면 Swagger UI가 자동으로 예시 JSON을 생성한다.
@Schema(description = "사용자 등록 요청", example = "{\"name\": \"홍길동\", \"email\": \"hong@test.com\"}")
public class UserRequest { ... }
또는 각 필드에 example을 지정하면 Swagger가 전체 예시를 조합한다. 이 기능은 실제 요청 테스트 시 “Try it out” 영역의 JSON 초기값으로 사용된다.
'Web > Spring' 카테고리의 다른 글
| [Kafka × Elasticsearch 기반 상품 검색 시스템] 1. 상품 검색 엔진 설계 (0) | 2025.11.24 |
|---|---|
| [Swagger] Swagger에서 JWT 인증 처리하기 (0) | 2025.10.26 |
| [Swagger] Spring Boot 프로젝트에 Swagger 설정하기 (0) | 2025.10.26 |
| Spring Boot 멀티모듈 프로젝트 빌드 실패 - 루트 프로젝트의 bootJar 설정 누락 (0) | 2025.07.06 |
| Spring 프로필, Gradle, JVM 옵션: -Dspring.profiles.active (0) | 2025.04.26 |