ktor-swagger-ui icon indicating copy to clipboard operation
ktor-swagger-ui copied to clipboard

Properties defined as non-nullable with a default value are still marked as required in the swagger schema

Open vincentburesi-es opened this issue 6 months ago • 2 comments

As said in the title, I have looked into the code up to io.github.smiley4.schemakenerator.reflection.steps.ReflectionTypeProcessingStep#parseProperty

    private fun parseProperty(
        member: KProperty<*>,
        resolvedTypeParameters: Map<String, TypeParameterData>,
        typeData: MutableList<BaseTypeData>
    ): PropertyData {
        return PropertyData(
            name = member.name,
            type = resolveMemberType(member.returnType, resolvedTypeParameters, typeData).id,
            nullable = member.returnType.isMarkedNullable, // <-- This definition here
            annotations = parseAnnotations(member).toMutableList(),
            kind = PropertyType.PROPERTY,
            visibility = determinePropertyVisibility(member)
        )
    }

and its usage in io.github.smiley4.schemakenerator.swagger.steps.SwaggerSchemaGenerationStep#buildObjectSchema

    private fun buildObjectSchema(typeData: ObjectTypeData, typeDataList: Collection<BaseTypeData>): SwaggerSchema {

        val requiredProperties = mutableSetOf<String>()
        val propertySchemas = mutableMapOf<String, Schema<*>>()

        collectMembers(typeData, typeDataList).forEach { member ->
            propertySchemas[member.name] = schema.referenceSchema(member.type)
            if (!member.nullable) { // <-- Used here to define the property as required
                requiredProperties.add(member.name)
            }
        }

        return SwaggerSchema(
            swagger = schema.objectSchema(propertySchemas, requiredProperties),
            typeData = typeData
        )
    }

So there seem to be no distinction between the notions of "nullable" and "required" in the PropertyData class. It would be great to have a distinct "required" boolean field that takes into account non-nullable fields with default values such as :

data class MyClass(
    val myField: Int = 42
)

vincentburesi-es avatar Jul 31 '24 08:07 vincentburesi-es