๐ฉ๐ป๐ป๐
[250429] Spring Boot + Swagger๋ก API ๋ฌธ์ ์๋ํ
_silver
2025. 4. 29. 21:34
๐ฉ๐ป๐ป ์ค๋ ๋ชฉํ ๐ฉ๐ป๐ป
Spring Boot ํ๋ก์ ํธ์ Swagger(OpenAPI 3) ์ค์ ์ถ๊ฐํ์ฌ API ๋ฌธ์๋ฅผ ์๋ํํ๋ค.
Swagger๋ฅผ ์ค์ ํ๋ฉด ์๋ฒ ์ฝ๋๋ง์ผ๋ก๋ API ๋ฌธ์๋ฅผ ์ฝ๊ฒ ๊ด๋ฆฌํ ์ ์๊ณ ,
ํ๋ก ํธ์๋์ ํ์ ์ API ์คํ ๊ณต์ ๋ฐ ํ ์คํธ๊ฐ ํธ๋ฆฌํด์ง๋ค.
1. build.gradle ์์กด์ฑ ์ถ๊ฐ
dependencies {
// Swagger
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'
}
2. application.properties ์ค์
# Swagger ์ ์ URL ์ค์ (๊ธฐ๋ณธ๊ฐ์ด์ง๋ง ๋ช
์์ ์ผ๋ก ์ ์ธ)
springdoc.swagger-ui.path=/swagger-ui.html
3. ํจํค์ง ๊ตฌ์กฐ
src
โโโ main
โโโ java
โโโ global
โโโ config
โโโ SwaggerConfig.java
โ๏ธ global.config๋ ๊ณตํต ์ค์ (Spring Security, CORS, Swagger ๋ฑ)์ ๋ชจ์๋๋ ํจํค์ง๋ก ๊ตฌ์ฑํ๋ค.
4. SwaggerConfig ํด๋์ค ์์ฑ
package global.config;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI openAPI() {
// ์ฐ๋ฝ์ฒ ์ ๋ณด
Contact contact = new Contact()
.name("Baek Eunyeong")
.email("beunyeong.b@gmail.com");
// License ์ ๋ณด
License license = new License()
.name("Cookbot License")
.url("https://github ์ฃผ์ ์ถ๊ฐ ์์ ")
.url("๋ฐฐํฌ ์ฃผ์ ์ถ๊ฐ ์์ ");
// API ๋ฌธ์ ์ ๋ณด(ํ๋ก์ ํธ ์ ๋ชฉ, ํ๋ก์ ํธ ์ค๋ช
, Contact ๋ฐ License ์ ๋ณด ์ฐ๊ฒฐ)
Info info = new Info()
.version("v1.0")
.title("Cookbot API")
.description("์ถํ ํ๋ก์ ํธ ์ค๋ช
์ถ๊ฐ ์์ ")
.contact(contact)
.license(license);
final String securityScheme = "bearerAuth";
return new OpenAPI()
.info(info)
// ์ ์ฒด API์ ์ธ์ฆ ๋ฐฉ์ ์ ์ฉ (SecurityRequirement ๋ฑ๋ก)
.addSecurityItem(new SecurityRequirement().addList(securityScheme))
.components(new Components()
// JWT ๊ธฐ๋ฐ ์ธ์ฆ ์ค์ ์ถ๊ฐ
.addSecuritySchemes(securityScheme, new SecurityScheme()
.name(securityScheme)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}
}
5. Swagger URL ์ ์
http://localhost:8080/swagger-ui/index.html
6. Swagger ๋์ ์ ํ ๋น๊ต
| Before | After |
| Notion์ผ๋ก API ํ๋ํ๋ ์ง์ ์ ๋ ฅ | Swagger UI๋ก ๋ฌธ์ ์๋ํ |
| API ์์ ์ ๋ฌธ์๋ฅผ ๊ฐ๊ฐ ์์ | ์ฝ๋ ์์ ์ ์๋์ผ๋ก ๋ฐ์ |
| ํ ์คํธ์ Posman ๋ฐ๋ก ์ฌ์ฉ | Swagger์์ ๋ฐ๋ก ํ ์คํธ ๊ฐ๋ฅ |
| ์ํ์ฝ๋, ์ค๋ช , ์ธ์ฆ ์ง์ ํ์ดํ | ์ด๋ ธํ ์ด์ ๊ธฐ๋ฐ์ผ๋ก ์๋์ผ๋ก ๋ ธ์ถ |

7. ์ฐธ๊ณ ์๋ฃ