Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data annotations in Swagger

Tags:

I am using ASP.NET and Swagger that exposes a complex type that accepts a POST. It has a number of string fields that have different restricted lengths. How can I reflect that in the Swagger UI?

like image 256
illug Avatar asked Feb 23 '16 14:02

illug


People also ask

How do you add annotations in Swagger?

Step 1: Open the User. java and add @ApiModel annotation just above the class name. Add the description about the User model. @ApiModel: It provides additional information about Swagger Models.

What is @API annotation in Swagger?

Annotation Type Api. @Target(value=TYPE) @Retention(value=RUNTIME) @Inherited public @interface Api. Marks a class as a Swagger resource. By default, Swagger-Core will only include and introspect only classes that are annotated with @Api and will ignore other resources (JAX-RS endpoints, Servlets and so on).

What is the use of @operation annotation?

@Operation. The annotation may be used to define a resource method as an OpenAPI Operation, and/or to define additional properties for the Operation.


1 Answers

You can annotate the properties with the StringLengthAttribute from System.ComponentModel.DataAnnotations.

For instance:

[StringLength(10)] public String Name {get;set;} 

will become:

"name": {     "minLength": 0,     "maxLength": 10,     "type": "string" } 

And this:

[StringLength(10, MinimumLength = 5)] public String Name {get;set;} 

becomes:

"name": {     "minLength": 5,     "maxLength": 10,     "type": "string" } 

Besides StringLength Swashbuckle also supports the Range and RegularExpression attributes.

Update

MaxLength does not work. StringLength does. However, discovering this information in Swagger UI is a bit clumsy. You have to navigate to the Model of your object and then hover over the property:

How to discover max length info

like image 140
venerik Avatar answered Oct 20 '22 23:10

venerik