Coder Social home page Coder Social logo

kotlin-openapi3-dsl's Introduction

kotlin-openapi3-dsl

Download Maven Central

Build your OpenApi3 spec in kotlin!

import

kotlin-openapi3-dsl is available on maven central

gradle

compile "cc.vileda:kotlin-openapi3-dsl:0.20.2"

maven

<dependency>
    <groupId>cc.vileda</groupId>
    <artifactId>kotlin-openapi3-dsl</artifactId>
    <version>0.20.2</version>
</dependency>

example

for a complete example look at the test

complete vertx.io example

import cc.vileda.openapi.dsl.*
import io.swagger.oas.models.parameters.Parameter
import io.swagger.oas.models.security.SecurityScheme
import io.vertx.core.Handler
import io.vertx.core.json.JsonObject.mapFrom
import io.vertx.kotlin.core.http.HttpServerOptions
import io.vertx.reactivex.core.Vertx
import io.vertx.reactivex.ext.web.Router
import io.vertx.reactivex.ext.web.api.contract.openapi3.OpenAPI3RouterFactory
import io.vertx.reactivex.ext.web.handler.CorsHandler

private val vertx = Vertx.vertx()

data class HelloResponse(
        val message: String
)

data class HelloRequest(
        val message: String
)

private val api3 = openapiDsl {
    info {
        title = "test api"
        version = "0.0.1"
    }

    components {
        schema<HelloResponse>()
        schema<HelloRequest>()
        securityScheme {
            name = "apiKey"
            type = SecurityScheme.Type.APIKEY
            `in` = SecurityScheme.In.HEADER
        }
    }

    security {
        put("apiKey", emptyList())
    }

    paths {
        path("/hello") {
            get {
                tags = listOf("without params")
                operationId = "hello"
                description = "hello get"
                parameter {
                    name = "id"
                    `in` = "query"
                    required = true
                    style = Parameter.StyleEnum.SIMPLE
                    schema<String>()
                }
                responses {
                    response("200") {
                        description = "a 200 response"
                        content {
                            mediaTypeRef<HelloResponse>("application/json") {
                                description = "Hello response"
                                example = HelloResponse("World")
                            }
                        }
                    }
                }
            }
            post {
                tags = listOf("without params")
                operationId = "postHello"
                description = "hello post"
                extension("x-stable", true)
                responses {
                    response("201") {
                        description = "created response"
                        requestBody {
                            content {
                                mediaTypeRef<HelloRequest>("application/json") {
                                    description = "Hello request"
                                    example(HelloRequest("World")) {
                                        description = "hello request"
                                    }
                                }
                            }
                        }
                        content {
                            mediaType<HelloResponse>("application/json") {
                                description = "Hello response"
                                example = HelloResponse("World")
                            }
                        }
                    }
                }
            }
        }
        path("/greetings") {
            get {
                tags = listOf("without params")
                operationId = "greetings"
                description = "greetings get"
                responses {
                    response("200"){
                        description = "a 200 response"
                        content {
                            mediaTypeArrayOfRef<HelloResponse>("application/json") {
                                description = "An array of HelloResponses"
                                example = HelloResponse("Greetings")
                            }
                        }
                    }
                }
            }
        }
    }
}

fun main(args: Array<String>) {
    val apiFile = api3.asFile()
    println(api3.asJson().toString(2))
    OpenAPI3RouterFactory.rxCreateRouterFactoryFromFile(vertx, apiFile.absolutePath)
            .doOnError { it.printStackTrace() }
            .doOnSuccess(::createOperationHandlers)
            .doOnSubscribe { println("Server started") }
            .subscribe(::startServer)
}

fun startServer(routerFactory: OpenAPI3RouterFactory) {
    val mainRouter = Router.router(vertx)
    bindAdditionalHandlers(mainRouter)
    mainRouter.mountSubRouter("/", routerFactory.router)
    val server = vertx.createHttpServer(HttpServerOptions(
            port = 8080,
            host = "localhost"))
    server.requestHandler({ mainRouter.accept(it) }).listen(8080)
}

fun bindAdditionalHandlers(router: Router) {
    val create = CorsHandler.create("^.*$")
            .allowedHeaders(setOf(
                    "Content-Type",
                    "apiKey"
            ))
    router.route().handler(create)

    router.get("/spec.json").handler { routingContext ->
        routingContext.response()
                .putHeader("Content-Type", "application/json")
                .end(api3.asJson().toString(2))
    }
}

private fun createOperationHandlers(routerFactory: OpenAPI3RouterFactory) {
    routerFactory.addSecurityHandler("apiKey", Handler {
        if (it.request().getHeader("apiKey") == "foo") it.next()
        else it.fail(401)
    })

    routerFactory.addHandlerByOperationId("postHello", { routingContext ->
        routingContext.response()
                .putHeader("Content-Type", "application/json")
                .end(mapFrom(HelloResponse("Hello World!")).encode())
    })

    routerFactory.addHandlerByOperationId("hello", { routingContext ->
        routingContext.response()
                .putHeader("Content-Type", "application/json")
                .end(mapFrom(HelloResponse("Hello World!")).encode())
    })

    routerFactory.addFailureHandlerByOperationId("hello", { routingContext ->
        println("FAIL")
        routingContext.fail(500)
    })
}

todo

  • Make compatible to vertx OpenAPI3RouterFactory
  • Implement all OpenApi3 fields
    • paths
      • all HTTP methods
      • minimal features
      • security features
      • complete features
      • requestBody
        • minimal features
        • examples
        • complete features
      • parameters
        • minimal features
        • complete features
    • components
    • $ref to components
  • Publish on bintray
  • Publish on jcenter
  • Publish on maven central

license

Copyright 2017 Tristan Leo

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

kotlin-openapi3-dsl's People

Contributors

derveloper avatar richardskg avatar travisagengler avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.