0
votes

I have an API that I'm trying to document using Swagger. My API takes a POJO as input via JSON in the RequestBody, and returns, likewise, a POJO as JSON in the ResponseBody. Some of the fields in my JSON object are nullable, and others are required. I would like my Swagger documentation to reflect which fields are nullable and which are required. Is there a way to do this simply, without creating a Swagger config file which would likely be longer than manually documenting the API in a text editor?

As a concrete example, let's say I have a POJO that looks like this:

public class pojo {
    private String val1;
    private String val2;
    private String val3;
    //getters, setters, constructors, etc.
}

Let's say I wanted my Swagger documentation to tell the reader: "On request, do not send val1 (e.g. this API is a database insert and val1 corresponds to the PK of the table which is supposed to be auto-generated), val2 is optional, and val3 is required". How do I do this?

As a related question, how can I do something similar for the response body? Like, using the POJO above, how can I say "on response, you should expect val1 to be empty, val2 might have a value or might be null, and val3 should have a value, assuming the service was successful"?

1

1 Answers

2
votes

In order to document optional parameters within your POJO object it is possible to use the @ApiModelProperty attribute, for example:

public class pojo {
    @ApiModelProperty(value = "This parameter will be ignored", required = false)
    private String val1;
    @ApiModelProperty(value = "This parameter is optional", required = false)
    private String val2;
    @ApiModelProperty(required = true)
    private String val3;
    //getters, setters, constructors, etc.
}

Swagger will take these annotations into account and it should be reflected in the documentation:

Swagger UI

And in yaml API documentation:

pojo:
    type: object
    required:
      - val3
    properties:
      val1:
        type: string
        description: This parameter will be ignored
      val2:
        type: string
        description: This parameter is optional
      val3:
        type: string