papsign / Ktor-OpenAPI-Generator

Ktor OpenAPI/Swagger 3 Generator
Apache License 2.0
241 stars 42 forks source link

Multiple responses #6

Closed Globegitter closed 4 years ago

Globegitter commented 4 years ago

Another thing I just ran into and I am not sure on how to specify, what if my endpoint has different types it can return and multiple response codes?

Top be precise for that endpoint we return data class ErrorResponse(val message: String) in cases where we return a 400, 404 and 500 status but not sure how I can define that.

Further when we may return a 201 with en empty response. How can this all be defined? It is not quite clear to me from the existing examples.

Wicpar commented 4 years ago

use the throws route selector:


                throws(APIException.apiException(HttpStatusCode.BadRequest) {it: Exception -> 
                    ExceptionDescriptionDTO(it)
                }) {
                    ...
                }

this will catch and respond the exception, and create the appropriate descriptions.

you can also declare them globally if you use the ktor status pages:


            val api = install(OpenAPIGen)  { ... }
...
            // StatusPage interop, can also define exceptions per-route
            install(StatusPages) {
                withAPI(api) {
                    exception<JsonMappingException, Error>(HttpStatusCode.BadRequest) {
                        it.printStackTrace()
                        Error("mapping.json", it.localizedMessage)
                    }
                    exception<ProperException, Error>(HttpStatusCode.BadRequest) {
                        it.printStackTrace()
                        Error(it.id, it.localizedMessage)
                    }
                }
            }
Globegitter commented 4 years ago

Ah cool, thanks for the examples. The first thing that came to my mind and I tried was again using sealed classes so e.g. having

sealed class MyResponses

@Response("An NotFound error response", 404)
data class NotFoundResponse(val message: String): MyResponses()

@Response("Response when request was a success", 201)
object Created: MyResponses()

but this has some drawbacks in itself and what you just posted is more than sufficient for now thanks.

Wicpar commented 4 years ago

@Request and @Response only work on the reified type you declare, subclasses are not analyzed, and at runtime no reflection occurs.

Globegitter commented 4 years ago

@Wicpar One more question - how can I provide examples for the error responses in the StatusPages integration?