Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Provides Ktor Swagger support

NotificationsYou must be signed in to change notification settings

Olexandr88/ktor-docs-plugin

 
 

Repository files navigation

Test and Publish to SonarType

This plugin implements a plug and play solution for generating OpenAPI (Swagger) specification for your Ktor server on any platform with minimal effort - no need to modify your existing code, no special DSL wrappers etc.Just annotate your route(s) definitions with@GenerateOpenApi andopenapi.yaml will be generated at build time.

Take a look at theSample Project to get started.

How to apply the plugin

plugins {    id("io.github.tabilzad.ktor-docs-plugin-gradle") version"0.6.2-alpha"}swagger {    documentation {        docsTitle="Ktor Server Title"        docsDescription="Ktor Server Description"        docsVersion="1.0"        generateRequestSchemas=true        hideTransientFields=true        hidePrivateAndInternalFields=true        deriveFieldRequirementFromTypeNullability=true    }    pluginOptions {        format="yaml"// or json    }}

Supported Features

FeatureisSupportedtype
Path/Endpoint definitionsAutomatic
Ktor ResourcesAutomatic
Request SchemasAutomatic
Response SchemasExplicit
Endpoint/Scheme DescriptionsExplicit
Endpoint TaggingExplicit

Plugin Configuration

Documentation options

OptionDefault ValueExplanation
docsTitle"Open API Specification"Title for the API specification that is generated
docsDescription"Generated using Ktor Docs Plugin"A brief description for the generated API specification
docsVersion"1.0.0"Specifies the version for the generated API specification
generateRequestSchemastrueDetermines if request body schemas should
be automatically resolved and included
hideTransientFieldstrueControls whether fields marked with@Transient
are omitted in schema outputs
hidePrivateAndInternalFieldstrueOpts to exclude fields withprivate orinternal modifiers from schema outputs
deriveFieldRequirementFromTypeNullabilitytrueAutomatically derive object fields' requirement from its type nullability
serversemptyList of server URLs to be included in the spec (ex:listOf("http://localhost:8080")

Plugin options

OptionDefault ValueExplanation
enabledtrueEnable/Disables the plugin
saveInBuildtrueDecides if the generated specification file should
be saved in thebuild/ directory
formatyamlThe chosen format for the OpenAPI specification
(options: json/yaml)
filePath$modulePath/build/resources/main/openapi/The designated absolute path for saving
the generated specification file

How to use the plugin

Generating endpoint specifications

Annotate the specific route definitions you want the OpenAPI specification to be generated for.

@GenerateOpenApifun Route.ordersRouting() {    route("/v1") {        post("/order1") {/*...*/        }    }}

You could also annotate the entireApplication module with multiple/nested route definitions. The plugin willrecursively visit eachRoute. extension and generate its documentation.

@GenerateOpenApifun Application.ordersModule() {    routing {        routeOne()        routeTwo()    }}fun Route.routeOne() {    route("/v1") {/*...*/ }}fun Route.routeTwo() {    route("/v2") {/*...*/ }    routeThree()}

Endpoint and field descriptions

Describe endpoints or schema fields.

data classRequestSample(    @KtorFieldDescription("this is a string")valstring:String,valint:Int,valdouble:Double)@GenerateOpenApifun Route.ordersRouting() {    route("/v1") {        @KtorDescription(            summary="Create Order",            description="This endpoint will create an order",        )        post("/create") {            call.receive<RequestSample>()        }        route("/orders") {            @KtorDescription(                summary="All Orders",                description="This endpoint will return a list of all orders"            )            get {/*...*/ }        }    }}

Responses

Defining response schemas and their corresponding HTTP status codes are done via@KtorResponds annotation on an endpoint.

@GenerateOpenApifun Route.ordersRouting() {    route("/v1") {        @KtorResponds(               [ResponseEntry("200",Order::class, description="Created order"),ResponseEntry("400",ErrorResponseSample::class, description="Invalid order payload")               ]        )        post("/create") {/*...*/ }        @KtorResponds([ResponseEntry("200",Order::class, isCollection=true, description="All orders")])        get("/orders") {/*...*/ }    }}

Tagging

Using tags enables the categorization of individual endpoints into designated groups.Tags specified at the parent route will propogate down to all endpoints contained within it.

@Tag(["Orders"])fun Route.ordersRouting() {    route("/v1") {        post("/create") {/*...*/ }        get("/orders") {/*...*/ }    }    route("/v2") {        post("/create") {/*...*/ }        get("/orders") {/*...*/ }    }}

On the other hand, if the tags are specified with@KtorDescription or@Tag annotation on an endpoint, they are associated exclusively with that particular endpoint.

@GenerateOpenApifun Route.ordersRouting() {    route("/v1") {        @KtorDescription(tags= ["Order Operations"])        post("/order") {/*...*/ }        @Tag(["Cart Operations"])        get("/cart") {/*...*/ }    }}

Planned Features

  • Automatic Response resolution
  • Support for polymorphic types with discriminators
  • Option for an automatic tag resolution from module/route function declaration
  • Tag descriptions
  • Parsing kdocs for schema/property descriptions

Sample Specification

sample

About

Provides Ktor Swagger support

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Kotlin100.0%

[8]ページ先頭

©2009-2025 Movatter.jp