[BUG] [KOTLIN] [CLIENT] Optional query parameters handled wrong
Created by: ghost
Bug Report Checklist
-
Have you provided a full/minimal spec to reproduce the issue? -
Have you validated the input using an OpenAPI validator (example)? -
What's the version of OpenAPI Generator used? -
Have you search for related issues/PRs? -
What's the actual output vs expected output? -
[Optional] Bounty to sponsor the fix (example)
Description
The code generation does not work properly for optional / nullable query parameters. The example below contains a REST resource with an optional query parameter. The generator produces a nullable type in the function signature - in this case here kotlin.Int?
- which is correct. But when building the localVariableQuery
the nullable type is not handled correctly:
fun resourcesGet(page: kotlin.Int?) : Unit {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mapOf("page" to listOf("$page"))
[...]
}
As you can see in the code snippet, the function arguments are directly embedded into a String
. When calling the method with page=null
, the String "null"
is sent to the server instead of simply omitting the query parameter. In this case the server will try to parse "null"
into a number which will probably not work and let the request fail.
openapi-generator version
I am using v4.0.3. Current code from master
seems to have same issue.
OpenAPI declaration file content or url
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "MyService"
},
"paths": {
"/resources": {
"get": {
"produces": [
"application/json",
"application/json;charset=UTF-8"
],
"parameters": [
{
"name": "page",
"in": "query",
"description": "Zero-based page number for paging (minimum 0).",
"required": false,
"type": "integer",
"default": 0,
"minimum": 0,
"exclusiveMinimum": false,
"format": "int32",
"allowEmptyValue": true,
"x-example": 0
}
],
"responses": {
"200": {
"description": "Success"
}
}
}
}
}
}
Command line used for generation
generate --generator-name kotlin --additional-properties enumPropertyNaming=original --additional-properties dateLibrary=java8
Steps to reproduce
- Use above JSON to generate a client (and a server)
- Use the generated client code to perform a request with function parameter
page=null
Related issues/PRs
Suggest a fix
As a workaround, I do a post-processing of the generated code: file.text.replaceAll('"([^"]*)" to listOf\\("[^"]*"\\)', '"$1" to if ($1 != null) listOf($1.toString()) else emptyList()')
This transforms mapOf("page" to listOf("$page"))
into mapOf("page" to if (page != null) listOf(page.toString()) else emptyList())
This is more a hack than a real solution. It would be better to put the optional/nullable parameters into the localVariableQuery
variable only if they are not null.