Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure Swagger javax validation Constraints on DTOs

Tags:

I'm using Swagger (1.5.8). I want my swagger.json definition to detect the javax.validation JSR-303 annotations on my DTOs, so that I can document my API's validation constraints.

I would expect a @Min annotation (like this example) would show something about the minimum value (44), but it does not.

@POST
@ApiOperation(value = "post", httpMethod = "POST")
public Response post(
        @QueryParam("id") @NotNull @Min(44) Integer id) {...}

The resulting swagger.json for this is:

"/foo": {
  "post": {
    "operationId": "post",
    ...
    "parameters": [
      {
        "in": "body",
        "name": "id",
        "description": "id",
        "required": false,
        "schema": {
          "type": "integer",
          "format": "int32"
        }
      }

Swagger has closed the pull request for this functionality, but I'm unclear where/how it is able to be consumed in the Swagger definition.

I want to be able to do things like:

FooController

@POST
public void postFoo(@Valid @RequestBody FooDTO fooDto) {...}

FooDTO

public class FooDTO {
    @NotNull
    @Size(min = 1, max = 100)
    private Integer myInt;
}

Desired/Expected swagger.json Output:

"FooDTO": {
  "type": "object",
  "required": [
    "myInt"
  ],
  "properties": {
    "myInt": {
      "type": "number",
      "format": "integer",
      "minimum": "1",
      "maximum": "100",
 ...

What's the preferred way to configure Swagger Modules/Plugins to enable things like ModelResolver and BeanValidator, so that they'll inspect the annotations on my DTO's?

like image 519
JJ Zabkar Avatar asked May 10 '16 17:05

JJ Zabkar


1 Answers

Latest, as of now, Swagger-Core version 1.5.19 perfectly supports this:

DTO object similar to this:

public class SampleDTO {

    @Min(value = 5)
    @Max(value = 10)
    @NotNull
    private Integer integer;

    @NotNull
    private String string;

    //...

}

Will generate swagger.json similar to this:

...

 "definitions" : {
    "SampleDTO" : {
      "type" : "object",
      "required" : [ "integer", "string" ],
      "properties" : {
        "integer" : {
          "type" : "integer",
          "format" : "int32",
          "minimum" : 5,
          "maximum" : 10
        },
        "string" : {
          "type" : "string"
        },

...
like image 168
Mikhail Kholodkov Avatar answered Sep 20 '22 03:09

Mikhail Kholodkov