티스토리 뷰
지난 시간에는 Springdoc을 사용하는 한 사이클에 대해서 봤다면 이번시간에는 어떻게 상세하게 내가 원하는대로 설정을 할 수 있는지에 대해서 알아보겠다.
OpenAPI 설정
지난시간에 application.yml 파일에 springdoc을 설정한 부분이다.
springdoc:
swagger-ui:
path: animal.html
version: v1
paths-to-match:
- /bear/**
- /dog/**
여기에 나온 내용들은 문서 맨 아래의 참고에 있는 properties 표에서 내가 원하는 속성을 찾아서 설정을 해줄 수 있다.
springdoc에서 샘플로 제공한 application.yml 의 모습은 다음과 같다. (일반적으로 사용할거라고 예상하여 샘플을 만들었으므로 거의 이 모습에서 크게 다르게 사용될것 같지는 않다.)
springdoc:
version: '@springdoc.version@'
api-docs:
groups:
enabled: true
swagger-ui:
path: /swagger-ui.html
display-request-duration: true
groups-order: DESC
operationsSorter: method
disable-swagger-default-url: true
show-actuator: true
group-configs:
- group: stores
paths-to-match: /store/**
- group: users
packages-to-scan: org.springdoc.demo.app2
OpenAPI Annotation
swagger 2 annotations과 swagger 3 annotations의 차이는 아래와 같다. 우리가 다루고 있는 Springdoc은 swagger 3 annotation을 사용하고 있다.
annotation들은 어떻게 사용하는지 알아보자. (swagger 2 annotations 참조)
swagger 3 annotations | swagger 2 annotations | desc |
@Tag | @Api | 클래스를 Swagger 리소스로 표시 |
@Parameter(hidden = true) or @Operation(hidden = true) or @Hidden | @ApiIgnore | API 작업에서 단일 매개 변수를 나타냄 |
@Parameter | @ApiImplicitParam | API 작업에서 단일 매개 변수를 나타냄 |
@Parameters | @ApiImplicitParams | API 작업에서 복수 매개 변수를 나타냄 |
@Schema | @ApiModel | Swagger 모델에 대한 추가 정보를 제공 |
@Schema(accessMode = READ_ONLY) | @ApiModelProperty(hidden = true) | 모델 속성의 데이터를 추가하고 조작 |
@Schema | @ApiModelProperty | Swagger 모델에 대한 추가 정보를 제공 |
@Operation(summary = "foo", description = "bar") | @ApiOperation(value = "foo", notes = "bar") | 특정 경로에 대한 작업 또는 일반적으로 HTTP 메서드를 설명 |
@Parameter | @ApiParam | 작업 매개 변수에 대한 추가 메타 데이터를 추가 |
@ApiResponse(responseCode = "404", description = "foo") | @ApiResponse(code = 404, message = "foo") | 작업의 가능한 응답을 설명 |
이를 활용한 Controller의 샘플은 다음과 같다.
@Slf4j
@RequestMapping("/bear")
@RestController
@Tag(name = "bear controller", description = "bear controller desc")
public class BearController {
@Operation(summary = "bear eat method", description = "bear eat method description", tags = { "contact" })
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "successful operation",
content = @Content(array = @ArraySchema(schema = @Schema(implementation = Contact.class)))) })
@GetMapping("/eat")
public Json<List<BearVo>> eatSomething(@Parameter(description="bear food") String food) {
log.debug("The bear is eating.");
return null;
}
@PostMapping("/sleep")
public Json<List<BearVo>> sleeping(@Parameter(description="bear sleep") String time) {
log.debug("The bear is sleeping");
return null;
}
}
여기에 쓰인 @Tag, @Operation, @ApiResponses, @Parameter, @Schema 등의 정보를 위의 표와 매핑시켜 이해를 하는 것보다는 swagger-ui를 통해 확인을 하면 더욱 쉽게 이해를 할 수 있다.
Swagger-UI 를 통한 확인
Controller 클래스와 method에 각각 @Tag, @Operation 로 작성했던 부분을 확인할 수 있다.
/bear/eat 이라는 get method를 클릭해 보겠다.
여기에서는 @ApiResponses, @Parameter 등에 설정했던 내용들이 들어가 있는것을 확인할 수 있다.
API를 할 RestController에 이런 식으로 OpenAPI를 활용하여 만들어 놓으면 Swagger-ui 를 통해 편리하게 관리할 수 있다.
참고 #1. Springdoc-openapi Properties
Parameter |
Default Value |
Description |
springdoc.api-docs.path |
/v3/api-docs |
String, For custom path of the OpenAPI documentation in Json format. |
springdoc.api-docs.enabled |
true |
Boolean. To disable the springdoc-openapi endpoint (/v3/api-docs by default). |
springdoc.packages-to-scan |
* |
List of Strings.The list of packages to scan (comma separated) |
springdoc.paths-to-match |
/* |
List of Strings.The list of paths to match (comma separated) |
springdoc.produces-to-match |
/* |
List of Strings.The list of produces mediaTypes to match (comma separated) |
springdoc.headers-to-match |
/* |
List of Strings.The list of headers to match (comma separated) |
springdoc.consumes-to-match |
/* |
List of Strings.The list of consumes mediaTypes to match (comma separated) |
springdoc.paths-to-exclude |
|
List of Strings.The list of paths to exclude (comma separated) |
springdoc.packages-to-exclude |
|
List of Strings.The list of packages to exclude (comma separated) |
springdoc.default-consumes-media-type |
application/json |
String. The default consumes media type. |
springdoc.default-produces-media-type |
/ |
String.The default produces media type. |
springdoc.cache.disabled |
false |
Boolean. To disable the springdoc-openapi cache of the the calculated OpenAPI. |
springdoc.show-actuator |
false |
Boolean. To display the actuator endpoints. |
springdoc.auto-tag-classes |
true |
Boolean. To disable the springdoc-openapi automatic tags. |
springdoc.model-and-view-allowed |
false |
Boolean. To allow RestControllers with ModelAndView return to appear in the OpenAPI description. |
springdoc.override-with-generic-response |
true |
Boolean. When true, automatically adds @ControllerAdvice responses to all the generated responses. |
springdoc.api-docs.groups.enabled |
true |
Boolean. To disable the springdoc-openapi groups. |
springdoc.group-configs[0].group |
|
String.The group name |
springdoc.group-configs[0].packages-to-scan |
* |
List of Strings.The list of packages to scan for a group (comma separated) |
springdoc.group-configs[0].paths-to-match |
/* |
List of Strings.The list of paths to match for a group(comma separated) |
springdoc.group-configs[0].paths-to-exclude |
`` |
List of Strings.The list of paths to exclude for a group(comma separated) |
springdoc.group-configs[0].packages-to-exclude |
|
List of Strings.The list of packages to exclude for a group(comma separated) |
springdoc.group-configs[0].produces-to-match |
/* |
List of Strings.The list of produces mediaTypes to match (comma separated) |
springdoc.group-configs[0].consumes-to-match |
/* |
List of Strings.The list of consumes mediaTypes to match (comma separated) |
springdoc.group-configs[0].headers-to-match |
/* |
List of Strings.The list of headers to match (comma separated) |
springdoc.webjars.prefix |
/webjars |
String, To change the webjars prefix that is visible the URL of swagger-ui for spring-webflux. |
springdoc.api-docs.resolve-schema-properties |
false |
Boolean. To enable property resolver on @Schema (name, title and description). |
springdoc.remove-broken-reference-definitions |
true |
Boolean. To disable removal of broken reference definitions. |
springdoc.writer-with-default-pretty-printer |
false |
Boolean. To enable pretty print of the OpenApi specification. |
springdoc.model-converters. deprecating-converter.enabled |
true |
Boolean. To disable deprecating model converter. |
springdoc.use-fqn |
false |
Boolean. To enable fully qualified names. |
springdoc.show-login-endpoint |
false |
Boolean. To make spring security login-endpoint visible. |
springdoc.pre-loading-enabled |
false |
Boolean. Pre-loading setting to load OpenAPI on application startup. |
springdoc.writer-with-order-by-keys |
false |
Boolean. Enable a deterministic/alphabetical orderding. |
springdoc.use-management-port |
false |
Boolean. To expose the swagger-ui on the actuator management port. |
출처 : springdoc.org/#properties
참고 #2. swagger-ui properties
Parameter |
Default Value |
Description |
springdoc.swagger-ui.path |
/swagger-ui.html |
String, For custom path of the swagger-ui HTML documentation. |
springdoc.swagger-ui.enabled |
true |
Boolean. To disable the swagger-ui endpoint (/swagger-ui.html by default). |
springdoc.swagger-ui.configUrl |
/v3/api-docs/swagger-config |
String. URL to fetch external configuration document from. |
springdoc.swagger-ui.layout |
BaseLayout |
String. The name of a component available via the plugin system to use as the top-level layout for Swagger UI. |
springdoc.swagger-ui.validatorUrl |
null |
By default, Swagger UI attempts to validate specs against swagger.io’s online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators Validator Badge. Setting it to null will disable validation. |
springdoc.swagger-ui.filter |
false |
Boolean OR String. If set, enables filtering. The top bar will show an edit box that you can use to filter the tagged operations that are shown. Can be Boolean to enable or disable, or a string, in which case filtering will be enabled using that string as the filter expression. Filtering is case sensitive matching the filter expression anywhere inside the tag. |
springdoc.swagger-ui.operationsSorter |
|
Function=(a ⇒ a). Apply a sort to the operation list of each API. It can be 'alpha' (sort by paths alphanumerically), 'method' (sort by HTTP method) or a function (see Array.prototype.sort() to know how sort function works). Default is the order returned by the server unchanged. |
springdoc.swagger-ui.tagsSorter |
|
Function=(a ⇒ a). Apply a sort to the tag list of each API. It can be 'alpha' (sort by paths alphanumerically) or a function see Array.prototype.sort() to learn how to write a sort function). Two tag name strings are passed to the sorter for each pass. Default is the order determined by Swagger UI. |
springdoc.swagger-ui.oauth2RedirectUrl |
/swagger-ui/oauth2-redirect.html |
String. OAuth redirect URL. |
springdoc.swagger-ui.displayOperationId |
false |
Boolean. Controls the display of operationId in operations list. The default is false. |
springdoc.swagger-ui.displayRequestDuration |
false |
Boolean. Controls the display of the request duration (in milliseconds) for "Try it out" requests. |
springdoc.swagger-ui.deepLinking |
false |
Boolean. If set to true, enables deep linking for tags and operations. See the [Deep Linking documentation](/docs/usage/deep-linking.md) for more information. |
springdoc.swagger-ui.defaultModelsExpandDepth |
1 |
Number. The default expansion depth for models (set to -1 completely hide the models). |
springdoc.swagger-ui.defaultModelExpandDepth |
1 |
Number. The default expansion depth for the model on the model-example section. |
springdoc.swagger-ui.defaultModelRendering |
|
String=["example"*, "model"]. Controls how the model is shown when the API is first rendered. (The user can always switch the rendering for a given model by clicking the 'Model' and 'Example Value' links.) |
springdoc.swagger-ui.docExpansion |
|
String=["list"*, "full", "none"]. Controls the default expansion setting for the operations and tags. It can be 'list' (expands only the tags), 'full' (expands the tags and operations) or 'none' (expands nothing). |
springdoc.swagger-ui.maxDisplayedTags |
|
Number. If set, limits the number of tagged operations displayed to at most this many. The default is to show all operations. |
springdoc.swagger-ui.showExtensions |
false |
Boolean. Controls the display of vendor extension (x-) fields and values for Operations, Parameters, and Schema. |
springdoc.swagger-ui.url |
|
String.To configure, the path of a custom OpenAPI file . Will be ignored if urls is used. |
springdoc.swagger-ui.showCommonExtensions |
false |
Boolean. Controls the display of extensions (pattern, maxLength, minLength, maximum, minimum) fields and values for Parameters. |
springdoc.swagger-ui.supportedSubmitMethods |
|
Array=["get", "put", "post", "delete", "options", "head", "patch", "trace"]. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display. |
springdoc.swagger-ui.display-query-params-without-oauth2 |
false |
Boolean. To enable access to swagger-ui using url query params instead of configUrl. If the REST APIs, are not using OAuth2 (Available if groups are not enabled. Prevents the load of the swagger-config twice with configUrl, available since v1.4.1). |
springdoc.swagger-ui.display-query-params |
false |
Boolean. To enable access to swagger-ui using url query params instead of configUrl. If the REST APIs, are using OAuth2 (Available if groups are not enabled. Prevents the load of the swagger-config twice with configUrl, available since v1.4.1). |
springdoc.swagger-ui.oauth. additionalQueryStringParams |
|
String. Additional query parameters added to authorizationUrl and tokenUrl. |
springdoc.swagger-ui.disable-swagger-default-url |
false |
Boolean. To disable the swagger-ui default petstore url. (Available since v1.4.1). |
springdoc.swagger-ui.urls[0].url |
|
URL. The url of the swagger group, used by Topbar plugin. URLs must be unique among all items in this array, since they’re used as identifiers. |
springdoc.swagger-ui.urls[0].name |
|
String. The name of the swagger group, used by Topbar plugin. Names must be unique among all items in this array, since they’re used as identifiers. |
springdoc.swagger-ui.urlsPrimaryName |
|
String. The name of the swagger group which will be displayed when Swagger UI loads. |
springdoc.swagger-ui.oauth.clientId |
|
String. Default clientId. MUST be a string. |
springdoc.swagger-ui.oauth.clientSecret |
|
String. Default clientSecret. Never use this parameter in your production environment. It exposes crucial security information. This feature is intended for dev/test environments only. |
springdoc.swagger-ui.oauth.realm |
|
String. realm query parameter (for OAuth 1) added to authorizationUrl and tokenUrl. |
springdoc.swagger-ui.oauth.appName |
|
String. OAuth application name, displayed in authorization popup. |
springdoc.swagger-ui.oauth.scopeSeparator |
|
String. OAuth scope separator for passing scopes, encoded before calling, default value is a space (encoded value %20). |
springdoc.swagger-ui.csrf.enabled |
false |
Boolean. To enable CSRF support |
springdoc.swagger-ui.csrf.cookie-name |
XSRF-TOKEN |
String. Optional CSRF, to set the CSRF cookie name. |
springdoc.swagger-ui.csrf.header-name |
X-XSRF-TOKEN |
String. Optional CSRF, to set the CSRF header name. |
springdoc.swagger-ui.syntaxHighlight.activated |
true |
Boolean. Whether syntax highlighting should be activated or not. |
springdoc.swagger-ui.syntaxHighlight.theme |
agate |
String. String=["agate"*, "arta", "monokai", "nord", "obsidian", "tomorrow-night"]. Highlight.js syntax coloring theme to use. (Only these 6 styles are available.) |
springdoc.swagger-ui.oauth. useBasicAuthentication WithAccessCodeGrant |
false |
Boolean. Only activated for the accessCode flow. During the authorization_code request to the tokenUrl, pass the Client Password using the HTTP Basic Authentication scheme (Authorization header with Basic base64encode(client_id + client_secret)). |
springdoc.swagger-ui.oauth. usePkceWithAuthorization CodeGrant |
false |
Boolean.Only applies to authorizatonCode flows. Proof Key for Code Exchange brings enhanced security for OAuth public clients. |
springdoc.swagger-ui.persistAuthorization |
false |
Boolean. If set to true, it persists authorization data and it would not be lost on browser close/refresh |
출처 : springdoc.org/#properties
끝!
'Framework > Spring' 카테고리의 다른 글
Openfeign 사용시 IllegalStateException: Method has too many Body parameters 오류 조치 (0) | 2021.03.02 |
---|---|
Cannot deserialize instance of `java.io.File` out of START_OBJECT token 오류 조치 (0) | 2021.02.25 |
Springboot에서 API Docs (Springdoc) 사용하는 방법 (1) (0) | 2021.02.18 |
spring-boot-starter, parent 로 dependency 관리하기 (0) | 2021.02.10 |
Spring Validation Message properties 파일을 통해 관리하기 (2) | 2021.02.09 |