Spring Swagger란?
Swagger는 RESTful API의 문서를 자동으로 생성해주는 도구입니다. Spring Boot 프로젝트에서 주로 Swagger UI를 통해 API 명세를 시각적으로 보여줍니다. 이를 통해 개발자나 클라이언트는 API의 동작 방식과 요청/응답 구조를 쉽게 이해하고 테스트가능
Swagger는 이제 **OpenAPI Specification (OAS)**로 발전했으며, Springdoc OpenAPI 라이브러리를 주로 사용
Swagger의 장점
- 자동 API 문서화: 코드 주석 기반으로 자동 문서 생성
- API 테스트 용이: Swagger UI에서 직접 API 호출 및 테스트
- 개발자 협업 강화: 명확한 API 명세 제공
- 버전 관리: API 변경에 따른 문서 자동 업데이트
Spring Boot 프로젝트에 Swagger 적용하기
1. Dependency 추가
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.7.0</version> </dependency>
2. 기본 설정
Spring Boot에서는 추가적인 설정 없이 Swagger가 바로 동작
3. API Documentation 보기
애플리케이션을 실행하고 다음 URL로 접속
- Swagger UI: http://localhost:7777/swagger-ui.html
4. Controller 예제
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class UserController
{
@GetMapping("/users/{id}") public String getUser(@PathVariable int id) {
return "User with ID: " + id;
} @PostMapping("/users") public String createUser(@RequestBody String user) {
return
"Created user: " + user; } }
Swagger 애노테이션 사용
Swagger 애노테이션을 사용
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.web.bind.annotation.*;
@RestController @RequestMapping("/api")
public class ProductController {
@Operation(summary = "Get a product by its ID")
@ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Found the product", content = {@Content(mediaType = "application/json")}),
@ApiResponse(responseCode = "404", description = "Product not found", content = @Content) })
@GetMapping("/products/{id}") public String getProduct(@PathVariable int id) {
return "Product with ID: " + id; }
}
Swagger UI 커스터마이징
springdoc.swagger-ui.path=/api-docs springdoc.api-docs.path=/v3/api-docs
Swagger의 주요 대안
- Redoc: 보다 현대적이고 직관적인 UI 제공
- Postman: 문서화보다는 API 테스트에 특화
- Insomnia: Postman 대안으로 API 테스트 제공
Swagger는 효율적인 API 관리와 테스트에 매우 유용하니, 특히 RESTful 서비스를 제공할때 유용함
'Spring' 카테고리의 다른 글
Spring Security (0) | 2025.02.10 |
---|---|
WebSocket 예제 (0) | 2024.12.05 |
WebSocket (0) | 2024.12.05 |
Spring - AutoWired (0) | 2024.11.27 |
Spring기본 (0) | 2024.11.26 |