nielsfalk / ktor-swagger Goto Github PK
View Code? Open in Web Editor NEWLicense: Apache License 2.0
License: Apache License 2.0
This project started as a POC by @nielsfalk. It was further fleshed out by me as a functional library to support software that I was building at a previous company. I am no longer working for that company.
I'm currently merging PRs that are well-tested with unit tests. However, there are no active maintainers of this project. This project is mostly self-serve.
This project is very much an example of "open source is 'free', as in 'free puppy'".
Releases are currently handled by JitPack.
Hi,
i was working on a project with ktor 1.3.1, and would love to try out this swagger library, but i am getting this runtime error as below:
java.lang.NoSuchMethodError: io.ktor.client.call.TypeInfo.<init>(Lkotlin/reflect/KClass;Ljava/lang/reflect/Type;)V
the reason seems to be that since the Ktor migration to 1.3.0, it has a breaking change: No binary compatibility with 1.2.x. (See: https://ktor.io/quickstart/migration/1.3.0.html), so is it possible for you to recompile the project to the current Ktor version? Thanks!
Hello,
Today I learned about defining securitySchemes
(step 1 in https://swagger.io/docs/specification/authentication/):
openApi = OpenApi().apply {
...
components.securitySchemes["BearerAuth"] = mapOf(
"type" to "http",
"scheme" to "bearer"
)
// paths["/corporations"]["security"] = Operation.create(...)
...
}
How can I apply security (step 2) to a path (e.g. "/corporations")?
Thanks
Hello,
I've been fiddling with the project to see if it is a viable tool for my project, and I've come across a somewhat odd issue: The link to the openapi.json is not defined in the swagger-ui page.
How would i go about doing that?
I'm trying to add a list request to the Swagger documentation, so what I did was
get<something>(
"all".responds(ok<Collection<Something>>())
) {
call.respond(somethingService.list())
}
Here, somethingService.list()
returns a Collection<Something>
. But this doesn't work, it throws an exception:
Exception in thread "main" java.lang.IllegalArgumentException: invalid number of type parameters specified: expected 0, got 1
at de.nielsfalk.ktor.swagger.SwaggerParameterizedTypeKt.parameterize(SwaggerParameterizedType.kt:19)
Am I missing something, or is this not (yet) supported? The pet store example seems to sidestep this problem by wrapping the list responses in an object, I want to avoid this method, and just return a JSON array of objects.
Hi,
First of all, this is a very useful project! Thanks for sharing this with the world. I hope this will make it into the Ktor mainline code base in the near future.
Unfortunately, I keep running into errors on the Swagger UI page when I use ktor-swagger in my project. Whenever I click on any of the operation buttons to expand a specific operation ("GET", "POST", etc), errors appear on the top of the Swagger UI page with multiple error messages such as these:
Errors
Resolver error at paths./pets.post.responses.200.schema.properties.id.$ref
$ref: must be a string (JSON-Ref)
Resolver error at paths./pets.post.responses.200.schema.properties.name.$ref
$ref: must be a string (JSON-Ref)
Also, under each parameter name, the following error is shown (including the emoji):
😱 Could not render ParameterRow, see the console.
See also the attached screenshot.
I've tried both the example in the README of this project and the example code you posted in this thread: ktorio/ktor#453
In both cases, I got these errors.
I have tried Googling these error messages, but I couldn't find any useful information about it. I have no idea what I'm doing wrong. Should this library and/or Swagger be responsible for generating the proper $ref fields in the JSON output?
By the way, I'm using ktor-swagger with the latest currently available version of Ktor, which is currently 1.1.3. Could that perhaps have something to do with it? Also, I'm using Jackson 2.9.8 for content negotiation.
Thank you for any help you could provide.
A patch-operation should be implemented to support documentation of patch-operations.
Maybe something like this?
@ContextDsl
inline fun <reified LOCATION : Any, reified ENTITY : Any> Route.patch(
metadata: Metadata,
noinline body: suspend PipelineContext<Unit, ApplicationCall>.(LOCATION, ENTITY) -> Unit
): Route {
application.swaggerUi.apply {
metadata.apply<LOCATION, ENTITY>(HttpMethod.Patch)
}
return patch<LOCATION> {
body(this, it, call.receive())
}
}
Hello, how i can implement authorizations to generated page?
Now "Available authorizations" window is empty
I'd love to use this at my company, however, to do so you'd need to license this under a permissive license (something like Apache, BDS, or MIT). Would you be so kind as to add a License.txt file to this repository?
It would be great if you could publish your ktor-swagger
artefact on maven central so it can be used by other people much easier.
We are making use of moshi and com.ryanharter.ktor:ktor-moshi
, so we have
...
val moshi = Moshi.Builder()
.add(LocalDateTimeJsonAdapter())
.add(OffsetDateTimeJsonAdapter())
.add(KotlinJsonAdapterFactory())
.add(HexIntegerJsonAdapter())
.build()
install(ContentNegotiation) {
moshi(moshi)
}
...
and when I start up the server I get an empty openapi.json
file. But if I change it to e.g. gson
everything seems to work as expected. Any idea why that could be?
I found the lib doesn't work with genrtics type.
for example:
data class Result<T>(
val code: Int = 0,
val data: T? = null
)
// after definition of
ok<Result<String>>()
// it calls
internal fun parameterize(raw: Class<*>, vararg typeArguments: Type): ParameterizedType {
val useOwner: Type? = if (raw.enclosingClass == null) {
// no owner allowed for top-level
null
} else {
raw.enclosingClass
}
require(raw.typeParameters.size == typeArguments.size) {
"invalid number of type parameters specified: expected ${raw.typeParameters.size}, got ${typeArguments.size}"
}
@Suppress("UNCHECKED_CAST")
return ParameterizedTypeImpl(raw, useOwner, typeArguments as Array<Type>)
}
when handling: val code: Int,
1st parameter raw: Class<*>
is kotlin.Int
2nd parameter vararg typeArguments: Type
is the same with the typeParameters of reified type Result<String>
, which is String.
Now that kotlin.Int
has empty typeParameter, require(raw.typeParameters.size == typeArguments.size)
is false and it throws an exception
I'm not farmiliar with this project and I don't know why it has to parameterize val code: Int
with typeParameters of reified type Result<String>
, and what the purpose of the require
statement is.
Anyway, after I delete the require
statement, it works well with generics type.
function parameterize
is under SwaggerParameterizedType.kt file.
It would be nice if one could create a request like:
put<location, String>(...)
Where the object type is a string. This would set the content-type to text/plain as well.
Using something like JitPack will significantly reduce the overhead for maintainers.
Latest version of this library uses Ktor 1.3.2 which it's getting from jcenter (with all the associated issues that's causing these days). I realise this isn't being maintained but just in case anyone is planning on updating dependencies?
Why when I use OpenApi.json I must declare all model examples manually and when I use Swagger.json all examples are already declared automatically
Since this project is gaining a bit of popularity and might be used on a publicly facing website, we should validate the security of this library. In particular:
It would be good if someone could validate that we don't have any path traversal vulnerabilities that would allow an attacker to exfiltrate files from the webserver that they shouldn't have access to.
The particular lines of concern are these:
When this is validated, it's important to do so on both a Windows and Unix OS.
Since the path separators in Uninx and Windows are different, some path traversal vulnerabilities will only ever exist on windows.
The signature of the io.ktor.client.call.TypeInfo class was changed in KTor 1.3, from
data class TypeInfo(val type: KClass<*>, val reifiedType: Type)
to
data class TypeInfo(
val type: KClass<*>,
val reifiedType: Type,
val kotlinType: KType? = null
)
As a result, when running 0.6.0 on Ktor 1.3+ you will get this runtime error when calling anything which reads class metadata for Json:
java.lang.NoSuchMethodError: io.ktor.client.call.TypeInfo.<init>(Lkotlin/reflect/KClass;Ljava/lang/reflect/Type;)V
The solution would probably be to do a new release compiled against Ktor 1.3.
Can I integrate this library to project with Structured Handling of HTTP Requests ?
Is there a way to specify the basePath or server. Once you host this behind an api gateway, api calls from swagger lacking the base path. Can display the swagger gui with no issues, by setting forwardRoot
to false
apigateway route is:
http://{apigatewayhost}/xxx
forwards to http://{swaggerhost}
end point is
http://{swaggerhost}/users
you would want swagger to call:
http://{apigatewayhost}/xxx/users
which would forward to http://{swaggerhost}/users
but it calls
http://{apigatewayhost}/users
so it fails. I believe, basePath setup can fix this
thanks in advance...
I am able to test get methods (via curl and swagger client) with no issues. but post method never parse the json body. Always returns HTTP 415 Unsupported Media error.
@Group("Debug Group") @Location("/RefData/Xceptor/v1/findIspreadByIdList/x") class testLocation()
post<testLocation, TestModel>("find Ispread by Id(s)".responds(ok<InterceptorClientResponse>()).header<Header>().examples(example("body", TestModel.exampleBody, summary = "Map of name and age"))){ _ , postBody->
...}
class TestModel(val name : String, val age: String ){
companion object {
val exampleBody = mapOf(
"Alex" to "25"
)
}
body:
{
"name":"Alex",
"age":"25"
}
Thanks in advance..
Add support for file uploads via multipart/form-data body.
使用你的方法配置后,发现authorizations 无法正常使用,请问要如何在Swagger正常使用
I have generated in swagger web-site openapi.json and openapi.yaml is it possible not to generate schemas from code and to replace it with static path to this files ??
Hello,
Is it possible to add Authorization key to the header?
Is there a way to add and example values for parameters?
Currently I have this Paramenters Class:
class QueryParameter(@DefaultValue("2019") @Description("Maximum released year") val yearMax: Int?)
And my swagger Ui is like this:
I don't want a "default value", but actually an example that auto populate the field when trying the endpoint. Is it possible to add an example value to a parameter?
My project is already using json from kotlinx.serialization, both for ContentNegotiation as well for some other purposes, and not jackson or gson. Is it possible to use ktor-swagger in this case?
Right now I'm getting
[ERROR] 2020-09-29 12:44:31.387 [nioEventLoopGroup-4-1] Application - Unhandled: GET - /apidocs/openapi.json - {}
kotlinx.serialization.SerializationException: Serializer for class 'OpenApi' is not found.
Mark the class as @Serializable or provide the serializer explicitly.
and I wonder if there is any easy solution for that
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.