Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 208
Kuldeep Jain Avatar asked Apr 02 '18 21:04

Kuldeep Jain


People also ask

What is a swagger definition file?

Swagger™ is a project used to describe and document RESTful APIs. The Swagger specification defines a set of files required to describe such an API. These files can then be used by the Swagger-UI project to display the API and Swagger-Codegen to generate clients in various languages.

What is swagger codegen CLI?

Swagger Codegen is an open source project which allows generation of API client libraries (SDK generation), server stubs, and documentation automatically from an OpenAPI Specification.

How do I hide a field in swagger?

We can use the hidden property of the annotation to hide a field in the definition of a model object in Swagger UI. In the above scenarios, we find that the id field is hidden for both GET and POST APIs.


1 Answers

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;
}
like image 76
Kuldeep Jain Avatar answered Oct 11 '22 13:10

Kuldeep Jain