Kuldeep Jain
Kuldeep Jain

Reputation: 8598

Swagger-codegen enforcement of "required" fields in Definitions

I have these fields marked as required in my yaml file (swagger spec)

  MyType:
    type: object
    required:
      - name
      - amount

I am using swagger codegen maven plugin with these configurations:

<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>2.2.3</version>

<language>spring</language>
<library>spring-mvc</library> 

I would like to have required fields in spec to be made required in the generated classes as well. But that is not happening currently.

Are there configuration options to do that? I have <useBeanValidation>true</useBeanValidation> but this does not seem to work for me.

I saw a similar request enforcement of "required" fields in Definitions on Swagger-codegen GitHub page where suggestion was to use useBeanValidation and I do have it but it still does not work.

Created this request on Swagger-codegen GitHub page: Swagger-codegen enforcement of “required” fields in generated model classes

Upvotes: 9

Views: 4669

Answers (1)

Kuldeep Jain
Kuldeep Jain

Reputation: 8598

Found the solution. It was actually my mistake; I was expecting the field in the generated class to be marked required. It is rather the getter method which is annotated with @NonNull and required = true which solves the purpose. And now with the validation in place, I am able to see the validation is triggered and showing the message Amount should be present when amount is not passed in the request payload.

@ApiModelProperty(required = true, value = "Amount should be present")
@NotNull
public Amount getAmount() {
    return amount;
}

Upvotes: 3

Related Questions