Skip to content

V2 Plugin Configuration

Lukas Ruegner edited this page Jun 2, 2024 · 2 revisions

When installing the plugin with install(SwaggerUI), sensible default values will be used and can be overwritten when required.

By default, the swagger-ui is available at "localhost:8080/swagger-ui" (assuming the application is running on localhost:8080).

Swagger

Configuration of the Swagger-UI itself

install(SwaggerUI) {
    swagger {
        automaticRouter = true
        forwardRoot = false
        swaggerUrl = "swagger-ui"
        rootHostPath = "/my-ktor-web-app"
        authentication = "MySwaggerAuth"
        withCredentials = true
        onlineSpecValidator()
        displayOperationId = true
        showTagFilterInput = true
        sort = SwaggerUiSort.HTTP_METHOD
        syntaxHighlight = SwaggerUiSyntaxHighlight.MONOKAI
    }
    //...
}
  • automaticRouter - whether to automatically configure routes for swagger-ui and apispec-json
  • forwardRoot - whether to forward the "/"-route to the swagger-ui
  • swaggerUrl - the url at which the swagger-ui is available
  • rootHostPath - the path under which the ktor-app is deployed. Can be useful if a reverse proxy is in use.
  • authentication - the name of the authentication method to use for the Swagger-UI and OpenApi-Spec
  • withCredentials - If set to true, enables passing credentials, in CORS requests that are sent by the browser (default false).
  • validatorUrl - Swagger UI can validate specs against an online validator. This option can be used to enable/disable the validation or supply an url to a custom validator. disableSpecValidator() to disable validation (=default), specValidator("myUrl") to point to a custom validator, onlineSpecValidator() to use the default swagger-ui validator (https://validator.swagger.io/validator)
  • displayOperationId - Whether to show the operation-id of endpoints in the list
  • showTagFilterInput - Whether the top bar will show an edit box that you can use to filter the tagged operations.
  • sort - Apply a sort to the operation list of each API
  • syntaxHighlight - Syntax coloring theme to use

Info

Metadata about the API. See the official OpenAPI Specification for further information.

install(SwaggerUI) {
    info {
        title = "Api"
        version = "latest"
        description = "My Api"
        termsOfService = "http://example.com/terms"
        contact {
            name = "API Support"
            url = "http://www.example.com/support"
            email = "support@example.com"
        }
        license {
            name = "Apache 2.0"
            url = "https://www.apache.org/licenses/LICENSE-2.0.html"
        }
    }
    //...
}

Servers

Connectivity information to any amount of target servers. See the official OpenAPI Specification for further information.

install(SwaggerUI) {
    server {
        url = "localhost:8080"
        description = "Development server"
    }
    server {
        url = "https://example.com/"
        description = "Example server"
    }
    //...
}

Security Schemes

The security mechanisms that can be used across the API. See the official OpenAPI Specification for further information.

install(SwaggerUI) {
    securityScheme("MyBasicAuth") {
        type = AuthType.HTTP
        scheme = AuthScheme.BASIC
    }
    securityScheme("MyJwtAuth") {
        type = AuthType.HTTP
        scheme = AuthScheme.BEARER
        bearerFormat = "jwt"
    }
    //...
}

Tags

Add additional information for tags.

install(SwaggerUI) {
    tag("MyTag1") {
        description = "My first tag"
        externalDocDescription = "Description of additional external documentation"
        externalDocUrl = "https://example.com/"
    }
    tag("MyTag2") {
        description = "My second tag"
        externalDocDescription = "Description of additional external documentation"
        externalDocUrl = "https://example.com/"
    }
    //...
}
  • tag("name") - the name of the tag to add the information to
  • description - a short description of the tag
  • externalDocDescription - a short description of the additional external documentation
  • externalDocUrl - the url to an additional external documentation

External Documentation

Add a reference to external documentation.

install(SwaggerUI) {
    externalDocs {
        url = "https://github.com/SMILEY4/ktor-swagger-ui/wiki"
        description = "Sample external documentation object"
    }
    //...
}
  • url - the url to an additional external documentation
  • description - a short description of the additional external documentation

Custom Schemas

Provide custom or remote schemas.

install(SwaggerUI) {
	customSchemas {
		json("customSchema1") {
            """{"type": "string"}"""
        }
        openApi("customSchema2") {
            Schema<Any>.apply {
                type = "string"
            }
        }
        remote("customSchema3", "example.com/schema")
	}
	//...
	includeAll = false
}
  • json("schemaId") - provide a schema as a json-string
  • openApi("schemaId") - provide a schema as an openapi Schema-instance
  • remote - provide a remote schema at the given url
  • includeAll - whether to include all custom schemas or only those directly references by any route

See Response Bodies for more information.

Encoding

install(SwaggerUI) {
    encoding {
        schemaEncoder { type ->
            SchemaGenerator(EncodingConfig.schemaGeneratorConfigBuilder().build())
                .generateSchema(type.javaType)
                .toPrettyString()
        }
        schemaDefinitionsField = "\$defs"
        exampleEncoder { type, example ->
            jacksonObjectMapper().writeValueAsString(example)
        }
    }
	//...
}

Customize or replace the default schema and example encoders

  • schemaEncoder - encode the given type as a json-schema-string
  • schemaDefinitionsField - the name of the field in the json-schema containing additional schema definitions
  • exampleEncoder - encode the given example value (of the given type) as a json-string

Others

Miscellaneous configuration

install(SwaggerUI) {
    defaultUnauthorizedResponse = {
        description = "Username or password invalid."
        // ...
    }
    defaultSecuritySchemeName = "MyBasicAuth"
    defaultSecuritySchemeNames = setOf("MyBasicAuth", "MyTokenAuth")
    generateTags { url -> listOf(url.firstOrNull()) }
    pathFilter = { method, url => url.firstOrNul() != "hidden" }
    ignoredRouteSelectors = listOf(MyIgnoredRouteSelector::class)
    spec("specName") {
        //...
    }
    whenBuildOpenApiSpecs = { openapiSpec -> ... }
    //...
}
  • defaultUnauthorizedResponse - the response-information for a "401 Unauthorized"-response to automatically add to each protected route - if not specified otherwise. See Responses for more information.
  • defaultSecuritySchemeName - The name of the security scheme to automatically use for each protected route - if not specified otherwise.
  • defaultSecuritySchemeNames - The name of the security schemes to automatically use for each protected route - if not specified otherwise.
  • generateTags - Takes the url of a route as a list (split at every "/") and returns tags for the route (null-elements are ignored).
  • pathFilter - Filter to apply to all routes. Return 'false' for routes to not include them in the OpenApi-Spec and Swagger-UI.
  • ignoredRouteSelectors - ktor route-selectors (and all their sub-classes) in this list are ignored in the route-urls
  • spec(specName) - used to customized individual openapi-specs and swagger-uis is multiple are present. The fill plugin-config can be accessed inside the block. The "top-level"-plugin-config serves as a base while inddividual fields can be overwritten inside this block.
  • whenBuildOpenApiSpecs - hook that is executed after the openapi-spec is generated. Allows for more customization of the final content.
Clone this wiki locally