# SpringDoc

## SpringDoc

{% embed url="<https://springdoc.org/>" %}

**`springdoc-openapi`**&#xB294; Spring Boot 프로젝트의 문서를 자동으로 생성하는 자바 라이브러리이다. **Swagger-UI**를 기반으로 하며, <mark style="color:blue;">`application.properties`</mark> 또는 <mark style="color:blue;">`application.yml`</mark>을 통해 간단한 설정으로 사용이 가능하다는 장점이 있다.

<div align="left"><figure><img src="/files/gd4cZCXJG0AasLJOJosY" alt=""><figcaption></figcaption></figure></div>

## 의존성 추가

Maven Repository에서 springdoc 의존성을 찾아 pom.xml 또는 build.gradle에 추가한다.

작성 시점(2022-11-11) 기준 최신 버전은 <mark style="color:red;">**1.16.12**</mark>이다.

### maven

```markup
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.6.12</version>
</dependency>
```

### gradle

```groovy
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.12'
```

## Spring Boot 설정

<mark style="color:blue;">**`application.properties`**</mark> 또는 <mark style="color:blue;">**`application.yml`**</mark> 파일에 다음과 같이 springdoc 설정을 작성한다.

```properties
# OAS(Open Api Service) setting
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.packages-to-scan=com.hacademy.app.controller
```

* springdoc.swagger-ui.path - swagger ui 접속  페이지 주소 (기본값 `/swagger-ui/index.html`)
* springdoc.packages-to-scan - 문서화할 패키지 경로

설정에 대한 상세 정보는 다음 링크에서 확인할 수 있다.

{% embed url="<https://springdoc.org/properties.html>" %}

실행하면 다음과 같은 페이지를 확인할 수 있다.

<div align="left"><figure><img src="/files/knKmEZaheDRetFiPMVD5" alt=""><figcaption></figcaption></figure></div>

## 데모

공식 사이트에서 제공하는 데모 페이지는 다음 링크에서 확인할 수 있다.

{% embed url="<https://springdoc.org/#springdoc-applications-demos>" %}

## 문서 정보 설정

표시되는 문서의 정보를 설정하기 위해서 필요한 설정은 다음과 같다.

```java
@OpenAPIDefinition(
	info = @Info(
		title = "API 제목",
		description = "API 상세 설명",
		version = "API 버전 정보"
	)
)
@Configuration
public class RestAPIConfiguration {

}
```

<mark style="color:red;">`@Configuration`</mark>을 생성하고 <mark style="color:red;">`@OpenApiDefinition`</mark>을 통해 문서의 정보를 설정한다. <mark style="color:red;">`@Info`</mark>에 설정하는 정보는 다음과 같다.

* title - API 문서의 최상단 제목
* description - 제목 아래 적힐 설명
* version - 문서의 버전(통상적으로 v로 시작하며 major, minor, release 버전을 기재)
* contact - 연락처 정보
* license - 라이선스 정보
* extensions - 확장 목록 (<https://swagger.io/docs/specification/2-0/swagger-extensions/>)
* termsOfService - 이용 약관 정보

## 컨트롤러 명세 설정

컨트롤러 클래스의 표시 이름을 <mark style="color:red;">`@Tag`</mark> 설정으로 변경한다. 같은 태그는 같은그룹으로 표시된다.

```java
@Tag(name = "포켓몬스터 컨트롤러")
@RestController
public class PocketMonsterController {

}
```

<div><figure><img src="/files/9KLlJV7axQllJRP227xB" alt=""><figcaption><p>@Tag 적용 전</p></figcaption></figure> <figure><img src="/files/WVTvIlQVjTtnzE8UcUty" alt=""><figcaption><p>@Tag 적용 후</p></figcaption></figure></div>

## 매핑 명세 설정&#x20;

매핑에 대한 명세 설정은 `@Operation`설정으로 변경한다.

```java
@Operation(
    summary = "포켓몬 상세",
    description = "포켓몬 상세",
    responses = {
        @ApiResponse(
            responseCode = "200", 
            content = @Content(
                mediaType = "application/json",
                array = @ArraySchema(
                    schema = @Schema(
                        implementation = PocketMonsterDto.class
                    )
                )
            )    
        ),
        @ApiResponse(
            responseCode = "404", 
            content = @Content(
                mediaType = "text/plain",
                schema = @Schema(implementation = String.class),
                examples = {
                    @ExampleObject(value="not found")
                }
            )
        ),
        @ApiResponse(
            responseCode = "500", 
            content = @Content(
                mediaType = "text/plain",
                schema = @Schema(implementation = String.class),
                examples = {
                    @ExampleObject(value="server error")
                }
            )
        )
    }
)
@GetMapping("/pocketmon/{no}")
public PocketMonsterDto find(
                @Parameter(description = "포켓몬 번호")
                @PathVariable int no) {
    return dao.find(no);
}
```

* <mark style="color:red;">**`@Operation`**</mark> - 작업 설명
  * summary - 요약 설명
  * description - 상세 설명
  * responses - 응답 설정 (<mark style="color:red;">**`@ApiResponse`**</mark>)
    * responseCode - 응답 상태 코드
    * content - 응답 데이터 형태 (<mark style="color:red;">**`@Content`**</mark>)
      * mediaType - 응답 데이터 Content-Type
      * schema - 응답 객체의 형태(단일 객체인 경우) (<mark style="color:red;">**`@Schema`**</mark>)
      * arraySchema - 응답 객체 배열의 형태(배열 혹은 리스트인 경우) (<mark style="color:red;">**`@ArraySchema`**</mark>)
      * examples - 응답 객체 예시 (<mark style="color:red;">**`@ExampleObject`**</mark>)
* <mark style="color:red;">**`@Parameter`**</mark> - 파라미터 설명
  * description - 설명&#x20;
  * example - 응답 객체 예시 (<mark style="color:red;">**`@ExampleObject`**</mark>)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.sysout.co.kr/web/back-end/openapi-swagger/springdoc.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
