swagger-core icon indicating copy to clipboard operation
swagger-core copied to clipboard

Setting example value 'null' to fields in json request body with @Schema, not "null" string without model converter

Open infomuscle opened this issue 1 year ago • 2 comments

Hello,

While I was making an API document, I struggled to set value of fields to 'null' in json request body. I used @Schema annotation because I was in spring boot and kotlin.

At first, I thought that setting "null" in an attribute like defaultValue or example would be helpful. But it showed "null" string. So I searched it on the Internet because I thought many people would have faced same issue with me. With help of Generative AI, I finally found that ModelConverter could solve my issue and solved it. Below is the way I solved.

@Configuration
class SwaggerConfiguration {
    @Bean
    fun customModelConverter(): CustomModelConverter {
        return CustomModelConverter()
    }

}

class CustomModelConverter : ModelConverter {
    override fun resolve(type: AnnotatedType, context: ModelConverterContext, chain: Iterator<ModelConverter>, ): Schema<*>? {
        var schema: Schema<*>? = null
        while (chain.hasNext()) {
            schema = chain.next().resolve(type, context, chain)
            if (schema.example == "null") {
                schema.example = null
            }
        }

        return schema
    }
}

But It seems that it can be solved in easier way. For example, in JUnit, @CSVSource can pass argument as null with nullValues attribute. Below is the sample code, which converts "null" string to null.

@CsvSource(value= {"null"}, nullValues={"null"})

Or it can be set to null if nullable is true and example is not defined.

I'm curious that this issue is being considered to be solved or many people are satisfied with using model converter or there is another way to handle it in easier.

Thank you.

infomuscle avatar Oct 25 '24 05:10 infomuscle

@infomuscle could you provide your code snippet from your code of using @Schema as this functionality should already exist?

ponelat avatar Nov 29 '24 12:11 ponelat

@ponelat hi, you mean sample code of @Schema to set null value? If so, I made a pull request #4794 and please refear the link https://github.com/swagger-api/swagger-core/pull/4794. Or if you didn't mean it, could you explain what you intended again? Thank you..

infomuscle avatar Dec 02 '24 05:12 infomuscle